Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomly selecting a unique element in a 2D Array

Tags:

java

algorithm

Hi so I'm doing an assignment but I've kind of fallen flat on the concept of 2D arrays. I'm writing a method body that randomly selects an element in a 2D array. However, I'm not completely sure when of how to approach the problem.

I was thinking of using a random number generator to select a random element. Although what I need first is for the whole length of the box to be filled first with a value. In this case, the dimensions of the 2D array box are 20x20 and the value is zero. So I'd want the 2D array to be complete filled with zeroes. Although if I used a random number generator, is there a chance that an element which was randomly selected by the generator could possibly be used again before the entire box dimensions are filled first with zero?

Sorry for the long block of text. Basically what I'm asking is if there is a way to use random number generator to still randomly generate numbers but not repeat any its used previously.

like image 851
Sozziko Avatar asked Dec 04 '25 18:12

Sozziko


2 Answers

One option is to use Collections.shuffle(allCells).

Another option is to use the following algorithm, by keeping track of remaining unused cells:

1. Find a random number from 0 to size of the set - 1 .
2. Remove number at position `randomNumber` from the set.
3. Go to 1.
like image 87
Petar Minchev Avatar answered Dec 07 '25 08:12

Petar Minchev


I would go this way:

        int [][] myArray = new int[4][5]; //Any size and type
        int totalEmenent = myArray.length *myArray[0].length;
        int indexToSelect = (int)(Math.random()*totalEmenent);
        int xIndex = (int)indexToSelect/myArray.length;
        int yIndex = indexToSelect%myArray.length;
        int selectElement = myArray[xIndex][yIndex];

If you wish to select unique index each time:

        int [][] myArray = new int[4][5]; //Any size and type
        int totalEmenent = myArray.length *myArray[0].length;
        String selectedIndex = "";
        int numberOfSelect = 10; //Any number< totalEmenent

         for(int indx=0; indx< numberOfSelect; indx++){
              int indexToSelect = (int)(Math.random()*totalEmenent);
              //generate random until its unique
              while(selectedIndex.indexOf(String.valueOf(indexToSelect))> 0){
                   indexToSelect = (int)(Math.random()*totalEmenent);
              }
              selectedIndex = selectedIndex+indexToSelect;
              int xIndex = (int)indexToSelect/myArray.length;
              int yIndex = indexToSelect%myArray.length;
              int selectElement = myArray[xIndex][yIndex];
         }
like image 41
Yogendra Singh Avatar answered Dec 07 '25 07:12

Yogendra Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!