随机变量结果

时间:2012-03-30 10:30:21

标签: javascript spotify

在学校,我们正在忙着制作Spotify应用程序。我目前正在制作一个应用程序,我从LastFM获取图像,来自当前正在播放的艺术家。我看到三个随机图像。我现在正在努力确保3个随机图像不能相同。

这就是我现在所拥有的:

var randno       = Math.floor ( Math.random() * artistImages.length );
var randno2      = Math.floor ( Math.random() * artistImages.length );
var randno3      = Math.floor ( Math.random() * artistImages.length );

现在我想确保它们不一样。任何人都可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

使用while loop

var randno = Math.floor ( Math.random() * artistImages.length );    

var randno2 = Math.floor ( Math.random() * artistImages.length );
while (randno2==randno)
{
   randno2 = Math.floor ( Math.random() * artistImages.length );
}

var randno3 = Math.floor ( Math.random() * artistImages.length );
while (randno3==randno || randno3==randno2)
{
   randno3 = Math.floor ( Math.random() * artistImages.length );
}

答案 1 :(得分:1)

您可以创建索引数组,使用Fisher Yates shuffle对其进行随机播放,然后将3切片。

function fisherYates ( myArray ) {
  var i = myArray.length;
  if ( i == 0 ) return false;
  while ( --i ) {
     var j = Math.floor( Math.random() * ( i + 1 ) );
     var tempi = myArray[i];
     var tempj = myArray[j];
     myArray[i] = tempj;
     myArray[j] = tempi;
   }
}

var arr = new Array(artistImages.length + 1).map(function(val, index) { 
                                                    return index; 
                                                 });

var rands = fisherYates(arr).slice(0, 3);

Fisher Yates从here实施。

相关问题