2011-07-07 35 views
-6

有一個totalscore給出,例如, 50,用一些價值觀陣列:隨機函數,其結果是給定的totalscore從數組值

var totalscore = 50 
var myvalues = [ 1, 3, 4, 7, 9, 2, 53, 123, 324324, 221 ] 

我想有一個隨機函數,這使我從數組中值(或位置),這樣所有選定值相同住在totalscore值。

有沒有人有想法?

+5

請問您可以重新解釋一下這個問題嗎? – wonk0

+4

你能舉一個你想要的結果的例子嗎? –

+3

聞到功課 –

回答

1
function getRandom(maxval) 
{ 
    return (Math.floor(Math.random()* maxval)); 
} 
funktion getTotal() 
{ 
    var totalscore = 50; 
    var tempScore = 0; 
    var temp = 0; 
    var storeIndex = ""; 
    var myvalues = [ 1, 3, 4, 7, 9, 2, 53, 123, 324324, 221 ]; 
    while(tempScore < totalscore) 
    { 
     temp =getRandom(myvalues.length); 
     if(tempScore+myvalues[temp] <= totalscore) 
     { 
       tempScore += myvalues[temp]; 
       storeIndex += temp + " "; 
     } 
    } 
    alert("total score indexes are " + storeIndex); 
} 

我認爲它是理想的結果。