2012-03-30 13 views
0

In der Schule machen wir gerade eine Spotify-Anwendung. Ich mache gerade eine Anwendung, wo ich Bilder von LastFM von dem aktuellen Künstler, der gerade spielt, bekomme. Ich bekomme drei zufällige Bilder gezeigt. Ich versuche jetzt sicherzustellen, dass die 3 zufälligen Bilder nicht identisch sein können.Zufälliges variables Ergebnis

Dies ist, was ich im Moment haben:

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

nun sicherzustellen, dass ich möchte, dass sie nicht die gleichen sind. Kann mir jemand helfen, wie das geht?

Antwort

1

Verwenden Sie ein 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

Vielen Dank, das hat mir sehr geholfen! – mparryy

+0

Dies könnte theoretisch für immer berechnen. : P – alex

+0

@alex lol sehr unwahrscheinlich, obwohl! – Curt

1

Sie könnten eine Reihe von Indizes erstellen, mische sie mit dem Shuffle Fisher Yates und dann 3 abschneiden.

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-Implementierung von here.

+0

Ich verstehe, was Sie hier tun, aber ich gehe zur ersten Antwort, da es für mich einfacher ist, es zu verstehen. Danke für deine Antwort! – mparryy

+0

+1 Ermöglicht Skalierbarkeit – Curt