简体   繁体   中英

Java- populating 2d array element index randomly?

I have a 5x5 2D array that is supposed to be populated with objects from another array that has the same dimensions. I need a loop that iterates until each spot is full with all of the objects from the other array. The row and column need to be random, and if the spot has already been filled then it needs to find an empty spot to fill it. For example, if the random spot is array[0][3] then it fills it then goes to a new spot like array[1][2]. I have Random rand = new Random() declared and declare int row = rand.nextInt(4) and int col = rand.nextInt(4) and array[row][col] = object . How do i construct the loop that performs this action until all indices are populated?

Here's code to radomize the order in which spots in the 2D array is filled. If you need any further assistance on this feel free to ask.

ArrayList<Integer> inds= new ArrayList<Integer>();
for(int i=1; i<26;i++){
    inds.add(i);
}
while(inds.size()!=0){
    int x = rand.nextInt(inds.size());
    array[inds.get(x)/5][inds.get(x)%5] =  0; //replace 0 with what ever it is that you want to store
}

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