nh1402
nh1402

Reputation: 75

How to pick a random element in a 2 dimensional array

Ok I want to pick a random point in the 2d array so it can be filled. Ive seen how to do this for a 1d array, and am wondering how this would be possible in a 2d array. All I have seen about this method is that the same position comes up again, which is a slight problem, but I don't know how to do it in the first place. The 2d array is essentially a grid, with the dimensions being the x and y coordinates. And the random element selecting a point within the boundaries (which is user selected but for the purposes of this problem can be 30x50.

EDIT:

  import java.util.Random;
class pickRand{
public static String get (int x, int y){
    int rndx = generator.nextInt(x) + 2;
    int rndy = generator.nextInt(y) + 2;


}
}

So would this work, the x and y will correspond to the user generated number and have a raised boundary of 2 either side to prevent any objects going (partially outside or of the grid. Nothing needs to be returned right?

Upvotes: 0

Views: 8633

Answers (2)

Has QUIT--Anony-Mousse
Has QUIT--Anony-Mousse

Reputation: 77454

What role does the array play here?

Essentially, the task is to pick... random integer 2D coordinates.

So if you want two coordinates, say i in 0...W-1 and j in 0...H-1, just draw two random integers. If you need more for higher dimensionality, draw more randoms.

Obviously, you can then access array[i][j].

In most languages, arrays can however be ragged, i.e. the rows/columns may have different lengths. This is however just as trivial to handle...

Upvotes: 0

parapura rajkumar
parapura rajkumar

Reputation: 24403

If you grid is of size M by N

  • Generate a random number between 0 and M-1 say i
  • Generate another random between 0 and N-1 say j

(i,j) will be a random element of the 2d array

Upvotes: 3

Related Questions