Skip to content

Instantly share code, notes, and snippets.

@finaiized
Created April 21, 2012 22:57
Show Gist options
  • Save finaiized/2440125 to your computer and use it in GitHub Desktop.
Save finaiized/2440125 to your computer and use it in GitHub Desktop.
The simple solution to problem 11 of Project Euler.
using System;
using System.IO;
namespace ProjectEuler11
{
class Program
{
static void Main(string[] args)
{
const int NUMBER_OF_ELEMENTS = 20;
int[][] numbers = new int[NUMBER_OF_ELEMENTS][];
Console.WriteLine("Analyzing grid...");
using (StreamReader sr = new StreamReader("eulereleven.txt"))
{
string line;
int i = 0;
while ((line = sr.ReadLine()) != null)
{
numbers[i++] = Array.ConvertAll<string, int>(line.Split(new char[] { ' ' }), int.Parse);
Console.WriteLine(line);
}
}
int largestProduct = 0;
int horizontal = 0, vertical = 0, diagonal = 0;
// Horizontal
for (int j = 0; j < NUMBER_OF_ELEMENTS; j++)
{
for (int i = 0; i < NUMBER_OF_ELEMENTS - 3; i++)
{
int product = numbers[j][i] * numbers[j][i + 1] * numbers[j][i + 2] * numbers[j][i + 3];
if (product > horizontal)
horizontal = product;
}
}
// Vertical
for (int j = 0; j < NUMBER_OF_ELEMENTS - 3; j++)
{
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
int product = numbers[j][i] * numbers[j + 1][i] * numbers[j + 2][i] * numbers[j + 3][i];
if (product > vertical)
vertical = product;
}
}
// Diagonal \
for (int j = 0; j < NUMBER_OF_ELEMENTS - 3; j++)
{
for (int i = 0; i < NUMBER_OF_ELEMENTS - 3; i++)
{
int product = numbers[j][i] * numbers[j + 1][i + 1] * numbers[j + 2][i + 2] * numbers[j + 3][i + 3];
if (product > diagonal)
diagonal = product;
}
}
// Diagonal /
for (int j = 0; j < NUMBER_OF_ELEMENTS - 3; j++)
{
for (int i = NUMBER_OF_ELEMENTS - 1; i > 2; i--)
{
int product = numbers[j][i] * numbers[j + 1][i - 1] * numbers[j + 2][i - 2] * numbers[j + 3][i - 3];
if (product > diagonal)
diagonal = product;
}
}
largestProduct = Math.Max(Math.Max(horizontal, vertical), diagonal);
Console.WriteLine("Horizontal: " + horizontal.ToString());
Console.WriteLine("Vertical: " + vertical.ToString());
Console.WriteLine("Diagonal: " + diagonal.ToString());
Console.WriteLine("Total: " + largestProduct.ToString());
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment