How to find repeated patterns of numbers in the rows of a matrix with C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

class PatternFinder
{
    static void FindRepeatingPatterns(List<List<int>> matrix, int patternSize) {
        Dictionary<string, HashSet<int>> patternMap = new Dictionary<string, HashSet<int>>();

        for (int row = 0; row < matrix.Count; row++) {
            for (int col = 0; col <= matrix[row].Count - patternSize; col++) {
                string pattern = string.Join("-", matrix[row].GetRange(col, patternSize));

                if (!patternMap.ContainsKey(pattern)) {
                    patternMap[pattern] = new HashSet<int>();
                }

                patternMap[pattern].Add(row);
            }
        }

        Console.WriteLine("Repeated Patterns Found:");
        foreach (var entry in patternMap) {
            if (entry.Value.Count > 1) {
                Console.Write(entry.Key + " appears " + entry.Value.Count + " times in rows: ");
                foreach (int row in entry.Value) {
                    Console.Write(row + " ");
                }
                Console.WriteLine();
            }
        }
    }

    static void Main()
    {
        List<List<int>> matrix = new List<List<int>>
        {
            new List<int> { 1, 2, 3, 8, 9, 7, 4, 9, 6 },
            new List<int> { 1, 3, 2, 7, 8, 9, 4, 5, 6 },
            new List<int> { 1, 2, 3, 8, 6, 1, 4, 9, 8 },
            new List<int> { 1, 2, 3, 0, 8, 8, 4, 5, 9 },
            new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 },
            new List<int> { 1, 2, 3, 7, 0, 9, 4, 5, 7 },
            new List<int> { 1, 3, 2, 4, 5, 6, 7, 8, 9 }
        };

        int patternSize = 3; // Looking for sequences of 3 numbers
        FindRepeatingPatterns(matrix, patternSize);
    }
}



/*
run:

Repeated Patterns Found:
1-2-3 appears 5 times in rows: 0 2 3 4 5 
2-3-8 appears 2 times in rows: 0 2 
1-3-2 appears 2 times in rows: 1 6 
7-8-9 appears 3 times in rows: 1 4 6 
9-4-5 appears 2 times in rows: 1 5 
4-5-6 appears 3 times in rows: 1 4 6 
5-6-7 appears 2 times in rows: 4 6 
6-7-8 appears 2 times in rows: 4 6 

*/

 



answered May 25, 2025 by avibootz
...