0

For a task I must create a function that generates a number between 1 and 9. This function needs to be called 100 times. Then I need to create a 9 element array that will keep count of the number of times each number appears. My code is below. Currently a number is being generated and the array changes. However the array doesn't change correctly, it changes the wrong index and I don't know why, can anyone help? Any advice on how to call the function 100 times as well would be appreciated. It doesn't matter how it works or looks, I don't need to have a set format. Thanks in advance!

    <script>
    function numberGenerate () {
     var nmbrGen = Math.floor(Math.random()*8 +1) ;
     return nmbrGen;
    } 

    function numberChange () {

    document.write(numberGenerate(), "<br>");

    var numberArray = [0,0,0,0,0,0,0,0,0];

     if (numberGenerate() == 1){
       numberArray[0]++;
     }

     else if (numberGenerate() == 2) {
       numberArray[1]++;
     }

     else if (numberGenerate() == 3) {
       numberArray[2]++;
     }

     else if (numberGenerate() == 4) {
       numberArray[3]++;
     }

     else if (numberGenerate() == 5) {
       numberArray[4]++;
     }

     else if (numberGenerate() == 6) {
       numberArray[5]++;
     }

     else if (numberGenerate() == 7) {
       numberArray[6]++;
     }

     else if (numberGenerate() == 8) {
       numberArray[7]++;
     }

     else {numberArray[8]++;}

     document.write(numberArray);       
     }

    </script>
</head>

5
  • 3
    Erm... have you considered just doing numberArray[numberGenerate()-1]++? Commented Oct 21, 2016 at 14:30
  • Keep in mind that every time you call numberGenerate(), you get a new random number! Commented Oct 21, 2016 at 14:30
  • Are you familiar with for loops? Also, you could simplify your if chain a lot. If numberGenerate() === 5 then you're going to numberArray[4]. When numberGenerate() === 6 then you're going to numberArray[5]. Do you see a relationship between the number you're generating and the number you're using to access the array? Commented Oct 21, 2016 at 14:30
  • Wouldn't it be easier to do just numberArray[numberGenerate() - 1] += 1; instead all those if checks...? Just sayin'... Commented Oct 21, 2016 at 14:31
  • Ah, so it was calling different numbers to the one it was displaying, good to know! I am not that familiar with for loops and didn't know a way to do so with them. The task was fairly vague so i wasn't sure the best way to go about it. The array doesn't start at 0, its from 1-9. That's why the value of the number and the index don't match. Commented Oct 21, 2016 at 14:58

6 Answers 6

3

You call numberGenerate() in each if statement what means that it will generate a new number every if statement. Your code would work if you generate the number one time and compare it, something like that:

var nRand = numberGenerate();

