随机将字符串放入2d数组中

时间:2017-12-04 23:19:34

标签: javascript

我需要创建一个2D数组,然后随机生成两个数字,这些数字将是X的行和列。我需要放置其中的四个并且它们需要被隐藏,因为它是用于猜测用户所在位置的游戏。

char[][]gameBoard= new char [10][10];

int row= (int) (Math.random()*9+1);
int col=(int) (Math.random()*9+1);


for (int i = 0; i < 10; i++){
                for (int j = 0; j <     10; j++){

                      if(i==row&&j==col) 
                            System.out.print("[X]");


                    else
                         System.out.print("[ ]");

                System.out.println();
}

1 个答案:

答案 0 :(得分:1)

const FILLED_FIELD = 'X'
function placeX(array) {
    const width = array.length - 1;
    const height = array[0].length - 1;
    const targetX = Math.round(Math.random() * width); //Pick a random number between 0, and the width of the array
    const targetY = Math.round(Math.random() * height); //Pick a random number between 0, and the height of the array
    if (array[targetX][targetY] === FILLED_FIELD) return placeX(array); //If the choosed place is already occupied, try again
    array[targetX][targetY] = FILLED_FIELD; //Otherwise fill a field
}

技术上不是一个完美的实现,但会完成这项工作。只需将2D数组传递给函数,它就会随机放置X,忽略X已放置的位置。