如何将某个值添加到2D数组中的随机块?

时间:2014-10-21 17:28:22

标签: java arrays random

我想要做的是将数字(例如2)分配给数组中的两个随机点。以下是我设置数组的方法。

public static void print_array(int[][] array) {
    for (int row = 0; row < array.length; row++) {
        System.out.print("\n-----------------\n" +
                         "|  ");
        for (int col = 0; col < array[row].length; col++) {
            if (col != array[row].length) {
                System.out.print(array[row][col] + "|  ");
            if (col == array[row].length) {
                System.out.print("\n");
                }
            }
        }
    }
    System.out.print("\n-----------------");
}

然后我在main方法中调用print_array来显示数组。然后添加我需要使用此方法的数字:

public static void placeBlock(int[][] array) {
}

如何在数组中的随机点中放置一个整数?

2 个答案:

答案 0 :(得分:2)

您可以使用模运算符。该运算符返回余数。 例如。

2 % 3 returns 2 (It is lesser that 3 the second operand)
3 % 3 returns 0 (It is lesser that 3 the second operand)
3 % 2 returns 1 (It is lesser that 2 the second operand)

假设你有两个随机数num1和num2&amp;你知道你2D维数的维度是MxN。那是M行和N列。 所以当你这样做时

num1 % M returns a number between 0...M
num2 % N returns a number between 0...N

这使您可以:

array[num1%M][num2%N]=2;

根据评论进行编辑: 如果您要生成随机数,那么:

Random randomGenerator=new Random();
int num1 = randomGenerator.nextInt(array.length);
int num2 = randomGenerator.nextInt(array[0].length);

在这种情况下,您可以根据长度获得随机数,以便直接使用

array[num1][num2]=2;

答案 1 :(得分:1)

你可以试试这个:

public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {

        int[][]array={{3,4,5},{1,8,3},{33,7,5}};
        print_array(array);
        placeBlock(array,2);
        print_array(array);


    }
    public static void placeBlock(int[][] array,int value) {
        Random rand=new Random();
        int randRow=rand.nextInt(array.length);
        int randCol=rand.nextInt(array[0].length);
        array[randRow][randCol]=value;
    }
    public static void print_array(int[][] array) {
        for (int row = 0; row < array.length; row++) {
            System.out.print("\n-----------------\n" +
                             "|  ");
            for (int col = 0; col < array[row].length; col++) {
                if (col != array[row].length) {
                    System.out.print(array[row][col] + "|  ");
                if (col == array[row].length) {
                    System.out.print("\n");
                    }
                }
            }
        }
        System.out.print("\n-----------------");
    }

}