Thursday, August 12, 2010

Interview Questions

I was asked to come up with a rather simple function during a phone interview a little while ago. Since it was over the phone, and i'm completely spoiled by my IDE, I made a pretty lame attempt at it, and completely failed. Having no visual feedback didn't help much either.

In any case, the interviewer asked me to come up with a function that will take a string of characters and return back the telephone keypad numeric equivalent. I actually sat down at my IDE and banged this bit of code out. I think it handle all cases, and fulfills the request.... Too bad it's a little too late to get that job.

using System;
using System.Collections;
using System.Text;

namespace PhoneLetters
{
class Program
{
static void Main(string[] args)
{
//returns "2223334"
Console.WriteLine(getNumbers("ABCDEFG"));

//returns "222-3334"
Console.WriteLine(getNumbers("ABC-DEFG"));

//returns "1-222-33134"
Console.WriteLine(getNumbers("1-ABC-DE1FG"));

//returns "222-33134&"
Console.WriteLine(getNumbers("ABC-DE1FG&"));
}

static string getNumbers(string letters)
{
StringBuilder sb = new StringBuilder();
foreach (char c in letters.ToUpper())
{
switch (c)
{
case 'A':
case 'B':
case 'C':
sb.Append("2");
break;
case 'D':
case 'E':
case 'F':
sb.Append("3");
break;
case 'G':
case 'H':
case 'I':
sb.Append("4");
break;
case 'J':
case 'K':
case 'L':
sb.Append("5");
break;
case 'M':
case 'N':
case 'O':
sb.Append("6");
break;
case 'P':
case 'Q':
case 'R':
case 'S':
sb.Append("7");
break;
case 'T':
case 'U':
case 'V':
sb.Append("8");
break;
case 'W':
case 'X':
case 'Y':
case 'Z':
sb.Append("9");
break;
default:
sb.Append(c);
break;
}
}
return sb.ToString();
}
}
}

While I understand what interviewers are trying to do, I find it very difficult to whip up code on demand on a white board or over the phone for these made up problems. I guess i should go practice writing code to made up problems without the help of a computer so i can better handle these situations where i need to be able to show that i can indeed write some halfway decent code when i have access to my tools.