检查随机化的数字是否在数组中,如果为true,则再次随机化
Check if randomized number is in an array, if true then randomize again?
我正在创建一个战列舰游戏,并试图随机化计算机的舰艇。然而,它有时会多次随机化同一位置,从而在某些回合中创建不到8艘船。我试图使用indexOf来修复这个问题,但无论我如何更改代码,我似乎都无法使其正常工作。如果随机化的数字在数组shipLocations中,那么我想再次滚动该数字,直到它与数组中的任何数字都不匹配。有什么想法吗?
var shipLocations = [];
function randShips() {
for (i = 0; i < 8; i++) {
var randomize = Math.floor(Math.random() * 64 + 1);
if (shipLocations.indexOf(randomize) == true) {
var randomize = Math.floor(Math.random() * 64 + 1);
}
else {
shipLocations.push(randomize);
}
} //end of i loop
} //end of randShips()
randShips();
console.log(shipLocations);
编辑:因此,在尝试了一些答案后,在测试了大约100次后,它似乎以应有的方式工作。
var shipLocations = [];
function randShips() {
while (shipLocations.length < 8) {
var randomize = Math.floor(Math.random() * 64 + 1);
while (shipLocations.indexOf(randomize) > -1) {
randomize = Math.floor(Math.random() * 64 + 1);
}
shipLocations.push(randomize);
}
}
randShips();
var shipLocations = [];
function randShips() {
while ( shipLocations.length < 8 ) {
var randomize = Math.floor(Math.random() * 64 + 1);
while ( shipLocations.indexOf(randomize) >= 0 ) {
randomize = Math.floor(Math.random() * 64 + 1);
}
shipLocations.push(randomize);
}
} //end of randShips()
randShips();
console.log(shipLocations);
由于您想要8个唯一的值,很可能一行中创建的2个数字都已经在数组中了。所以我想你会想做一个while
:
while (shipLocations.indexOf(randomize) != -1) {
randomize = Math.floor(Math.random() * 64 + 1);
}
var
部分不应该在那里,这只是变量的第一个实例所必需的。
在javascript中,返回值为-1的false条件。
因此,将if else条件更改为:
if (shipLocations.indexOf(randomize) != -1) { //true condition equivalent
var randomize = Math.floor(Math.random() * 64 + 1);
}
else {
shipLocations.push(randomize);
}
indexOf
不返回布尔值,它返回匹配元素的索引(int)。
所以代码应该是
if (~shipLocations.indexOf(randomize)) {
var randomize = Math.floor(Math.random() * 64 + 1);
}
您可以使用此函数为数组获取一个真正的唯一数字。
function uniqueRandom( arr) {
var num = Math.floor(Math.random() * 64 + 1);
if (~arr.indexOf(num)) {
uniqueRandom(arr);
} else {
return num;
}
}
顺便说一句,你写的逻辑有问题。如果你发现了一个重复的数字,你只需再次将其随机化,而不将其推入数组。因此使用CCD_ 4或递归函数应该可以很好地完成这项工作。
相关文章:
- $(document).height()在刷新时随机化值(Safari 5.1.10)
- 将键盘使用与 Qualtrics 中的答案随机化相结合
- 我怎样才能随机化 HTML 元素的颜色属性
- 通过AJAX调用PHP随机化器的输出
- 如何在JS中随机化backgroundPosition而不使用鼠标移动来制作万花筒的动画
- 使用Javascript对RGBA颜色进行光标控制的形状随机化
- 如何在一个随机化的有序列表中随机化多个无序列表
- 如何使用JavaScript随机化有序列表
- 使用JavaScript随机化html标记
- 可以'我的单词随机化器脚本不能正常循环
- 如果语句是假的 JavaScript,则再次随机化数字
- 函数随机化 - 我可以让它错过一个页面并且该页面上只有一个图像吗?可湿性粉剂
- 随机化网页上的图像和颜色对
- 随机侮辱生成器(随机化结果)
- Javascript:通过在while循环内推送/拼接来随机化数组
- 构建一个简单的随机化器,其中包括一个点、一个下划线、字母 A 和字母 B
- 随机化并在页面加载时显示给定数量的 if 元素
- jQuery Rotator是按字母顺序排列的,我怎样才能在我的主页上随机化
- 检查随机化的数字是否在数组中,如果为true,则再次随机化
- 如果目标是避免污染全局作用域,为什么不让更多的人随机化他们的全局命名空间对象呢?