1D到2D,无限循环

时间:2012-12-28 22:59:38

标签: java multidimensional-array

这是我在10x10扫雷游戏板中生成随机地雷的代码。

    for (int j = 0; j < 10; j++) {
        mine[j] = (int) (Math.random() * 100);
        while (board[mine[j]] != 99)
            board[mine[j]] = 99;
    }

我想修改它以在2D int数组中工作:

    for (int j = 0; j < 10; j++) {
        do {
            temp = (int) (Math.random() * 100);
            row = temp / 10;
            column = temp % 10;
        } while (board[row][column] != 99);
        board[row][column] = 99;
    }

然而,这段代码会创建一个无限循环。我被卡住了,我想不出为什么它不起作用

3 个答案:

答案 0 :(得分:3)

我认为你的意思是:[while条件错了,你为什么要设置一个已经99到99的字段

for (int j = 0; j < 1; j++) {
    do {
        temp = (int) (Math.random() * 100);
        row = temp / 10;
        column = temp % 10;
    } while (board[row][column] == 99);
    board[row][column] = 99;
}

答案 1 :(得分:0)

为什么您的代码会创建无限循环?最初,没有任何单元格的值为99,而do_while条件为while (board[row][column] != 99);。因此循环将继续迭代,因为它永远不会遇到值为99的单元格 您的do_while条件错误。它应该是while (board[row][column] == 99);
说明:如果当前生成的随机单元格具有矿,即单元格值等于99,则将重新生成行号和列号。do_while循环将继续运行,直到生成的单元格位置尚未生成一个矿。
我相信这就是你想要做的 请注意,用于生成地雷的算法不是最佳的。有更好的方法来做到这一点。

答案 2 :(得分:0)

从语法上讲,你的问题是在while条件下,但你的算法也不是最优的,因为与已放置炸弹的碰撞会越来越频繁。在极端情况下,必须在棋盘上填写除一个位置之外的所有位置,您可能需要多次重新注册才能获得免费点。

最好从仅包含空位的集合中绘制插槽。

    // create an array of slots to draw ten slots from
    int[] slots = new int[100];
    for (int i = 0; i < slots.length; i++) {
        slots[i] = i;
    }

    /*
     * draw ten slots by placing them at the start of the array
     * subsequent draws will draw from the tail of the array
     */
    Random random = new Random();
    for (int i = 0; i < 10; i++) {
        // draw from one of the slots from the tail
        int draw = random.nextInt(100 - i) + i; 

        // switch values at draw and i index
        int temp = slots[draw];
        slots[draw] = slots[i];
        slots[i] = temp;

        // use the draw to place a bomb on the board
        board[(draw / 10)][(draw % 10)] = 99;
    }