首页 > 解决方案 > 来自数组项目的 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]));

标签: javascriptarraysrandomarray-splice

解决方案


您可以采用索引并循环,直到您获得不同的索引以从数组中获取值。

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]));


推荐阅读