if (nRand ==...

It is needless to say that your code is not well written (to say it in a harmless way). You could just replace all of your if statements with the following:

numberArray[nRand - 1]++;

And to run it 100 times:

for (var i = 0; i < 100; i++) {
    var nRand = numberGenerate();
    console.log('run ' + (i+1) + ': ' + nRand);
    numberArray[nRand - 1]++;
}
Sign up to request clarification or add additional context in comments.

Comments

0

You get the wrong index because you are assigning 1 to 0, 2 to 1 and so on. Try this:

var numberArray = [0,0,0,0,0,0,0,0,0,0];
var times = 100; // Run this 100 times

for(var i = 0; i < times; ++i) {
    number = numberGenerate();
    if(number < numberArray.length) { //Checks, just to be sure
        numberArray[number]++;
    }
}

PS: with your random function you will get numbers from 1 to 8 both included, but never 9. I'm not sure if that was your intention. This would fix it:

function numberGenerate () {
    return Math.floor(Math.random() * 9 + 1);
} 

6 Comments

Oops! My bad, I've just been programming in C
This method is great! My only problem is it doesn't ever seem to display a value for the first index. A value of 1 should make the index change, do you know of a way to do so? My current code is:
<script> function numberGenerate () { var nmbrGen = Math.floor(Math.random()*8 +1) ; return nmbrGen; } function numberChange() { var numberArray = [0,0,0,0,0,0,0,0,0]; var times = 100; for (var i = 0; i< times; i++) { number = numberGenerate(); if(number <= numberArray.length){ numberArray[number]++; } } document.write(numberArray); } </script>
@HudsonMckie that's because you are generating numbers from 1 to 9. Indexs start with 0, so it will be always blank. I did it like this so that the number matched the index, but you can encode it how you like. For example you can save 1's count into 0 index 2's into 1, etc, but you must substract one to the index every time.
It was meant to go to 9, that was a dumb mistake on my part,. So would I need to put numberArray[number] -1 in the loop? Would that solve it?
|
0

Try this:

function numberGenerate () {
  var nmbrGen = Math.floor(Math.random()*9 +1) ;
  return nmbrGen;
} 

function randomGenerationStats(howManyTimes) {
  var stats = {};

  for(var i = 0; i < howManyTimes; i++) {
    var randomNumber = numberGenerate();

    if(stats[randomNumber]) {
        ++stats[randomNumber];
    } else {
        stats[randomNumber] = 1;
    }
  }

  return stats;
}

console.log(randomGenerationStats(100));

Prints:

Object {1: 14, 2: 13, 3: 11, 4: 8, 5: 12, 6: 18, 7: 6, 8: 5, 9: 14}

The output in console will be object whch keys are numbers from 1-9 with values how many times they occurred.

Comments

0

Hm.. I'll ad my answer

Hope this help, even if some answer do the tricks.

var numberArray = [0,0,0,0,0,0,0,0,0];
var nmbrGen;
for(var i=0; i<100; i++) { // From 0 to 99, so 100 time.
    nmbrGen = Math.floor(Math.random() * 9 + 1); // 9 + 1 = (Max - Min + 1 + Min)
    console.log("Generated : "+nmbrGen);
    numberArray[nmbrGen-1]++;
}

Comments

0

Firstly, there's a bug in your numberGenerate function. It will only produce numbers from 1 to 8. What you need to do is change the corresponding line to Math.floor(9 * Math.random() + 1).

Secondly, every successive call to numberGenerate creates a new random number. Call the function once and store the value once per loop iteration. So, you must insert a line like var rand = numberGenerate(); at the top of the numberChange function, and replace every call to numberGenerate following with rand.

Thirdly, notice a pattern with the number in your if conditions and the statement underneath. The number in the condition is from 0-8, and the number in the statement beneath is one more than it. You can simply all of that into one statement after realizing this pattern by replacing all the if statements with this single line numberArray[rand - 1]++.

And lastly, you forgot the most important part! You need to iterate 100 times! Include a for loop surrounding the code in the numberChange function.

After you've made all these changes, the code should resemble this.

function numberGenerate () {
    return Math.floor(9 * Math.random() + 1);
}

function numberChange () {
    var numberArray = [0, 0, 0, 0, 0, 0, 0, 0, 0];

    for(var i = 0; i < 100; i++) {
        var rand = numberGenerate();
        document.write(rand, "<br>");
        numberArray[rand - 1]++;
    }

    document.write(numberArray);
}

Comments

0

If I understood you right, you want to count the occurrences of these 9 random numbers?

It is easier if you use an associative array (dictionary) for this. You have a function that generates random numbers between 1 and 9. I have created an associative array with 9 keys (from 1 to 9), and set the respective value to 0. That value is the "occurrence counter". Then we loop through 100 times, as you requested and change the counter of that value. Something like this:

function numberChange() {
  // read this array as "value 1 has 0 occurrences, value 2 has 0 occurrences, etc."
  var numberArray = { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9:0 }
  for (var i = 0; i < 100; i++) {
    // generate 100 random numbers and add the relative counter value.
    var newRandomNumber = numberGenerate();
    numberArray[newRandomNumber]++;
  }
  //  loop through all keys and display the respective occurrence counter value.
  for (var key in numberArray) {
    console.log("Number: " + key + " Occurrences: " + numberArray[key]);
  }
}
function numberGenerate() {
  var nmbrGen = Math.floor(Math.random() * 9 + 1);
  return nmbrGen;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.