如何隨機選擇任意范圍內的數字並使用JavaScript數組加在一起

[英]How to randomly select numbers within an arbitrary range and add together using JavaScript arrays


I am trying to write some JavaScript that will select some random numbers from an array and then add those selected numbers to make a single total value.

我正在嘗試編寫一些JavaScript,它將從數組中選擇一些隨機數,然后添加這些選定的數字以生成單個總值。

For example if i had var array = [1, 22, 5, 88, 3, 105, 7, 88, 987] i would then like the code to select however many numbers it wants at random(amount selected changes every time it runs) and then add them together but i am not sure if this is even possible.

例如,如果我有var array = [1,22,5,88,3,10,5,7,88,987],那么我會希望代碼隨機選擇它想要的多個數字(每次運行時選擇的數量都會改變) )然后將它們加在一起,但我不確定這是否可能。

I am new to JavaScript so i have only managed to write code that adds all the array elements together instead of selecting at random.

我是JavaScript的新手,所以我只設法編寫將所有數組元素添加到一起而不是隨機選擇的代碼。

var arr = [1,2,3,4,5,6];
var total=0;
    for(var i in arr) { total += arr[i]; }

My code is very basic so please excuse me for this i'm still learning. Thank You

我的代碼非常基本,所以請原諒我,我還在學習。謝謝

3 个解决方案

#1


1  

You could use the Math.rand() function in order to create a random index. In terms of code:

您可以使用Math.rand()函數來創建隨機索引。在代碼方面:

// The array with your elements
var arr = [1,2,3,4,5,6];

// An array that will keep track of the elements we have selected.
var selectedIndex = [];

// The sum.
var sum=0;

// times is the number of elements we want to select from arr and sum them.
for(var i=0; i<times; i++)
{
    // Get a random integer number in the range [0, arr.length]
    var index = Math.floor(Math.rand()*arr.length);

    // check if the index we created has been selected again.
    if(selectedIndex.indexOf(index)>-1)
    {
        // The created index has been selected again. So we must select another one,
        // in order we get an item from the array only once.        
        while(selectedIndex.indexOf(index)>-1)
            index = Math.floor(Math.rand()*arr.length);    
    }

    // We push the created index in the selected index array.
    selectedIndex.push(index);

    // We increase the sum.
    sum+=arr[index];
}

update

更新

In order the above to be executed the caller should provide a value for the variable called times. This value in order to be valid shouldn't exceed the length of the array called arr.

為了執行上述操作,調用者應該為名為times的變量提供一個值。要使該值有效,該值不應超過名為arr的數組的長度。

Another way more elegant, it would be to follow on this part the solution that deitch suggested in his post.

另一種更優雅的方式,就是在這一部分中遵循deitch在帖子中提出的解決方案。

var times = Math.floor((Math.random() * arr.length)+1)

The above should be placed just before the for statement.

上面應該放在for語句之前。

#2


1  

I think you are looking something like:

<code>
function randormTotal() {
             var arr = [1,2,3,4,5,6];
             var total=0;
             var noOfData = 3;
             for(var i =0; i<noOfData; i++) { 
               var pos = Math.floor(Math.random()*(arr.length-1)) + 1;             
               total += arr[pos];
             }
             alert(total);
         }
</code>

#3


0  

FYI, this method actually modifies the array, so you might want to copy it.

僅供參考,此方法實際上修改了數組,因此您可能希望復制它。

// randomly select how many elements you will pick
var i, total = 0, elmsCount = Math.floor((Math.random() * arr.length)+1), current;
// select that many elements
for (i=0; i<elmsCount; i++) {
  current = Math.floor(Math.random()*arr.length);
  total += arr.splice(current,1)[0];
}
// total is now the sum

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/11/26/720f1b80dabf3df001ba4c5fb6f9e33f.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com