提问者:小点点

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


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

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

这是代码

 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%的情况下都会发生。

我想这不会是一个简单的解决办法。 我非常努力地用不同的技术,不同的循环,不同的数组方法来使它工作:(也请注意,我是初学者,所以我需要详尽的指导是怎么回事:)

祝你今天愉快。


共2个答案

匿名用户

一种选择是简单地洗牌一个数组:

null

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

匿名用户


const MIN = 1;
const MAX = 2;

// Get random numbers inclusive
function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min; 
}

const imgArray = [];
for (let i=0; i < MAX ; i++) {
  const index = getRandomIntInclusive(1, MAX );
  if (!imgArray[index]) {
    imgArray[index] = `cat-image-${index}`;
  }
}

// Filter out entries without an image
const images = imgArray.filter(i => !!i);

console.log(images);

\\["cat-image-2", "cat-image-4", "cat-image-5"]
\\ 0: "cat-image-2"
\\ 1: "cat-image-4"
\\ 2: "cat-image-5"