# Help!

#1

Basically I'm trying to count the numbers of 1 in 60 different random numbers.
But I don't know how to sum N1s in this exercise.

``````for(var i = 0; i < 60; i++)
{
var array = Math.floor((Math.random() * 6) + 1);
//console.log(array);
var N1 = 0;
if(array === 1){
N1++;
console.log(N1);

};
};``````

#2

Did not catch what are you trying to do. Inside the loop you have:

``````var array = Math.floor((Math.random() * 6) + 1);
var N1 = 0;``````

So every new iteration rewrites `var array` by new value, `var N1` always equals to 0 and `if(array === 1)` returns false. So I didn't understood what this code should do.

My solution:

``````var array = [];
var sum = 0;
for(var i = 0; i < 60; i++)
{
array.push( Math.floor((Math.random() * 6) + 1) );
sum += array[i];
}

console.log(sum);``````

I declared variables array and sum. .push() method add a new item to an array. `sum += array[i];` means that the previous value I add value of array's element in current iteration.
If you need to know how many elements in array you can use array .length property:

``var length = array.length;``

But in your case we initialize array from 0 to 60, so array has 60 elements.

Look at my example, maybe it can help you. If not, please provide more details what you want to do.

#3

What I want to do is to count the number of 1, for example, if for 5 random
numbers which are (1,5,4,8,1), then the frequency of number 1 is 2.
The problem is idk how to count the numbers in an array ( maybe it's not an
array ).

#4

I think that array is a good solution. So, first of all you need to generate an array with random numbers:

``````var array = [];
for(var i = 0; i < 10; i++) {
array.push( Math.floor((Math.random() * 6) + 1) );
}``````

When array was created now we can find the frequency of number 1:

``````var frequency = 0;
for(var i = 0; i < array.length; i++) {
if (array[i] === 1) { // every element we compare with 1
frequency++;
}
}

console.log("frequency:", frequency);
// or
if (frequency > 0) {
console.log("frequency:", frequency);
} else {
console.log("array doesn't have number 1");
]``````

Better solution can be with functions.

So your problem was inside the for loop:

``````var array = Math.floor((Math.random() * 6) + 1);
var N1 = 0;``````

Keyword var declare new variable. That's why every iteration recreated `var array` and `var N1`. So these variables should be outside and before for loop.
Also here:

``var array = Math.floor((Math.random() * 6) + 1);``

Actually it is not an array. As I said you need to use .push method to add elements to an array. In your case it was just variable which with every iteration has a new random value.

#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.