How can I print out all possible letter combinations a given phone number can represent?

前端 未结 30 2208
逝去的感伤
逝去的感伤 2020-12-22 18:01

I just tried for my first programming interview and one of the questions was to write a program that given a 7 digit telephone number, could print all possible combinations

30条回答
  •  轮回少年
    2020-12-22 18:50

    Here is one for pain C. This one is likley not efficet (in fact I don't think it is at all). But there are some intresting aspects to it.

    1. It take a number and converts it into a string
    2. It just raises the seed number once each time to create the next sequential string

    Whats nice about this is that there is no real limit to the size of the string (no character limit) This allows you to generate longer and longer strings if need be just by waiting.

    #include 
    #include 
    
    #define CHARACTER_RANGE 95  //  The range of valid password characters
    #define CHARACTER_OFFSET 32 //  The offset of the first valid character
    
    void main(int argc, char *argv[], char *env[])
    {
        int i;
    
        long int string;
        long int worker;
        char *guess;    //  Current Generation
        guess = (char*)malloc(1);   //  Allocate it so free doesn't fail
    
        int cur;
    
        for ( string = 0; ; string++ )
        {
            worker = string;
    
            free(guess);
            guess = (char*)malloc((string/CHARACTER_RANGE+1)*sizeof(char)); //  Alocate for the number of characters we will need
    
            for ( i = 0; worker > 0 && i < string/CHARACTER_RANGE + 1; i++ )    //  Work out the string
            {
                cur = worker % CHARACTER_RANGE; //  Take off the last digit
                worker = (worker - cur) / CHARACTER_RANGE;  //  Advance the digits
                cur += CHARACTER_OFFSET;
    
                guess[i] = cur;
            }
            guess[i+1] = '\0';  //  NULL terminate our string
    
            printf("%s\t%d\n", guess, string);
        }
    }
    

提交回复
热议问题