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; /// /// Constructs a TriangleQuestion and sets up internal data. /// 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]); } } /// /// Gets the answer to this question for the calling class. /// int Answer { get { AddToParent(Triangle.Length - 1); return Triangle[0][0]; } } /// /// Internal method. /// /// A row in the triangle. 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); } } }