Java coding question

Asked 2 years ago, Updated 2 years ago, 110 views

for(int p = 0; p < index.length;p++) 
        {
            int count=0;
            for(int q = p+1; q < index.length; q++) {
         if (Arrays.equals(index[p], index[q]))
         {

             count = count +1;

         }
            }
            if (count==7) 
            {
            For (inti = 0; i < 6; i++) // output winning number
             {

                  System.out.println(index[p][i]);
             }
            System.out.println("redundant count"+count); //Redundant count is 5,6 instead of 7
            }
        }

I'm comparing the elements in the index array with each other, and I want to print out the element that is overlapped 7 times, but I'm not sure what's wrong with the number of duplicates other than 7. Please take a look.

java coding if문

2022-09-22 19:11

1 Answers

There are many ways to check redundancy in a simple two-dimensional array, but I think it would be good to use Map.

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class Main {

    private static int index[][] = new int[20][20];
    private static Map<Integer, Integer> duplicate;


    public static void main(String[] args) {
        duplicate = new HashMap<>();

        for(int i=0; i<index.length; i++) {
            for(int j=0; j<index[i].length; j++) {
                index[i][j] = new Random().nextInt(100);
            }
        }

        for(int i=0; i<index.length; i++) {
            for(int j=0; j<index[i].length; j++) {
                Integer value = duplicate.get(index[i][j]);
                if(value==null) value = 0;
                duplicate.put(index[i][j], value+1);
            }
        }

        for(Map.Entry<Integer, Integer> entry : duplicate.entrySet()) {
            if(entry.getValue()==7)
                System.out.println (entry.getKey() + " : " + entry.getValue() + "number duplicate!"));
        }
    }
}

Code to calculate redundancy by generating random numbers up to 100. If you set the key value as a number and the value as the number of duplicate times, you can easily pull out the number that overlaps seven times.


2022-09-22 19:11

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.