Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,788 questions

51,694 answers

573 users

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

1 Answer

0 votes
import java.util.Map;
import java.util.Set;
import java.util.List;
import java.util.Arrays;
import java.util.HashSet;
import java.util.HashMap;

public class PatternFinder {
    public static void findRepeatingPatterns(List<List<Integer>> matrix, int patternSize) {
        Map<String, Set<Integer>> patternMap = new HashMap<>();

        for (int row = 0; row < matrix.size(); row++) {
            for (int col = 0; col <= matrix.get(row).size() - patternSize; col++) {
                StringBuilder pattern = new StringBuilder();
                for (int i = 0; i < patternSize; i++) {
                    pattern.append(matrix.get(row).get(col + i)).append("-");
                }
                patternMap.computeIfAbsent(pattern.toString(), k -> new HashSet<>()).add(row);
            }
        }

        System.out.println("Repeated Patterns Found:");
        for (Map.Entry<String, Set<Integer>> entry : patternMap.entrySet()) {
            if (entry.getValue().size() > 1) {
                System.out.print(entry.getKey() + " appears " + entry.getValue().size() + " times in rows: ");
                for (int row : entry.getValue()) {
                    System.out.print(row + " ");
                }
                System.out.println();
            }
        }
    }

    public static void main(String[] args) {
        List<List<Integer>> matrix = Arrays.asList(
            Arrays.asList(1, 2, 3, 8, 9, 7, 4, 9, 6),
            Arrays.asList(1, 3, 2, 7, 8, 9, 4, 5, 6),
            Arrays.asList(1, 2, 3, 8, 6, 1, 4, 9, 8),
            Arrays.asList(1, 2, 3, 0, 8, 8, 4, 5, 9),
            Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9),
            Arrays.asList(1, 2, 3, 7, 0, 9, 4, 5, 7),
            Arrays.asList(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:
4-5-6- appears 3 times in rows: 1 4 6 
1-3-2- appears 2 times in rows: 1 6 
1-2-3- appears 5 times in rows: 0 2 3 4 5 
5-6-7- appears 2 times in rows: 4 6 
2-3-8- appears 2 times in rows: 0 2 
7-8-9- appears 3 times in rows: 1 4 6 
9-4-5- appears 2 times in rows: 1 5 
6-7-8- appears 2 times in rows: 4 6 

*/

 



answered May 25, 2025 by avibootz
...