Advertisement
soxa

MaxSumOfMatrix

Dec 24th, 2013
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.33 KB | None | 0 0
  1. using System;
  2.  
  3. class MatrixMaxSum
  4. {
  5.     //Write a program that reads a rectangular matrix of size N x M and finds in it the square 3 x 3 that has maximal sum of its elements.
  6.  
  7.     static void Main()
  8.     {
  9.         // Input N and M
  10.         Console.WriteLine("Enter N ");
  11.         int rolCount = int.Parse(Console.ReadLine());
  12.         Console.WriteLine("Enter M ");
  13.         int colCount = int.Parse(Console.ReadLine());
  14.         int maxRol = 0;
  15.         int maxCol = 0;
  16.  
  17.         if (rolCount < 3 || colCount < 3)
  18.         {
  19.             Console.WriteLine("N >= 3 and M >=3");
  20.             return; //Stop task
  21.         }
  22.         // Solution
  23.         int[,] array = new int[rolCount, colCount];
  24.         int sum = 0;
  25.         int maxSum = 0;
  26.         // Input elements of matrix
  27.         Console.WriteLine("Enter elements ex. 1 3 4 ..");
  28.         for (int i = 0; i < rolCount; i++)
  29.         {
  30.             string rolStr = Console.ReadLine(); // ex. 1 2 3
  31.             string[] emptySpace = new string[] {" "}; // remove from split empty space
  32.             string[] colStrArray = rolStr.Split(emptySpace, StringSplitOptions.RemoveEmptyEntries);
  33.  
  34.             for (int j = 0; j < colStrArray.Length; j++)
  35.             {
  36.                 array[i, j] = int.Parse(colStrArray[j]); // Input digits in array
  37.             }
  38.         }
  39.  
  40.         for (int moveDown = 0; moveDown <= rolCount - 3; moveDown++)
  41.         {
  42.             for (int moveRight = 0; moveRight <= colCount - 3; moveRight++)
  43.             {
  44.                 sum = 0;
  45.                 //Sumator
  46.                 for (int rol = moveDown; rol < 3 + moveDown; rol++)
  47.                 {
  48.                     for (int col = moveRight; col < 3 + moveRight; col++)
  49.                     {
  50.                         sum += array[rol, col];
  51.                     }
  52.                 }
  53.                 if (sum > maxSum)
  54.                 {
  55.                     maxSum = sum;
  56.                     maxRol = moveDown;
  57.                     maxCol = moveRight;
  58.                 }
  59.             }
  60.         }
  61.         // Output
  62.         Console.WriteLine("Max sum is : {0} ", maxSum);
  63.         for (int i = maxRol; i < maxRol + 3; i++)
  64.         {
  65.             for (int j = maxCol; j < maxCol + 3; j++)
  66.             {
  67.                 Console.Write(array[i,j]+" ");
  68.             }
  69.             Console.WriteLine();
  70.         }
  71.     }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement