Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* We are given a matrix of strings of size N x M. Sequences in the matrix we define as sets of several neighbor elements located on the same line, column or diagonal.
- * Write a program that finds the longest sequence of equal strings in the matrix. */
- using System;
- namespace _03.EqualElementsInStringMatrix
- {
- class EqualElementsInStringMatrix
- {
- static void CheckForBestLen(int currentCount, ref int bestCount, string element, ref string bestElement)
- {
- if (currentCount > bestCount)
- {
- bestCount = currentCount;
- bestElement = element;
- }
- }
- static int CountDiagonal(string[,] matrix, int row, int col)
- {
- int count = 1;
- while (true)
- {
- if (row + 1 == matrix.GetLength(0) || col+1 == matrix.GetLength(1) || matrix[row, col] != matrix[row + 1, col+1])
- {
- break;
- }
- row++;
- col++;
- count++;
- }
- return count;
- }
- static int CountVertical(string[,] matrix, int row, int col)
- {
- int count = 1;
- while (true)
- {
- if (row + 1 == matrix.GetLength(0) || matrix[row, col] != matrix[row+1, col])
- {
- break;
- }
- row++;
- count++;
- }
- return count;
- }
- static int CountHorizontal(string[,] matrix,int row, int col)
- {
- int count = 1;
- while (true)
- {
- if (col+1==matrix.GetLength(1)|| matrix[row,col]!=matrix[row,col+1])
- {
- break;
- }
- col++;
- count++;
- }
- return count;
- }
- static void PrintStringMatrix(string[,] matrix)
- {
- for (int row = 0; row < matrix.GetLength(0); row++)
- {
- for (int col = 0; col < matrix.GetLength(1); col++)
- {
- Console.Write("{0,5}",matrix[row,col]);
- }
- Console.WriteLine();
- }
- }
- static void Main(string[] args)
- {
- //string[] str = { "ha","ho","fifi","hi","xx","xxx"};
- Console.WriteLine("Enter N:");
- int n = int.Parse(Console.ReadLine());
- Console.WriteLine("Enter M:");
- int m = int.Parse(Console.ReadLine());
- string[,] matrix = new string[n, m];
- //Random rand = new Random();
- for (int row = 0; row < matrix.GetLength(0); row++)
- {
- for (int col = 0; col < matrix.GetLength(1); col++)
- {
- //int index = rand.Next(0, str.Length);
- matrix[row, col] = Console.ReadLine();
- }
- }
- PrintStringMatrix(matrix);
- int bestLen = 0;
- string bestElement = string.Empty;
- for (int row = 0; row < matrix.GetLength(0); row++)
- {
- for (int col = 0; col < matrix.GetLength(1); col++)
- {
- string element = matrix[row, col];
- int currentLen = CountHorizontal(matrix, row, col);
- CheckForBestLen(currentLen, ref bestLen, element, ref bestElement);
- currentLen = CountVertical(matrix, row, col);
- CheckForBestLen(currentLen, ref bestLen, element, ref bestElement);
- currentLen = CountDiagonal(matrix, row, col);
- CheckForBestLen(currentLen, ref bestLen, element, ref bestElement);
- }
- }
- Console.WriteLine("Best length: {0}",bestLen);
- Console.WriteLine("Element: {0}",bestElement);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement