简体   繁体   English

如何选择二维数组中的随机元素

[英]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. 好的,我想在2d数组中选择一个随机点,以便可以填充它。 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. 2d数组本质上是一个网格,尺寸为x和y坐标。 And the random element selecting a point within the boundaries (which is user selected but for the purposes of this problem can be 30x50. 并且在边界内选择一个点的随机元素(用户选择该点,但出于此问题的目的,可以为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? 因此,这项工作将使x和y对应于用户生成的数字,并且在任一侧具有2的凸起边界以防止任何对象进入(部分在网格外部或网格之外。不需要返回任何内容吗?

If you grid is of size M by N 如果网格的大小为M by N

  • Generate a random number between 0 and M-1 say i 产生一个介于0 and M-1之间的随机数,说
  • Generate another random between 0 and N-1 say j 产生另一个介于0 and N-1之间的随机数,说j

(i,j) will be a random element of the 2d array (i,j)将是2d数组的随机元素

What role does the array play here? 数组在这里扮演什么角色?

Essentially, the task is to pick... random integer 2D coordinates . 本质上,任务是选择... 随机整数2D坐标

So if you want two coordinates, say i in 0...W-1 and j in 0...H-1 , just draw two random integers. 所以,如果你想两个坐标,说i0...W-1j0...H-1只画两个随机整数。 If you need more for higher dimensionality, draw more randoms. 如果您需要更高的尺寸,请绘制更多随机数。

Obviously, you can then access array[i][j] . 显然,您可以访问array[i][j]

In most languages, arrays can however be ragged, ie the rows/columns may have different lengths. 但是,在大多数语言中,数组可能参差不齐,即行/列的长度可能不同。 This is however just as trivial to handle... 但是,这同样不容易处理...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM