All pastes #1008407 Raw Edit

Jay Miller

public text v1 · immutable
#1008407 ·published 2008-05-05 16:56 UTC
rendered paste body
using System;
using System.IO;

namespace Interview
{
   public class TriangleQuestion
   {
      // triangle.txt contains the following four lines:
      // 3
      // 7 5
      // 2 4 6
      // 8 5 9 3
      const string TriangleFile = "triangle.txt";
      
      readonly int[][] Triangle;


      /// <summary>
      /// Constructs a TriangleQuestion and sets up internal data.
      /// </summary>
      public TriangleQuestion()
      {
         string[] lines = File.ReadAllLines(TriangleFile);
         Triangle = new int[lines.Length][];

         int position = 0;
         int row = 0;

         for (int i = 0; i <= 4; i++)
         {
            string[] items = lines[i].Split(new char[] { ' ' });

            for (int j = 0; j <= 4; j++)
               Triangle[row][position++] = Convert.ToInt32(items[j]);
         }
      }

      /// <summary>
      /// Gets the answer to this question for the calling class.
      /// </summary>
      int Answer
      {
         get
         {
            AddToParent(Triangle.Length - 1);

            return Triangle[0][0];
         }
      }

      /// <summary>
      /// Internal method.
      /// </summary>
      /// <param name="row">A row in the triangle.</param>
      void AddToParent(int row)
      {
         if (row == 0)
            return;

         for (int i = 0; i < Triangle[row - 1].Length; i++)
            Triangle[row - 1][i] +=
                  Math.Max(Triangle[row][i], Triangle[row][i + 1]);

         AddToParent(row);
      }
   }
}