Thursday 23 April 2009

PROJECT EULER #67

Link to Project Euler problem 67

By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.
3

7 5
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom in
triangle.txt (right click and 'Save Link/Target As...'), a 15K text file containing a triangle with one-hundred rows.
NOTE: This is a much more difficult version of
Problem 18. It is not possible to try every route to solve this problem, as there are 299 altogether! If you could check one trillion (1012) routes every second it would take over twenty billion years to check them all. There is an efficient algorithm to solve it. ;o)

I solved this when I did problem 18 just because I found a good algorithm back then.

using System;
using System.Collections.Generic;
using System.IO;

namespace ProjectEuler
{
class Program
{
static void Main()
{
//Problem 67
DateTime start = DateTime.Now;
StreamReader sr = new StreamReader(@"../../triangle.txt");
//Treat the triangle as a 2 dimensional array[][]
List<List<int>> triangle = new List<List<int>>();
//make the triangle
for (int i = 0; i < 100; i++)
{
string s = sr.ReadLine();
char[] c = { ' ' };
string[] sa = s.Split(c);
List<int> line = new List<int>();
foreach (string s1 in sa)
line.Add(int.Parse(s1));
triangle.Add(line);
}
//row
for (int i = 1; i < 100; i++)
//column
for (int j = 0; j <= i; j++)
//do the edges
if (j == 0)
triangle[i][0] = triangle[i][0] + triangle[i - 1][0];
else if (j == triangle[i].Count - 1)
triangle[i][triangle[i].Count - 1] = triangle[i][triangle[i].Count - 1] +
triangle[i - 1][triangle[i - 1].Count - 1];
//do the middle
else
triangle[i][j] = triangle[i - 1][j - 1] + triangle[i][j] > triangle[i - 1][j] + triangle[i][j]
? triangle[i - 1][j - 1] + triangle[i][j]
: triangle[i - 1][j] + triangle[i][j];
int max = 0;
foreach (int i in triangle[triangle.Count - 1])
max = i > max ? i : max;
Console.WriteLine(max);
TimeSpan time = DateTime.Now - start;
Console.WriteLine("This took {0}", time);
Console.ReadKey();
}
}
}

No comments: