如何在二维数组中选取随机元素
好吧,我想在二维数组中选择一个随机点,以便可以填充它。我已经了解了如何对一维数组执行此操作,并且想知道这在二维数组中如何实现。我所看到的关于此方法的只是相同的位置再次出现,这是一个小问题,但我一开始不知道该怎么做。二维数组本质上是一个网格,其维度是 x 和 y 坐标。并且随机元素选择边界内的一个点(这是用户选择的,但出于此问题的目的可以是 30x50。
编辑:
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;
}
}
这是否有效,x 和 y 将对应于用户生成的数字并具有凸起的边界2 任一侧以防止任何物体进入(部分在网格之外或网格之外。不需要返回任何东西,对吧?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果网格的大小为
M by N
0 和 M-1
之间的随机数,请说 i0 之间的随机数和 N-1
表示 j(i,j) 将是二维数组的随机元素
If you grid is of size
M by N
0 and M-1
say i0 and N-1
say j(i,j) will be a random element of the 2d array
数组在这里扮演什么角色?
本质上,任务是选择...随机整数二维坐标。
因此,如果您想要两个坐标,请说
0...W-1
中的i
和0...H- 中的
,只需抽取两个随机整数。如果您需要更多以获得更高的维度,请抽取更多随机数。j
1显然,您可以访问
array[i][j]
。然而,在大多数语言中,数组可能是参差不齐的,即行/列可能具有不同的长度。然而,这对于处理来说也是微不足道的......
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
in0...W-1
andj
in0...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...