Monday, November 17, 2008

Problem #18

I never did write code for this one...I just kind of looked at it and was able to spot the best possible route. I got it on my first try.

But, if you cannot do it on your own, here is a slightly modified version of someone elses code that works for finding the solution. When originally doing these, I think I used this code and modified it a bit farther to allow for solving the bigger triangle. The file pyramid.txt contains the pyramid, just copy/pasted from the page.


#include <iostream>
#include <ctime>
#include <fstream>
//#include <sstream>

using namespace std;

int main()
{
clock_t start = clock();
int total = 0;
unsigned int numbers[15][15];
ifstream fi;

fi.open("pyramid.txt");

for (int l=0;l<15;l++)
for (int n=0;n<l+1;n++)
fi >> numbers[l][n];

fi.close ();

for (int l=13;l>=0;l--)
for (int n=0;n<l+1;n++)
if (numbers[l+1][n]>numbers[l+1][n+1])
numbers[l][n]+=numbers[l+1][n];
else numbers[l][n]+=numbers[l+1][n+1];

cout << numbers[0][0] << endl
<< "Process took " << (static_cast<double> (clock()) - start) / CLOCKS_PER_SEC << " seconds." << endl;
system("pause");
return 0;
}

No comments: