tags:

views:

259

answers:

4

I generated 100 random numbers from 0-9, i am supposed to count how many times each number appears. Storing it in an array of 10 integers and count it.

heres 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);




  }
+9  A: 

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!

Adamski
+1 I like your attitude, with someone who's starting.
KLE
+6  A: 
  • Create an array for the counts (i.e. an array of length 10). The values will start of as 0 automatically
  • Iterate through the integers array, and for each element, increment its current count (i.e. the current value in the "counts array" for that result)

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.

Jon Skeet
+1 for not giving away an obvious homework question.
geowa4
A: 
int[] count = {0,0,0,0,0,0,0,0,0,0};
for(int i: integers) {
    count[i]++;
}
sepp2k
`{0,0,0,0,0,0,0,0,0,0}` is done for you by default.
geowa4
It's sad you're giving him the answer to his own homework.
KLE
A: 

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...

 <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. Forget this then!!!

Sohnee
It's sad you're giving him the answer to his own homework.
KLE