Web Toolbar by Wibiya

Pages

Sunday, January 15, 2012

Print all the possible strings a telephone number can represent.

Solution #1: The below code doesn't take into account the fact that keys 7 and 9 represent 4 alphabets and also it just prints ' ' and '+' for key 1 and 0 respectively. The code is just to explain the logic for printing the combinations and additional logic can be added to handle these cases. Here is the code,

char digitToChar(char x, int index)
{
    char ch;

    switch(x)
    {
        case '0':
            ch = '+'; break;
        case '1':
            ch = ' '; break;
        case '2':
            ch = "abc"[index]; break;
        case '3':
            ch = "def"[index]; break;
        case '4':
            ch = "ghi"[index]; break;
        case '5':
            ch = "jkl"[index]; break;
        case '6':
            ch = "mno"[index]; break;
        case '7':
            ch = "pqrs"[index]; break;
        case '8':
            ch = "tuv"[index]; break;
        case '9':
            ch = "wxyz"[index]; break;
        default:
            ch = ' ';

    }

    return ch;
}

void printAll(char* num, char* arr, int len, int x)
{
    int i=0;

    if(x == len)
    {
        printf("%s\n", arr);
        return;
    }

    for(i=0; i<3; i++)
    {
        arr[x] = digitToChar(num[x], i);
        printAll(num, arr, len, x+1);
    }
}

int main()
{
    char* num = "8017393450";
    char arr[20] = {0,};

    printAll(num, arr, 10, 0);

    return 0;
}

2 comments:

Abhishek said...
This comment has been removed by the author.
Abhishek said...

Hi Suchit ,
Nice set of questions !

The code does not print "zzz" if 999 is given as input so I tweaked a bit in the switch case and the for loop so this takes care of everything . Please comment if there are any issues.

I just added a space in the switch case and loop from 0 to 4

char digitToChar(char x, int index)
{
char ch;

switch(x)
{
case '0':
ch = '+'; break;
case '1':
ch = ' '; break;
case '2':
ch = "abc "[index]; break;
case '3':
ch = "def "[index]; break;
case '4':
ch = "ghi "[index]; break;
case '5':
ch = "jkl "[index]; break;
case '6':
ch = "mno "[index]; break;
case '7':
ch = "pqrs"[index]; break;
case '8':
ch = "tuv "[index]; break;
case '9':
ch = "wxyz"[index]; break;
default:
ch = ' ';

}

return ch;
}

void printAll(char* num, char* arr, int len, int x)
{
int i=0;

if(x == len)
{
printf("%s\n", arr);
return;
}

for(i=0; i<4; i++)
{
if(digitToChar(num[x], i) != ' ')
{
arr[x] = digitToChar(num[x], i);
printAll(num, arr, len, x+1);
}
// printAll(num, arr, len, x+1);
}
}

int main()
{
char* num = "9999";
char arr[20] = {0,};

printAll(num,arr,4,0);

return 0;
}