2012-03-30 114 views
0

在学校,我们正在忙于制作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); 

现在我要确保他们是不一样的。任何人都可以帮助我如何做到这一点?

回答

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); 
} 
+0

非常感谢你对我的帮助! – mparryy 2012-03-30 10:48:34

+0

这理论上可以永久计算。 :P – alex 2012-03-30 10:52:13

+0

@alex大声笑虽然不太可能! – Curt 2012-03-30 10:52:48

1

您可以创建索引的数组,与费雪耶茨洗牌洗牌它们,然后切掉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执行。

+0

我确实知道你在做什么,但我会首先回答,因为这对我来说更容易理解。谢谢你的回答! – mparryy 2012-03-30 10:49:07

+0

+1允许可扩展性 – Curt 2012-03-30 10:54:10