Last active
October 3, 2015 18:48
-
-
Save VegaFromLyra/f4426c8b42663850e2c4 to your computer and use it in GitHub Desktop.
Triangle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
// NOTE: Incorrect solution | |
// Triangle | |
// By starting at the top of the triangle and moving to adjacent numbers on the row below, the maximum total from top to bottom is 27. | |
// 5 | |
// 9 6 | |
// 4 6 8 | |
// 0 7 1 5 | |
// I.e. 5 + 9 + 6 + 7 = 27. | |
// Write a program in a language of your choice to find the maximum total from top to bottom in triangle.txt, a text file containing a triangle with 100 rows. | |
namespace Triangle | |
{ | |
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
string currentLine; | |
int sum = 0; | |
try | |
{ | |
using(StreamReader reader = new StreamReader("input.txt")) | |
{ | |
currentLine = reader.ReadLine(); | |
sum += Int32.Parse(currentLine); | |
int currentLineNumber = 1; | |
while ((currentLine = reader.ReadLine()) != null) | |
{ | |
currentLine = currentLine.Trim(); | |
currentLineNumber++; | |
var numbersInStringForm = currentLine.Split(' '); | |
var numbers = new int[numbersInStringForm.Length]; | |
for(int i = 0; i < numbers.Length; i++) | |
{ | |
numbers[i] = Int32.Parse(numbersInStringForm[i]); | |
} | |
int mid = numbers.Length / 2; | |
if (currentLineNumber % 2 == 0) | |
{ | |
sum += numbers[mid - 1]; | |
} else | |
{ | |
sum += numbers[mid]; | |
} | |
} | |
} | |
Console.WriteLine("Sum is {0}", sum); | |
} | |
catch(Exception e) | |
{ | |
Console.WriteLine("The file could not be read: "); | |
Console.WriteLine(e.Message); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment