简体   繁体   English

计算随机生成的数字列表中的频率

[英]Count Frequency in a Randomly Generated List of Numbers

I generated 100 random numbers from 0-9, I am supposed to count how many times each number appears. 我从0-9生成100个随机数,我应该计算每个数字出现的次数。 Storing it in an array of 10 integers and count it. 将它存储在10个整数的数组中并计算它。

Here's what I have so far, I cant figure out the count part. 这是我到目前为止所做的,我无法弄清楚计数部分。

Random r = new Random();
int[] integers = new int[100];

for (int i=0; i<integers.length; i++)
{
  integers[i] = (r.nextInt(10)+0);
}

Here's a clue: You need to take the approach whereby the array index represents the number being stored, and the value of that array element equals the frequency. 这是一个线索:您需要采用数组索引表示存储的数字的方法,并且该数组元素的等于频率。

Good luck! 祝好运!

  • Create an array for the counts (ie an array of length 10). 为计数创建一个数组(即长度为10的数组)。 The values will start of as 0 automatically 值将自动从0开始
  • Iterate through the integers array, and for each element, increment its current count (ie the current value in the "counts array" for that result) 遍历integers数组,并为每个元素递增其当前计数(即该结果的“计数数组”中的当前值)

I'd rather not give the full code here as it's clearly homework, but if you post your progress we can help if you run into difficulties. 我宁愿不在这里给出完整的代码,因为它显然是家庭作业,但如果你发布你的进展,我们可以帮助你遇到困难。

int[] count = {0,0,0,0,0,0,0,0,0,0};
for(int i: integers) {
    count[i]++;
}

You've flagged your question with JavaScript, so here is a JavaScript method of finding out how many instances of a random number between 1 and 10 (inclusive) you get... 你用JavaScript标记了你的问题,所以这里有一个JavaScript方法,可以找出1到10(含)之间的随机数的实例数...

    <div id="output">
        <p>Calculating...</p>
    </div>
    <script type="text/javascript">
    var range = 10;

    var counts = new Array();
    for (i=1; i<=range; i++) {
        counts[i] = 0;
    }

    var ints = new Array();
    for (i=0; i<100; i++) {
        var randomnumber = Math.floor(Math.random()*(range+1));
        ints[i] = randomnumber;
        counts[randomnumber] = parseInt(counts[randomnumber]) + 1;
    }

    var output = "";
    for (i=1; i<=range; i++) {
        output += i + " - " + counts[i] + "<br>";
    }

    document.getElementById("output").innerHTML = output;
    </script>

Update - cool - so the JavaScript tag has been removed. 更新 - 很酷 - 所以JavaScript标记已被删除。 Forget this then!!! 忘了这个!!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM