yanchevilian

5.Square with Maximum Sum

Jul 18th, 2021
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.35 KB | None | 0 0
  1.     using System;
  2.     using System.ComponentModel;
  3.     using System.Linq;
  4.     using System.Runtime.CompilerServices;
  5.  
  6.     namespace _5._Square_with_Maximum_Sum
  7.     {
  8.         class Program
  9.         {
  10.             static void Main(string[] args)
  11.             {
  12.                 int[] matrixSizes = ReadFromConsole();
  13.  
  14.                 int rows = matrixSizes[0];
  15.                 int cols = matrixSizes[1];
  16.  
  17.                 int[,] matrix = new int[rows, cols];
  18.  
  19.                 FillMatrix(matrix, rows, cols);
  20.                 int maxSum = Int32.MinValue;
  21.                 int maxRow = 0;
  22.                 int maxCol = 0;
  23.  
  24.                 for (int rowIndex = 0; rowIndex < rows - 1; rowIndex++)
  25.                 {
  26.                     for (int colIndex = 0; colIndex < cols - 1; colIndex++)
  27.                     {
  28.                         int currentResult = 0;
  29.  
  30.                         currentResult = (matrix[rowIndex, colIndex] + matrix[rowIndex, colIndex + 1])
  31.                                + (matrix[rowIndex + 1, colIndex] + matrix[rowIndex + 1, colIndex + 1]);
  32.                         if (currentResult > maxSum)
  33.                         {
  34.                             maxSum = currentResult;
  35.                             maxRow = rowIndex;
  36.                             maxCol = colIndex;
  37.                         }
  38.                     }
  39.                 }
  40.  
  41.                 Console.WriteLine($"{matrix[maxRow, maxCol]} {matrix[maxRow, maxCol + 1]}");
  42.                 Console.WriteLine($"{matrix[maxRow + 1, maxCol]} {matrix[maxRow + 1, maxCol + 1]}");
  43.                 Console.WriteLine(maxSum);
  44.             }
  45.  
  46.             static void FillMatrix(int[,] matrix, int rows, int cols)
  47.             {
  48.                 for (int row = 0; row < rows; row++)
  49.                 {
  50.                     int[] numbersToFill = ReadFromConsole();
  51.                     for (int col = 0; col < cols; col++)
  52.                     {
  53.                         matrix[row, col] = numbersToFill[col];
  54.                     }
  55.                 }
  56.  
  57.             }
  58.  
  59.             public static int[] ReadFromConsole()
  60.             {
  61.                 int[] matrixSizes = Console.ReadLine()
  62.                     .Split(", ", StringSplitOptions.RemoveEmptyEntries)
  63.                     .Select(int.Parse)
  64.                     .ToArray();
  65.                 return matrixSizes;
  66.             }
  67.         }
  68.     }
  69.  
Advertisement
Add Comment
Please, Sign In to add comment