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

1 Answer

0 votes
import Foundation

func findRepeatingPatterns(matrix: [[Int]], patternSize: Int) {
    var patternMap = [String: Set<Int>]()

    for (rowIndex, row) in matrix.enumerated() {
        for col in 0...(row.count - patternSize) {
            let pattern = row[col..<col + patternSize].map { String($0) }.joined(separator: "-")

            patternMap[pattern, default: Set()].insert(rowIndex)
        }
    }

    print("Repeated Patterns Found:")
    for (pattern, rows) in patternMap {
        if rows.count > 1 {
            print("\(pattern) appears \(rows.count) times in rows: \(rows.map { String($0) }.joined(separator: " "))")
        }
    }
}

let matrix = [
    [1, 2, 3, 8, 9, 7, 4, 9, 6],
    [1, 3, 2, 7, 8, 9, 4, 5, 6],
    [1, 2, 3, 8, 6, 1, 4, 9, 8],
    [1, 2, 3, 0, 8, 8, 4, 5, 9],
    [1, 2, 3, 4, 5, 6, 7, 8, 9],
    [1, 2, 3, 7, 0, 9, 4, 5, 7],
    [1, 3, 2, 4, 5, 6, 7, 8, 9]
]

let patternSize = 3 // Looking for sequences of 3 numbers

findRepeatingPatterns(matrix: matrix, patternSize: patternSize)



/*
run:

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

*/

 



answered May 25, 2025 by avibootz
...