有没有比这更好的方法从可变大小的数组中选择随机元素
Is there a better way of selecting a random element from an array of variable size than this?
我对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。
相关文章:
- 讨论 - 创建矩阵时的数组与向量的向量 - 什么是最实用的选择
- 如何从向量或数组中选择最常见的数字?(前五名)C++
- 如何为我的数组选择更大的数据类型?
- 选择一个元素而不是一个对象的数组的原因
- 如何在 c++ 中从数组中选择一个随机数?
- 从C++数组中选择一个随机元素
- 选择随机字符串数组的排序
- 我的选择排序代码是否存在导致它跳过数组中的元素的问题?
- 给定数组范围的选择排序问题
- 使用 C++ 从每个循环的数组中选择 n 个元素
- 使用STD :: String和字符数组之间的选择
- 根据 C++11 中的模板参数选择数组大小
- "我该如何展示cout<<"发烧";因为我不熟悉字符串数组,它也卡在选择部分?
- C 计数器用于从数组中选择事物
- 如何映射数组元素以选择二进制树节点
- C 选择排序字符串数组
- 在对象数组上进行选择排序
- 未选择引用到数组的构造函数进行列表初始化
- C++数组选择平方数并创建新向量
- c++数组选择