This post is originally from Christian Liensberger on Channel 8 on October 2, 2007
During an interview I was asked to walk a multi-dimensional array like in the “snail-shell” way (look at the image on the right side). Today I had some time and thought I could try to implement it.
What I did is partioning it in a call that does the first four arrows in the picture. The next recursive call does the next four and so on… I have also added some escape conditions to make sure stuff is not listed twice.
That’s what I got so far:
class Program
{
static void Main(string[] args)
{
// The multi-dimensional array that is walked.
int[][] table = {
new[] { 1, 2, 3, 4, 5 },
new[] { 6, 7, 8, 9, 10 },
new[] { 11, 12, 13, 14, 15 },
new[] { 16, 17, 18, 19, 20 },
new[] { 21, 22, 23, 24, 25 }
};
// Print that table.
Print(table);
}
private static void Print(int[][] table)
{
// Print out the sub table. Starting the
// recursion.
PrintSubTable(table, 0);
}
private static void PrintSubTable(int[][] table,
int iteration)
{
// Check if we are over the half. Leave then.
if (iteration >= table.Length / 2.0f)
return;
// Read the first line of the iteration.
int[] subtable = table[iteration];
for (int i = iteration; i < subtable.Length - iteration;
i++)
{
// Print all elements out.
Console.WriteLine(subtable[i]);
}
// Read on the right side down.
for (int i = iteration +1; i < table.Length -
iteration -1; i++)
{
// Print the elements.
Console.WriteLine(table[i][subtable.Length -
iteration -1]);
}
// Check if we have to leave as we would read the
// last read line backwards.
if (table[iteration] == table[table.Length -
iteration -1])
{
return;
}
// Read the last line of the iteration backwards.
subtable = table[table.Length - iteration -1];
for (int i = subtable.Length - 1 - iteration;
i >= iteration; i–)
{
Console.WriteLine(subtable[i]);
}
// Read the left side up.
for (int i = table.Length - iteration - 2;
i >= iteration +1; i–)
{
Console.WriteLine(table[i][iteration]);
}
// Proceed with the sub table.
PrintSubTable(table, ++iteration);
}
}