创建一个由唯一数字组成的数组。

问题描述 投票:0回答:2

我正在开发一个简单的游戏,允许用户从特定的猫咪Api中生成1到5个猫咪图像。然后,点击开始按钮后,应用程序会生成这些猫的影子副本(低透明度)。游戏将是关于拖动底部的图像,并将它们贴合到随机定位的影子副本上(只有这样游戏才有意义)。然后,我打算做一些更进一步的功能,如时间计数器,积分等,只是为了学习的目的。

但是,我正在努力创建一个唯一的随机数(将是特定猫的索引),并且在迭代过程中不会重复......

以下是代码

 const newArray = []; // 


const catsArrayList = [...catBoardCopy.querySelectorAll('.cat')] //Array with cat images

function randomizeIndex() { // randomize an index number
    let randomIndex = Math.floor((Math.random() * catsArrayList.length - 1) + 1);
    console.log(randomIndex);

    return randomIndex;
}

catsArrayList.forEach(catElement => { // here I am iterating over an array with cats which length is for example 5(this is max actually)

    newArray.push(catsArrayList[randomizeIndex()]); // and pushing those elements with randomly generated index to the new array

})

newArray.forEach(newCat => {

    shadowCatsContainer.appendChild(newCat); // here random cats are finally put to html container
})

所有这些工作,直到这些随机数字中的一个至少重复一次......当然,这实际上发生了90%的时间。

我想这不是一个简单的解决方案。我很努力地用不同的技术,不同的循环,不同的数组方法来使它工作,但什么都没有 :( 另外请注意,我是初学者,所以我需要详尽的指导,这是怎么回事 :)

祝你有个愉快的一天。

javascript unique-index
2个回答
0
投票

你的代码很接近,你可以从源数组中删除你分配给新数组的项目,这样你就不会重复使用它。

const cats = [...catBoardCopy.querySelectorAll('.cat')]

function randomIndex() {
    return Math.floor(Math.random() * cats.length);
}

cats.forEach(catElement => {
    const index = randomIndex();
    shadowCatsContainer.appendChild(cats[index]);
    cats.splice(index, 1);
})

0
投票

一种方法是简单地洗牌一个数组。

const cats = ['Tigger', 'Smokey', 'Kitty', 'Simba', 'Sassy'];

function shuffle(array, n = 500) {
    const output = array.slice();
    for (let i = 0; i < n; ++i) {
        swap(output, getRandomInt(0, output.length), getRandomInt(0, output.length))
    }

    return output;
}

function swap(array, i, j) {
    const temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}

function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}

const shadowedCats = shuffle(cats);
console.log(cats);
console.log(shadowedCats);
console.log(shuffle(cats));

0
投票

一个使用数组的例子. 在这里,我创建了一个包含可能数字的数组,它从0到'catsArrayList'数组中包含的元素数。如果'catsArrayList'有3个元素,那么数组中可能的数字将等于:[0, 1, 2]。[0, 1, 2]

现在的想法是从该数组中随机抽取一个数,然后从列表中删除,然后我们可以继续重复这个过程,而不会得到重复的值。

例如

let catsArrayList = ['value1', 'value2', 'value3', 'value4', 'value5', 'value6'] // example


let numbers = [...Array(catsArrayList.length).keys()]
let lengthnumbers = numbers.length


for(let i = 1; i <= lengthnumbers; i++) {
  let randoms = Math.floor(Math.random() * numbers.length)
  console.log(i + 'º number: ' + numbers.splice(randoms, 1))
}

点击 "运行代码片段 "几次,你会看到你会得到不同的、不重复的随机数。

© www.soinside.com 2019 - 2024. All rights reserved.