开发者

Random function which result is a given totalscore from array values

there is a totalscore given, e.g. 50 and a array with some values:

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

I want to have a random function which gives me the value (or position) from array so 开发者_开发技巧that all selected values are the same live the value in totalscore.

Has anybody an idea?


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

I think its the desired result.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