2012-03-30 81 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