首页 > 解决方案 > 如何在相同可能性的一百中选择一个?JS

问题描述

我正在构建一个音乐播放器,我想创建随机功能,我现在使用 math.random 这显然是个坏主意,因为它可以多次重复相同的数字,所以我需要给他们同样的机会,但没有清楚怎么做,现在我有一个包含三首音乐的数组,所以如果随机点击其中一个应该播放,如果我再次点击下一个,但从来没有两次相同的歌曲,我该怎么做?

标签: javascript

解决方案


虽然已经在评论中得到了回答,但这里是 javascript 代码示例:

// your playlist length
let playlistLength = 10;
// temporary variables
let src = [], res = [], idx, len;
// fill the 'src' array with numbers from 0 to playlistLength-1
for (idx = 0; idx < playlistLength; idx++) src.push(idx);
// while the 'src' array  has any elements
while (len = src.length) {
  // get random element index in 0 .. src.length-1 range
  idx = Math.floor(Math.random() * len);
  // push the element into the array 'res'
  res.push(src[idx]);
  // remove the element from array 'src'
  src.splice(idx, 1);
}
// here is random sequence of numbers from 0 to playlistLength-1
console.log(res.join(', '));


推荐阅读