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

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

问题描述

好吧,我想在2d数组中选择一个随机点,以便可以填充它.我已经看过如何对一维数组执行此操作,并且想知道在二维数组中如何做到这一点.我所看到的关于该方法的所有信息是再次出现相同的位置,这是一个小问题,但是我一开始不知道该怎么做.2d数组本质上是一个网格,尺寸为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×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)将是2d数组的随机元素

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

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

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