0

little stuck, please help! Trying to write code using the random number generator,initialize an array of size 50, with integer values in the range 0..49 and compute the frequency of the numbers in the range 10..19. Here's what I have so far:

var array_nums = new Array (50);
var frequency = 0;

for (i=0; i<array_nums.length; i++){
    array_nums [i] = Math.floor ((Math.random() * 50));
    for (i=0; i<array_nums.length; i++){ 
        if((i>=10) && (i<=19)){
            frequency = frequency+ [i];
            alert(frequency);
        }
    }
}
indubitablee
  • 8,136
  • 2
  • 25
  • 49
stuck
  • 27
  • 4

2 Answers2

0

var array_nums = [];
var frequency = 0;

for (i=0; i < 50; i++) {
    var randInt = Math.floor(Math.random()*50)
    array_nums.push(randInt);
    if(randInt >= 10 && randInt <= 19) {
     frequency = frequency + 1;
    }
}
document.getElementById('results').innerHTML = array_nums + '<br/><br/>frequency: ' + frequency;
<div id="results"></div>
indubitablee
  • 8,136
  • 2
  • 25
  • 49
0

We fill an array with 50 random numbers, then reduce it to an object that has the number of times each element between 10 and 19 occured, with a final "all" element that has the number of times all of the numbers between 10 and 19 occured.

var array_nums = Array.apply(null, Array(50)).map(function() { 
    return Math.floor(Math.random() * 50);
}).reduce(function (acc, curr) {
    if (curr >= 10 && curr <= 19) {
        acc[curr] = (acc[curr] || 0) + 1;
        acc["all"]++;
    }
    return acc;
}, {all:0});

document.getElementById("results").innerHTML = JSON.stringify(array_nums);
<div id="results">
dave
  • 62,300
  • 5
  • 72
  • 93