Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- //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
- class Program
- {
- static int bestMatch = 1;
- static string bestString = "";
- static void Main()
- {
- string[,] matrix = {
- {"ha","yo","hi","hi","hi","jo"},
- {"ha","bo","yo","go","go","go"},
- {"ha","bo","li","yo","li","li"},
- {"bo","li","li","li","yo","li"},
- };
- for (int x = 0; x < matrix.GetLength(0); x++)
- {
- for (int y = 0; y < matrix.GetLength(1); y++)
- {
- Seek(x, y, matrix);
- }
- }
- //print result
- for (int i = 0; i < bestMatch; i++)
- {
- if (i == 0)
- {
- Console.Write(bestString);
- }
- else
- {
- Console.Write("," + bestString);
- }
- }
- Console.WriteLine();
- }
- private static void Seek(int x, int y, string[,] matrix)
- {
- int match = 0;
- string test = matrix[x, y];
- //check horizontal
- for (int row = x, col = y; col < matrix.GetLength(1); col++)
- {
- if (test == matrix[row, col])
- {
- match++;
- }
- }
- CheckForBestScore(match, test);
- match = 0;
- //check diagonal down
- for (int row = x, col = y; row < matrix.GetLength(0) && col < matrix.GetLength(1); row++, col++)
- {
- if (test == matrix[row, col])
- {
- match++;
- }
- }
- CheckForBestScore(match, test);
- match = 0;
- //check diagonal up
- for (int row = x, col = y; row >= 0 && col >= 0; row--, col--)
- {
- if (test == matrix[row, col])
- {
- match++;
- }
- }
- CheckForBestScore(match, test);
- match = 0;
- //check vertical
- for (int row = x, col = y; row < matrix.GetLength(0); row++)
- {
- if (test == matrix[row, col])
- {
- match++;
- }
- }
- CheckForBestScore(match, test);
- }
- private static void CheckForBestScore(int match, string test)
- {
- if (match > bestMatch)
- {
- bestMatch = match;
- bestString = test;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement