Skip to main content

HACKER Edition pset1

How I come to tackle the hacker Edition of pset one...

My comments might not be that straight forward but feel free to comment.

I opted not to use the string class for the return type for the longToString() because I was getting issues when trying to do the conversion in the calculation for the digits.

#################################################################################

   #include <stdio.h>
   #include<cs50.h>
   #include <string.h>
   //method to get number of digis input but the user
   int lengthString(long long int cc);
   //Function to check the if the length is a valid length to proceed
   bool isValidLength(int numOfDigits);
   //Fuction that will use Luhns algorithim to check validity
   bool isValid(int numOfDigits, long long int cc);
   //Function that returns the card type
   int cardType(int numOfDigits, long long int cc);
   //function that converts the card to char array
   char* longToString(int numOfDigits, long long int cc);
   //function that will add two number
   int addDigits(int num, int numOfDigits);
   //function to display cardName
   void cardName(int num);
   int main (void)
   {
     //stores the credit card value
     long long int creditCard = 0;
     //string s = "";
     int numberOfDigits = 0; // stores the number of digits that the user input
     do
     {
       printf("Number: ");
       creditCard = GetLongLong();
     }while(creditCard < 0);
     //getting the number of digit that the user input
     numberOfDigits = lengthString(creditCard);
     //checking if its valid lengthwise
     bool checkLength = isValidLength(numberOfDigits);
     if(checkLength == true) //if true  
     {
       int result = cardType(numberOfDigits, creditCard); //check the card typep
       if(result == 404)
       {
         printf("INVALID");
         printf("\n");
       }
       else //if cardType not null
       {
         bool checkValidity = isValid(numberOfDigits, creditCard); // check validity
         if(checkValidity == true)// if valid print cardType
         {
           cardName(result);
         }
         else // if invalid
         {
           printf("INVALID");
           printf("\n");
         }
       }
     }
     else
     {
       printf("INVALID");
       printf("\n");
     }
   }
   //function to get number of digits
   int lengthString(long long int cc)
   {
     long long int quotient = cc; //assigning quotient to the creditcard number
     int counter = 0;  // counter for the number of digits  
     //loop through the number dividing by ten till the quotient is zero
     while(quotient >0)
     {
       quotient = quotient / 10;  
       counter ++;  
     };  
     //return the number of digits
     return counter;
   }
   /*
    Checking to see if the card length is valid. No need to proceed forward  
    when the length is not of a valid type
   */
   bool isValidLength(int numOfDigits)
   {
     if(numOfDigits >= 13 &&
       numOfDigits <= 16 )
       {
         return true;
       }
       else
       {
         return false;
       }
   }
   /*
     converts the digits to a char array
   */
   char* longToString(int numberOfDigits, long long int cc)
   {
     static char* stringCC; //static char pointer for array
     stringCC = (char*)calloc(numberOfDigits,sizeof(char)); // creating a dynamic array
     sprintf(stringCC, "%lld",cc); //populating char array with digits
     return stringCC;
   }
   /*
     This function checks the card type are returns a string with the card type.
     If its not valid it returns NULL
   */
   int cardType(int numOfDigits, long long int cc)
   {
     char * stringCC;
     stringCC = longToString(numOfDigits, cc);
     //checking of American Express cards have 15 digits. Start with 34, 36
     if( numOfDigits == 15 && stringCC[0] == '3'  
       && (*(stringCC + 0) == '4' || *(stringCC + 1) =='5' || *(stringCC + 1) =='6' || *(stringCC + 1) =='7'))
     {
       return 0; //AMEX
     }
     //checking for mastercard length = 16 numbers start with 51, 52, 53, 54, 55
     else if( numOfDigits == 16 && *(stringCC + 0) == '5' &&  
         (*(stringCC + 1) == '1' ||*(stringCC + 1) =='2' || *(stringCC + 1)=='3' || *(stringCC + 1) =='4' || *(stringCC + 1) =='5'))
     {
       return 1; //MASTERCARD
     }
     //checking for visa number of digits 13, 16 start with 4
     else if( (numOfDigits >= 13 && numOfDigits <= 16) && *(stringCC + 0) == '4')
     {
       return 2; //VISA
     }
     //returns NULL if the none of the above is true
     else
     {
       return 404;
     }
   }
   /*
     This function will check the card using the Luhns algorithm. This functions only runs if all  
     the basic checks for card type have been passed.
   */
   bool isValid(int numOfDigits, long long int cc)
   {
     char * input = longToString(numOfDigits, cc);
     int sum = 0; //variable to hold the sum to the digits
     for(int i = 0, j = (numOfDigits - 1); i < numOfDigits; i++, j--)
     {
       if(i % 2 == 1) // adds the even number
       {
         int partialSum = ((input[j] - '0') * 2); //calculate partial sum
         if(partialSum > 9) // if partial sum is greater than 9
         {
           partialSum = addDigits(partialSum, 2); // add the digits to the partial sum
         }
         sum += partialSum ; //add partial sum to total sum
       }
       else // adds the odd numbers
       {
         sum += (input[j] - '0');  
       }
     }
     if ( sum % 10 == 0)
     {
       return true;
     }
     else
     {
       return false;
     }
   }
   /*
     This function will add digits together
   */
   int addDigits(int num, int numOfDigits)
   {
     char charArray[numOfDigits]; // create the char array
     sprintf(charArray, "%i", num); // populate the char array
     int sum = 0;
     for(int i = 0; i < numOfDigits; i++)
     {
      sum = sum + ( charArray[i] - '0' );
     }
      return sum; // returning the sum
   }
   /*
     This function displays the card name
   */
   void cardName(int num)
   {
     switch(num)
     {
       case 0:
         printf("AMEX");
         printf("\n");
         break;
       case 1:
         printf("MASTERCARD");
         printf("\n");
         break;
        default:
         printf("VISA");
         printf("\n");
         break;
     }
   }



