javascript - 来自数组项目的 2 个随机值
问题描述
好吧,我必须制作一个计算 2 个随机值的程序。
在程序中,函数中应该有一个列表(1-9)。从这个列表中我应该得到 2 个随机值(我建议使用 array.splice())。
在选择了 2 个随机值之后,程序应该将它们计算(加法)为总值 randomvalue1 + randomvalue2 = totalvalue;
抓住!执行时 2 个随机值不能相同(5+5、3+3、2+2 等无效)
第二个收获!随机值不允许连续执行 2 次。我的意思是程序不应允许 randomvalue1 连续两次(或更多)等于相同的值(这也适用于 randomvalue2)
到目前为止,我收到了此代码的建议,但它不检查相同的值是否连续出现 x 次
function makeRandom(list) {
function getRandomIndex() {
return Math.floor(Math.random() * list.length);
}
let index1 = getRandomIndex(),
index2 = getRandomIndex();
while (index1 === index2) index2 = getRandomIndex();
return list[index1] + '+' + list[index2];
}
console.log(makeRandom([1, 2, 3, 4, 5, 6, 7, 8, 9]));
解决方案
您可以采用索引并循环,直到您获得不同的索引以从数组中获取值。
function makeRandom(list) {
function getRandomIndex() {
return Math.floor(Math.random() * list.length);
}
let index1 = getRandomIndex(),
index2 = getRandomIndex();
while (index1 === index2) index2 = getRandomIndex();
return list[index1] + '+' + list[index2];
}
console.log(makeRandom([1, 2, 3, 4, 5, 6, 7, 8, 9]));
排除某些指标的方法
function makeRandom(list, exclude = []) {
function getRandomIndex() {
return Math.floor(Math.random() * list.length);
}
function getFreeIndex() {
let index;
if (exclude.length >= list.length) return;
do index = getRandomIndex();
while (exclude.includes(index))
exclude.push(index);
return index;
}
return getFreeIndex() + '+' + getFreeIndex();
}
console.log(makeRandom([1, 2, 3, 4, 5, 6, 7, 8, 9], [2, 3]));
推荐阅读
- mysql - Typeorm - 使用子查询
- python - 我不能在 python 3.8 中使用 urllib3 或 urllib
- java - 将 Java KeyListener 实现转换为 Kotlin
- swift - 带有数组的 SwiftUI 动画形状
- python - 如何修复搜索路径上的放大错误?
- maven - 如何配置 Android Studio 以在项目中包含包含 pom.xml 的配置文件夹?
- function - 如何将字符串数组传递给函数并在 SQL 的“IN”语句中使用它
- python - 数据框唯一项目和 xy 位置到室友(共享位置)项目网格
- angular - Angular 9 ngx-image-cropper 使用滑块调整裁剪器大小
- java - 将字符串转换为键值对并在java中将其转换为一行