如何在二维数组中选取随机元素

发布于 2024-12-25 04:31:27 字数 475 浏览 4 评论 0原文

好吧,我想在二维数组中选择一个随机点,以便可以填充它。我已经了解了如何对一维数组执行此操作,并且想知道这在二维数组中如何实现。我所看到的关于此方法的只是相同的位置再次出现,这是一个小问题,但我一开始不知道该怎么做。二维数组本质上是一个网格,其维度是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

丢了幸福的猪 2025-01-01 04:31:27

如果网格的大小为 M by N

  • 生成一个介于 0 和 M-1 之间的随机数,请说 i
  • 生成另一个介于 0 之间的随机数和 N-1 表示 j

(i,j) 将是二维数组的随机元素

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

橘寄 2025-01-01 04:31:27

数组在这里扮演什么角色?

本质上,任务是选择...随机整数二维坐标

因此,如果您想要两个坐标,请说 0...W-1 中的 i0...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 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...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文