#################################################################################
here is how I tackled the second mario problem

 #include<stdio.h>  
 #include<string.h>  
 #include<cs50.h>  
 //function used to print the spaces  
 void printSpace(int num);  
 //function used to print hash symbols  
 void printHash(int num);  
 int main()  
 {  
   int input = 0; //variable to hold the value the user enters  
   do  
   {  
     printf("Height: ");  
     input = GetInt();  
   }while(input < 0 || input > 23);  
   //looping through to create the structure    
   for(int i = 1; i <= input; i++)  
   {  
     printSpace(input - i); //add spaces  
     printHash(i); //add symbols  
   }  
 }  
 /*  
   THis function will be used to print the number of spaces before the symbols  
 */  
 void printSpace(int num)  
 {  
   for(int i = 0; i < num; i++)  
   {  
     printf(" ");  
   }  
 }  
 /*  
   THis function will be used to print the symbols of spaces before the symbols  
 */  
 void printHash(int num)  
 {  
   for(int i = 0; i < num; i++)  
   {  
     printf("#");  
   }  
   printf(" ");  
   for(int i = 0; i < num; i++)  
   {  
     printf("#");  
   }  
   printf("\n");  
 }  

Comments

Popular posts from this blog

Installing libssl1.0 on Ubuntu 22.04

Following the upgrade of distro from 20.04 to 22.04 the libssl packages got affected, this ended up causing my vpn client to fail. The client kept opening and closing immediately.  on futher investigation I found the issue as the libssl client. Attached is a screenshot of the message I was getting when I tries starting it from the terminal. Tring to install libsll1.0-dev from apt was generating the following error: Due to this installing the package was not viable via the regular way, I really didn't want to downgrade back to 20.04 as this could have meant a clean installation, and I had just come from doing that, as the upgrade wasn't successful, but I still needed to try out the new 22.04 features. Google been my best friend finally come through after a long search on how to install libssl1.0-dev. I ended up landing on this link  , here they gave some instruction on how to install libss1.0-dev. Below are the steps of installing libssl1.0-dev on ubuntu 22.04 for backward compa

Creating PDF in MVC 5 using ITextSharp

Creating PDF in MVC 5 using ITextSharp For a long time I have been looking for free and cheaper ways of creating pdf documents within MVC. I have tried all the other options and none was able to give me the standard of document I wanted. After long and tiresome nights of trying to figure out the solution I stumbled upon ItextSharp... This was my life changer. Maybe it might be for you too..  Process Download ItextSharp using the Nuget Package manager and if you prefer using command line arguments you an use: Install-Package iTextSharp full documentation to this can be retrieved here Create a class that will be used to write the data you created as a byte array. How this works can be found here  or here   public class BinaryResult : ActionResult { private byte[] _fileBinary; private string _contentType; private string _fileName; public BinaryResult(byte[] fileBinary, string contentType, string fileName) { _fileBinary = f

Converting DateTime C# to DateTime.UTC javascript

Here is a simple way to change a C# datetime to a javascript Datetime.UTC value that can be used in the highcharts pointstart field. In C# private double DateUTCDate(DateTime date) { return date.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds } This will return a value that can be used directly in javascript series: { pointStart: dataFromCsharp, pointInterval: 3600 * 1000 // one day } highcharts pointstart only used Date.UTC values if you are timestamp for the x-axis