Sign In
  
  
  
  



  

 

 

Walking a multi-dimension­al array in the snail-shell way

 
 
Description:

This post is originally from  Christian Liensberger on Channel 8 on October 2, 2007

During an interview I was asked to walk a multi-dimension­al 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-dimension­al 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(t­able, 0);
   }

   private static void PrintSubTable(i­nt[][] 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.WriteLi­ne(subtable[i])­;
      }

      // Read on the right side down.
      for (int i = iteration +1; i < table.Length -
         iteration -1; i++)
      {
         // Print the elements.
         Console.WriteLi­ne(table[i][sub­table.Length -
            iteration -1]);
      }

      // Check if we have to leave as we would read the
      // last read line backwards.
      if (table[iteratio­n] == table[table.Len­gth - 
         iter­ation -1])
      {
         return;
      }

      // Read the last line of the iteration backwards.
      subtable = table[table.Len­gth - iteration -1];
      for (int i = subtable.Length - 1 - iteration;
         i >= iteration; i–)
      {
         Console.WriteLi­ne(subtable[i])­;
      }

      // Read the left side up.
      for (int i = table.Length - iteration - 2;
         i >= iteration +1; i–)
      {
         Console.WriteLi­ne(table[i][ite­ration]);
      }

      // Proceed with the sub table.
      PrintSubTable(t­able, ++iteration);
   }
}
 

 

Report abuse for blog post  |  Share
 
 

Related Posts