Sunday, September 27, 2009

print all word combinations from phone number

Print all words combinations from phone number.
ex: 111-1111 -> AAA-AAAA, AAA-AAAB ... CCC-CCCC

char charkeyMap(int digit, int position)
ex:
charkeyMap(1, 0) = 'A'
charkeyMap(1, 1) = 'B'
charkeyMap(1, 2) = 'C'

void printCombinations(int[] in):
    char[] out = new char[in.length]
    
    //first combination ex: 111-1111 -> AAA-AAAA
    for(int i = in.length -1; i >= 0; i--):
        out[i] = charkeyMap(in[i], 0)

    int i = 0
    while (i >= 0):
        out.print()
        i = in.length - 1;
        
        while (i >= 0):
            //if A then B
            if out[i] == charkeyMap(in[i], 0):
                out[i] = charkeyMap(in[i], 1)
                break
            
            //if B then C
            if out[i] == charkeyMap(in[i], 1):
                out[i] = charkeyMap(in[i], 2)
                break
            
            //if C then A and let it loop for the adjacent digit
            if out[i] == charkeyMap(in[i], 2):
                out[i] = charkeyMap(in[i], 0)
                //let it loop
                i--
        

No comments: