telephone books

package algorithm;

public class PhoneBook
{
    // static array initialization
    public static final char[][] PHONEKEY = {
                {'0', '0', '0'},
                {'1', '1', '1'},
                {'a', 'b', 'c'},
                {'d', 'e', 'f'},
                {'g', 'h', 'i'},
                {'j', 'k', 'l'},
                {'m', 'n', 'o'},
                {'p', 'r', 's'},
                {'t', 'u', 'v'},
                {'w', 'x', 'y' }
                };
    private static final int KEYCHARS = 3;
    public static void printPhoneNumbers( int number )
    {
        if( number > Integer.MAX_VALUE )
        {
            System.out.println( "input is invalid" );
        }
        StringBuilder sb = new StringBuilder( Integer.toString( number ) );
        StringBuilder result = new StringBuilder( );
        printCombinations( sb, result, 0 );
    }
    public static void printCombinations( StringBuilder sb, StringBuilder result, int start )
    {
        if( start <= sb.length( ) - 1 )
        {
            char temp = sb.charAt( start );
            for( int i = 0; i < KEYCHARS; i++ )
            {
                String s = Character.toString(temp);
                int num = Integer.parseInt( s );
                result.append( PHONEKEY[num][i] );
                printCombinations( sb, result, start + 1 );
            }
        }   
        if( start == sb.length( ))
        {
            System.out.println( result.toString( ) );
            return;
        }
    }

    /**
     * @param args
     */
    public static void main( String[] args )
    {
        printPhoneNumbers( 67 );

    }

}

Advertisements
This entry was posted in interview and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s