stefan1919

Matrix rectangle best sum

Aug 22nd, 2015
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.54 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace ConsoleApplication4
  8. {
  9.     class Program
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.             int[,] matrix = { { 0, 2, 4, 0, 9, 5 },
  14.                             { 7, 1, 3, 3, 2, 1 },
  15.                             { 1, 3, 9, 8, 5, 6 },
  16.                             { 4, 6, 7, 9, 1, 0 } };
  17.             int bestSum = int.MinValue;// helpful variables
  18.             int bestRow = 0;
  19.             int bestCol = 0;
  20.             for (int row = 0; row < matrix.GetLength(0) - 1; row++)// go trough the matrix first rows then cols
  21.             {
  22.                 for (int col = 0; col < matrix.GetLength(1) - 1; col++)
  23.                 {
  24.                     int sum = matrix[row, col] + matrix[row, col + 1] + matrix[row + 1, col] + matrix[row + 1, col + 1];//these cells could form a rectangle
  25.                     if (bestSum < sum)
  26.                     {
  27.                         bestSum = sum;
  28.                         bestRow = row;
  29.                         bestCol = col;
  30.                     }
  31.                 }
  32.             }
  33.             Console.WriteLine("The best platform is:");
  34.             Console.WriteLine(" {0}{1}", matrix[bestRow, bestCol], matrix[bestRow, bestCol + 1]);
  35.             Console.WriteLine(" {0}{1}", matrix[bestRow + 1, bestCol], matrix[bestRow + 1, bestCol + 1]);// print them like a matrix
  36.             Console.WriteLine("The maximal sum is: {0}", bestSum);// show the best sum
  37.         }
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment