How to pick a random element in a 2 dimensional array

空扰寡人 提交于 2021-01-29 15:42:16

问题


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?


回答1:


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




回答2:


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...



来源:https://stackoverflow.com/questions/8760302/how-to-pick-a-random-element-in-a-2-dimensional-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!