如何在二维数组中选择一个随机元素 [英] How to pick a random element in a 2 dimensional array

查看:34
本文介绍了如何在二维数组中选择一个随机元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我想在二维数组中随机选择一个点,以便填充.我已经看到如何对一维数组执行此操作,并且想知道这在二维数组中如何实现.我所看到的关于这种方法的所有内容是再次出现相同的位置,这是一个小问题,但我首先不知道该怎么做.二维数组本质上是一个网格,维度是 x 和 y 坐标.并且在边界内选择一个点的随机元素(这是用户选择的,但对于这个问题的目的可以是 30x50.

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.

  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 以防止任何对象移动(部分在网格之外或网格之外.不需要返回任何内容,对吗?

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?

推荐答案

如果你的网格大小为 M by N

  • 0 和 M-1 之间生成一个随机数,比如 i
  • 0 和 N-1 之间生成另一​​个随机数,比如 j
  • Generate a random number between 0 and M-1 say i
  • Generate another random between 0 and N-1 say j

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

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

这篇关于如何在二维数组中选择一个随机元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