Advertisement
simonses

SumMatrix3x3

Jan 18th, 2013
31
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.07 KB | None | 0 0
  1. using System;
  2.  
  3. class MatrixBiggerSum
  4. {
  5.     static void Main()
  6.     {
  7.         Console.WriteLine("Enter the length of the matrix rows: ");
  8.         int n = int.Parse(Console.ReadLine());
  9.         Console.WriteLine("Enter the length of the matrix columns: ");
  10.         int m = int.Parse(Console.ReadLine());
  11.  
  12.         int[,] matrix = new int[n, m];
  13.  
  14.  
  15.         // Read the matrix
  16.         Console.WriteLine("Now the values!");
  17.         for (int row = 0; row < matrix.GetLength(0); row++)
  18.         {
  19.             for (int col = 0; col < matrix.GetLength(1); col++)
  20.             {
  21.                 Console.Write("matrix[{0},{1}] = ", row, col);
  22.                 matrix[row, col] = int.Parse(Console.ReadLine());
  23.             }
  24.             Console.WriteLine();
  25.         }
  26.  
  27.         // Find the maximal sum platform of size 3 x 3
  28.         int count = 3; // For the sum loop count = count (3 x 3)
  29.         int bestSum = int.MinValue;
  30.         int bestRow = 0;
  31.         int bestCol = 0;
  32.  
  33.         for (int row = 0; row < matrix.GetLength(0) - (count - 1); row++)
  34.         {
  35.             for (int col = 0; col < matrix.GetLength(1) - (count - 1); col++)
  36.             {
  37.                 //Get the sum - Loop
  38.                 int sum = 0;
  39.                 for (int i = row; i < count + row; i++)
  40.                 {
  41.                     for (int j = col; j < count + col; j++)
  42.                     {
  43.                         sum += matrix[i, j];
  44.                     }
  45.                 }
  46.  
  47.                 if (sum > bestSum)
  48.                 {
  49.                     bestSum = sum;
  50.                     bestRow = row;
  51.                     bestCol = col;
  52.                 }
  53.             }
  54.         }
  55.  
  56.         // Print the result
  57.         Console.WriteLine("The best platform is:");
  58.  
  59.         for (int i = bestRow; i < count + bestRow; i++)
  60.         {
  61.             for (int j = bestCol; j < count + bestCol; j++)
  62.             {
  63.                 Console.Write("{0, -4}", matrix[i, j]);
  64.             }
  65.             Console.WriteLine();
  66.         }
  67.  
  68.         Console.WriteLine("The maximal sum is: {0} ", bestSum);
  69.     }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement