using System; using System.Text; namespace Pyramid { public class Pyramid { private readonly int rows; private readonly int[,] data; public Pyramid(int[,] data) { this.data = data; rows = data.GetLength(0); } public Pyramid(int rows) { this.rows = rows; data = new int[rows, rows]; } public int this[int row, int col] { get { return data[row, col]; } set { data[row, col] = value; } } public int Rows { get { return rows; } } public override string ToString() { var sb = new StringBuilder(); for (int row = 0; row < rows; row++) { sb.Append(new string(' ', 9 * row / 2)); for (int col = 0; col < rows - row; col++) { sb.AppendFormat("[{0:00000}] ", data[row, col]); } sb.AppendLine(); } return sb.ToString(); } } public interface IPyramidGenerator { Pyramid GeneratePyramid(); } public class RandomPyramidGenerator : IPyramidGenerator { private readonly int rows; private readonly int range; private readonly Random random; public RandomPyramidGenerator(int rows, int range) { this.rows = rows; this.range = range; random = new Random(); } public Pyramid GeneratePyramid() { var pyramid = new Pyramid(rows); for (int row = 0; row < rows; row++) { for (int col = 0; col < rows - row; col++) { pyramid[row, col] = random.Next(1, range); } } return pyramid; } } public interface IPyramidSolver { long PyramidMaximumTotal(Pyramid pyramid); } // There is something wrong here. A few things actually... public class NaivePyramidSolver : IPyramidSolver //........................... { public long PyramidMaximumTotal(Pyramid pyramid) { return GetTotalAbove(pyramid.Rows - 1, 0, pyramid); } private long GetTotalAbove(int row, int column, Pyramid pyramid) { if (row == 0) return 0; int myValue = pyramid[row, column]; long left = myValue + GetTotalAbove(row - 1, column, pyramid); long right = myValue + GetTotalAbove(row - 1, column + 1, pyramid); return Math.Max(left, right); } } public class OurProgram { private static void Main() { // this is doesn't get correct number var generator = new RandomPyramidGenerator(5, 99); Pyramid pyramid = generator.GeneratePyramid(); Console.WriteLine(pyramid); var solver = new NaivePyramidSolver(); Console.WriteLine("This result is wrong, do you know why ?"); Console.WriteLine(solver.PyramidMaximumTotal(pyramid)); Console.ReadLine(); } } }