有没有比这更好的方法从可变大小的数组中选择随机元素

Is there a better way of selecting a random element from an array of variable size than this?

本文关键字:数组 选择 元素 随机 更好 方法 有没有      更新时间:2023-10-16

我对C++很陌生,想知道是否有更好的方法可以做到这一点。它将在Arduino上运行,所以我不能使用ArrayLists或任何东西。

byte GetFreeCell(short x, short y)
{
    byte possibleMoves[4] = {0,0,0,0};
    if (y - 2 >= 0 && _grid[y - 2][x] == 0)
        possibleMoves[0] = 1;
    if (x + 2 < WIDTH && _grid[y][x + 2] == 0)
        possibleMoves[1] = 2;
    if (y + 2 < HEIGHT && _grid[y + 2][x] == 0)
        possibleMoves[2] = 3;
    if (x - 2 >= 0 && _grid[y][x - 2] == 0)
        possibleMoves[3] = 4;
    if (possibleMoves[0] == 0 && possibleMoves[1] == 0 && possibleMoves[2] == 0 && possibleMoves[3] == 0) {
        return 0;
    }
    byte move = 0;
    while(move == 0){
        move = possibleMoves[random(4)];
    }
    return move;
}

谢谢

byte GetFreeCell(short x, short y)
{
    byte possibleMoves[4];
    byte index = 0;
    if (y - 2 >= 0 && _grid[y - 2][x] == 0)
        possibleMoves[index++] = 1;
    if (x + 2 < WIDTH && _grid[y][x + 2] == 0)
        possibleMoves[index++] = 2;
    if (y + 2 < HEIGHT && _grid[y + 2][x] == 0)
        possibleMoves[index++] = 3;
    if (x - 2 >= 0 && _grid[y][x - 2] == 0)
        possibleMoves[index++] = 4;
    return index ? possibleMoves[random(index)] : 0;
}

你可以帮自己一个忙,使用它:

https://github.com/maniacbug/StandardCplusplus/#readme

然后,可以使用标准容器清理代码。

此外,C++中没有 ArrayList。这就是Java。使用上面的库,你可以改用std::vector。