I made this code to check out how "random" the random function is.
Array.prototype.random = function() {
var index = Math.floor(this.length*Math.random());
return this[index];
}
var arr = new Array('a', 'b', 'c', 'd', 'e');
var count = [0, 0, 0, 0, 0]; //I want to ask about this part
for (var i = 0; i < 10000; i++) {
var val = arr.random();
console.log(val);
switch (val) {
case 'a':
count[0]++;
break;
case 'b':
count[1]++;
break;
case 'c':
count[2]++;
break;
case 'd':
count[3]++;
break;
case 'e':
count[4]++;
break;
}
}
for (var i = 0; i < count.length; i++) console.log(count[i]);
In the process, I couldn't think of better way to initialize the 'count' array. Using that way, it would get really repetitive. I would have to put thousand 0 if my 'arr' has 1000 elements. Can anybody suggest better way for me?
If I don't initialize each element of 'count' array as 0, I get NaN.