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

1 Answer

0 votes
function findRepeatingPatterns(matrix, patternSize) {
    let patternMap = new Map();
 
    matrix.forEach((row, rowIndex) => {
        for (let col = 0; col <= row.length - patternSize; col++) {
            let pattern = row.slice(col, col + patternSize).join("-")
 
            if (!patternMap.has(pattern)) {
                patternMap.set(pattern, new Set());
            }
            patternMap.get(pattern).add(rowIndex);
        }
    });
 
    console.log("Repeated Patterns Found:");
    patternMap.forEach((rows, pattern) => {
        if (rows.size > 1) {
            console.log(`${pattern} appears ${rows.size} times in rows: ${[...rows].join(" ")}`);
        }
    });
}
 
const 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]
];
 
const 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 by avibootz
edited May 25 by avibootz
...