9am

What’s the Number

In Programming on September 4, 2010 at 3:45 pm
/*
Given a telephone number like 4156434531, get all possible names that would match it.
e.g. If the number is 23, the names could be “ad”, “bd”, “cd”, “ae” etc..
*/
This non recursive implementation does not use a queue/stack to simulate recursion either.
namespace AlphaNumerics
{
public static class TelNumber
{
private static char[][] KeyChars = new char[10][];
static TelNumber()
{
KeyChars[0] = new char[]{‘+’};
KeyChars[1] = new char[]{‘ ‘};
KeyChars[2] = new char[]{‘a’,’b’,’c’};
KeyChars[3] = new char[]{‘d’,’e’,’f’};
KeyChars[4] = new char[]{‘g’,’h’,’i’};
}
public static void GetCombinations(int[] tel_no)
{
int[] digits = new int[tel_no.Length];
while(true)
{
Print(digits, tel_no);
if (!Increment(digits, tel_no)) break;
}
}
public static bool Increment(int[] digits, int[] tel_no)
{
int i = 0;
bool overflow = false;
for (; i < digits.Length; i++)
{
digits[i] = (digits[i] + 1) % KeyChars[tel_no[i]].Length;
if (digits[i] != 0) { overflow = false; break; }
else overflow = true;
}
return !overflow;
}
public static void Print(int[] digits, int[] tel_no)
{
for (int i = 0; i < tel_no.Length; i++)
{
System.Console.Write(KeyChars[tel_no[i]][digits[i]]);
}
System.Console.WriteLine();
}
}
}
Advertisements

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

%d bloggers like this: