How to find a duplicate of length 5 in a single array. Java

后端 未结 1 1328
-上瘾入骨i
-上瘾入骨i 2021-01-27 09:52

I create an array that then prints in sets of five. I want to then be able to search the array by 5 to see if there are any duplicates. I\'ve tried but I can only think of a way

相关标签:
1条回答
  • 2021-01-27 10:41

    You could implement this using a Hashtable. Using your code as a base, I've written an example implementation but without knowing what it is you are trying to do, I can't judge if this is what you are looking for.

    import java.util.Hashtable;
    
    public class findPat {
        static final int COUNT = 100;
    
        static Hashtable<String, Integer> compareSet = new Hashtable<String, Integer>();
        static String groupInteger = "";
        static int arr [] = new int [5];
        static int st = 1;
        static int end = 56;
        static double t1;
        static double t2;
    
        public static void main(String[] args) {
            t1=System.currentTimeMillis(); 
            for(int n = 0; n < COUNT; n++){
                for (int i = 0; i < arr.length; i++) {
                    arr[i] = (int) (Math.random()* (end - st + 1)) + st;
    
                }
                for (int i = 1; i <= 5; i++) {
                    groupInteger += arr[i-1];
                    System.out.print("\t" + arr[i-1]);
                    if (i % 5 == 0) {
                        System.out.println();
                        if (compareSet.containsKey(groupInteger)) {
                            System.out.println("duplicate found");
                            int currentCount = compareSet.get(groupInteger);
                            compareSet.put(groupInteger, currentCount + 1);
                        } else {
                            compareSet.put(groupInteger, 1);                        
                        }
                        groupInteger = "";
                    }
    
                } 
            }
            t2=System.currentTimeMillis();
            System.out.println();
            System.out.println();
            System.out.println("\t" + "Total run time is " + ((t2 - t1)) + "ms");
        }
    }
    

    This code keeps track of the unique sets of random numbers by adding them (creating a key value that is the same for every set that has the same values in the same order, the concatenated string takes care of this).

    Your code ran in 13 seconds on my system, mine takes 17 seconds. Now if runtime is of crucial importance, you might want to look into hashing techniques. But I'm not sure if you will be able to shave off a lot as you will have to add some extra code which will take extra time.

    0 讨论(0)
提交回复
热议问题