Search code examples
javaarraysnumbersgenerated

Generating random non-repeating numbers 2d array - all numbers same


This question is for Java. I keep on trying to create a Block[][] of size N, where the numbers 0 - 9 are placed randomly. I've created an array and then shuffled it to prevent numbers from being repeated. When I iterate over the array and assign the numbers to the two dimensional array, I keep on finding that all of the numbers in the two dimensional array are the same. The block keeps on coming out as:

222

222

222

I'd greatly appreciate your help!

public class Board {

int N = 3; 
static int [][] copy; 

//construct a board from an N-by-N array of blocks 
//(where blocks[i][j] = block in row i, column j) 
public Board(int[][] blocks){
    blocks =  new int[N][N]; //creates array of size N
    //generates random numbers 0 inclusive to # exclusive 
    List<Integer> randomList = new ArrayList<>(); 
    for (int i = 0; i < blocks.length; i++){
        randomList.add(i); 
    }
    int randomNum = 0; 
    for (int i = 0; i < blocks.length; i++){
        randomNum = randomList.get(i); 
    }
    Collections.shuffle(randomList);
    for (int i = 0; i < blocks.length; i++){
        for (int j = 0; j < blocks[i].length; j++){
            blocks[i][j] = randomNum; 
        }
    }
    copy = blocks.clone(); 
}

Solution

  •    int counter = 0;
       Collections.shuffle(randomList);
        for (int i = 0; i < blocks.length; i++){
            for (int j = 0; j < blocks[i].length; j++){
                blocks[i][j] = randomList.get(counter);
                counter++; 
            }
        }
    

    You should create a counter that will loop through each element of your original arraylist and assign to the multi-dimensional arraylist

    Also change:

     for (int i = 0; i < 10; i++){
            randomList.add(i); 
        }
    

    You say you want 0-9 the above loop will give you 0-9. The loop you have will only give you 0-2.