using System; using System.Collections.Generic; using System.Text; using System.IO; namespace Euler11 { class Program { //What is the greatest product of four numbers on the same straight line in //the 20 by 20 grid? //Compute max product pf four terms in a 4*4 grid private static long MaxProd(int[,] Matrix, int x, int y) { try { long lMax = 0; long prod = 0; //1 NorthWest if (x > 3 && y > 3) prod = Matrix[x, y] * Matrix[x - 1, y - 1] * Matrix[x - 2, y - 2] * Matrix[x - 3, y - 3]; if (prod > lMax) lMax = prod; //2 North if (x > 3) prod = Matrix[x, y] * Matrix[x - 1, y] * Matrix[x - 2, y] * Matrix[x - 3, y]; if (prod > lMax) lMax = prod; //3 NorthEast if (x > 3 && y < Matrix.GetLength(0) - 3) prod = Matrix[x, y] * Matrix[x - 1, y + 1] * Matrix[x - 2, y + 2] * Matrix[x - 3, y + 3]; if (prod > lMax) lMax = prod; //4 East if (y < Matrix.GetLength(0) - 3) prod = Matrix[x, y] * Matrix[x, y + 1] * Matrix[x, y + 2] * Matrix[x, y + 3]; if (prod > lMax) lMax = prod; //5 SouthEast if ((x < Matrix.GetLength(0) - 3) && (y < Matrix.GetLength(0) - 3)) prod = Matrix[x, y] * Matrix[x + 1, y + 1] * Matrix[x + 2, y + 2] * Matrix[x + 3, y + 3]; if (prod > lMax) lMax = prod; //6 South if (x < Matrix.GetLength(0) - 3) prod = Matrix[x, y] * Matrix[x + 1, y] * Matrix[x + 2, y] * Matrix[x + 3, y]; if (prod > lMax) lMax = prod; //7 SouthWest if ((y < Matrix.GetLength(0) - 3) && (x > 3)) prod = Matrix[x, y] * Matrix[x - 1, y + 1] * Matrix[x - 2, y + 2] * Matrix[x - 3, y + 3]; if (prod > lMax) lMax = prod; //8 West if (y > 3) prod = Matrix[x, y] * Matrix[x, y - 1] * Matrix[x, y - 2] * Matrix[x, y - 3]; if (prod > lMax) lMax = prod; return lMax; } catch (Exception) { throw; } } static void Main(string[] args) { try { int[,] Matrix = new int[20, 20]; long lMax = 0; StreamReader strIn = File.OpenText(@"input.txt"); string stCurrentLine = null; int i = 0; while ((stCurrentLine = strIn.ReadLine()) != null) { int j =0; foreach (string number in stCurrentLine.Split(' ')) { Matrix[i,j] = int.Parse(number); ++j; } if (j != 20) throw new Exception("1"); ++i; } if (i != 20) throw new Exception("2"); for (i = 0; i < 20; ++i) { for (int j = 0; j < 20; ++j) { long localMax = MaxProd(Matrix, i, j); if (localMax > lMax) lMax = localMax; } } Console.WriteLine("Max Found: " + lMax); Console.ReadLine(); } catch (Exception e) { Console.WriteLine(e.Message); Console.ReadLine(); } } } }