简体   繁体   中英

2D array how to avoid the same numbers

Good evening I want to fill a five x five table with different numbers I do not want to have the same number for each column I have limitation that should be, belong to a certain limits, I was able to do but do not know how to avoid to be no more than once the numbers in the table

int num;
        int [][] array = new int [5][5];
        Random r = new Random();
        for (int row = 0; row < array.length; row++) {
            for (int col = 0; col < array[row].length; col++) { 
            if(row == 0){
                     num =r.nextInt(15);
                    array[row][col]=num;
            }else if(row == 1){
                     num =r.nextInt(31-16)+16;
                    array[row][col]=num;
            }else if(row == 2){
                     num =r.nextInt(45-31)+31;
                    array[row][col]=num;
            }else if(row == 3){
                     num =r.nextInt(61-46)+46;
                    array[row][col]=num;
            }else if(row == 4){
                     num =r.nextInt(75-61)+61;
                    array[row][col]=num;
            }
            }
        }

For each row, create a list containing the integers it can contain, then shuffle the list (with Collections.shuffle() ), and keep the 5 first elements.

Or, if your goal is to have different elements for the whole table, create a single list containing all the integers the matrix can contain, then shuffle the list, an iterate through the list to fill your matrix.

You could have a HashSet of the numbers already taken. Add to this and duplicated are not allowed. Use the toArray() method to get the array object if needed.

If you still want to use the arrays then the add() method of HashMap returns true if the value did not exist in the current set so if true then add to the table, if false then don't.

This allows you to add elements to the table without having to shuffle ie if you want to continually update the table and not have to wait for a full set before displaying.

That is assuming you just want the numbers to be unique for the table and not just the row positions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM