Phone Screen Questions


I love codinghorror.com. Jeff now works for Vertigo, which hires some damned good developers. They are the ones who coded the memorabilia app for Hard Rock (Silverlight 2.0). But I digress. Here are some of the questions he states are mandatory in his blog.

Write a function to reverse a string. There are many ways to do this, but in C#, a character array is one of the easiest. I will have to think whether or not this is the "best" way, but this would work.

public static string ReverseString(string input)
{
    char[] ary = input.ToCharArray();
    StringBuilder builder = new StringBuilder();

    for(int i = (ary.Length - 1); i >= 0; i--)
       builder.Append(ary[i]);

    return builder.ToString();
}

Of course, I could have returned an array here, as well. If so, I could have run the loop forward or backwards, as long as I kept the proper order for each array

public static string ReverseString(string input)
{
    char[] ary = input.ToCharArray();
    char[] ary2 = new char[ary.Length];
    int len = ary.Length - 1;

    for(int i = 0;i<ary.Length;i++,len--)
    {
        ary2[len] = ary[i];
    }

    return new string(ary2);
}

Or, what if we wanted to get really tricky and only use one array. Now that would be fun. Not impossible, however, as we can bitshift.

public static string ReverseString(string input)
{
    char[] ary = input.ToCharArray();
    int len = ary.Length - 1;

    for(int i = 0;i<len;i++,len--)
    {
        ary[i] ^= ary[len];
        ary[len] ^= ary[i];
        ary[i] ^= ary[len];
    }

    return new string(ary);
}

So, how does that last one work. If you break it down, you are doing a bitwise shift. If you think of it as a number, it would be something like this:

Write a function to compute the nth Fibonacci number. Recusion or loop?

//recursion
public static int FibonacciRecurse(int input)
{
    if ((input == 0) || (input == 1))
        return input;
    else
        return FibonacciRecurse(input - 1) + FibonacciRecurse(input - 2);
}

//loop
public static int FibonacciNonRecurse(int input)
{
    int sum, result = 1, working = -1;

    for(int i=0;i<=input;i++)
    {
        sum = result + working;
        working = result;
        result = sum;
    }

    return result;
}

Print out the grade-school multiplication table up to 12×12. Why not some reuse and build it so you can do any size matrix? I am going to stick with Console here, as I can save this as a CSV and display in Excel. But, I can also use a tab char and make it look good in the Console.

public static string GetMultiplicationTable(int input, char separator)
{
    StringBuilder body = new StringBuilder();
    StringBuilder builder = new StringBuilder();
    char[] RETURN_CHARS = new char[2] { (char)13, (char) 10 };

    for(int i = 1; i <= input; i++)
    {
        body.Append(i);

        for (int j = 1; j <= input; j++)
        {
            //Only build header first time
            if(i==1)
            {
                builder.Append(separator);
                builder.Append(j);

                if (j == input)
                    builder.Append(RETURN_CHARS);
            }

            body.Append(separator);
            body.Append(i*j);
        }

        body.Append("rn");
    }

    builder.Append(body.ToString());

    return builder.ToString();
}

If I play with this, I can use one StringBuilder. One easy way is to loop twice to get the header, but I opted against two loops. As this example stands, I am not ending up with much of a perf issue, as moving one char array (StringBuilder) to another is quite efficient.

Write a function that sums up integers from a text file, one int per line. I assume this means I keep a running sum?

public static void PrintSums(string origFilePath, string sumFilePath)
{
    int sum = 0;
    string line;
    StreamReader reader = new StreamReader(origFilePath);
    StreamWriter writer = new StreamWriter(sumFilePath);

    while(null != (line = reader.ReadLine()))
    {
        int num;
        int.TryParse(line, out num);

        sum += num;

        writer.WriteLine(sum);
    }

    reader.Close();
    writer.Close();
}

The line while(null != (line = reader.ReadLine()))  is one I found a few years ago that I like. I am sure there is some file out there somewhere that includes null chars in a line and blows this idea out of the water, but it works for all of the files I work with internally.

Write a function to print the odd numbers from 1 to 99. Simple mod check here. Will keep this one as a console app. I know that is not a "function" per se, especially for you VBers, but I am being lazy. After all, this is my time I am wasting.

static void Main()
{
    for(int i=1;i<100;i++)
    {
        if(i%2 != 0)
            Console.WriteLine(i);
    }

    Console.Read();
}

Find the largest int value in an int array. At times like this, I wish Microsoft had made SortedArray<T>. Overkill? Sure, but why write code when you can simply instantiate? 🙂

public static int FindLargest(int[] input)
{
    int result = 0;

    for(int i=0;i<input.Length;i++)
    {
        int working = input[i];
        if(working > result)
            result = working;
    }

    return result;
}

Format an RGB number as a 6-digit hexidecimal string. In .NET, this is easy, as there is a ToString(formatType) method.

public static string ConvertToHex(int r, int g, int b)
{
    StringBuilder builder = new StringBuilder();

    string[] rgb = new string[3] { r.ToString("X"), g.ToString("X"), b.ToString("X")};

    for (int i = 0; i < rgb.Length;i++)
    {
        if (rgb[i].Length == 1)
            rgb[i] = "0" + rgb[i];
    }

    //Conversion to Hex
    builder.Append(rgb[0]);
    builder.Append(rgb[1]);
    builder.Append(rgb[2]);

    return builder.ToString();
}

You may wonder why I did not simply put items into the builder and avoid the array. The reason is you will find that any number < 16 will only occupy one character as a hex value. For example, if I set r=0, g=255, and b=0, I end up with 0FF0 instead of 00FF00. Not very good. There is probably a smarter way to accomplish this, but I can determine that in refactoring.

As a quick conversion back, you can try this (which will bomb if you do not test the length of the hex value) as I have in my routine:

public static int[] ConvertFromHexToRGB(string hex)
{
    if(hex.Length != 6)
        throw new ApplicationException("Hex RGB must be 6 characters in length");

    int r = Convert.ToInt32(hex.Substring(0, 2), 16);
    int g = Convert.ToInt32(hex.Substring(2, 2), 16);
    int b = Convert.ToInt32(hex.Substring(4, 2), 16);

    return new int[3] { r, g, b};
}

There are other ways to convert from Hex that you might opt for, of course. For example, this one, using System.Globalization:

public static int[] ConvertFromHexToRGB(string hex)
{
    if (hex.Length != 6)
        throw new ApplicationException("Hex RGB must be 6 characters in length");

    int r = int.Parse(hex.Substring(0, 2), NumberStyles.HexNumber);
    int g = int.Parse(hex.Substring(2, 2), NumberStyles.HexNumber);
    int b = int.Parse(hex.Substring(4, 2), NumberStyles.HexNumber);

    return new int[3] { r, g, b};
}

I would go on with some of his other questions, OO-Design, Scripting and Regex, etc., but I have already wasted a bit of time typing, so I will quit while I am behind. Hope this one was a bit of fun for you, as well.

Peace and Grace,
Greg

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: