Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we use array elements as a counters in java?

Tags:

java

arrays

import java.util.Random;

public class DemoArrayElement {

    public static void main(String arg[]) {
        Random rand = new Random();
        int[] freq = new int[7];

        for (int roll = 1; roll < 10; roll++) {
            ++freq[1 + rand.nextInt(6)];
        }
        System.out.println("FACE\tFREQUENCY");

        for (int face = 1; face < freq.length; face++) {
            System.out.println(face + "\t\t" + freq[face]);
        }
    }
}

Can someone please explain me this ++freq[1+rand.nextInt(6)]; line of code.

like image 406
Prakash Avatar asked Jun 28 '14 11:06

Prakash


2 Answers

This program simulates rolling a die 10 times. The array freq is used to count the frequencies each face value is rolled - the index represents the face value and the content the number of times it was rolled. So, e.g., freq[3] contains the number of times 3 was rolled.

Let's take a look at ++freq[1+rand.nextInt(6)]; and take it apart:

rand.nextInt(6) calls Java's random number generator (a java.util.Random instance) and asks it for a uniformly distributed random number between 0 and 5 (inclusive). Adding 1 to it gives you a random face value form a die - a number between 1 and 6.

Accessing this index in the freq array (freq[1+rand.nextInt(6)]), as noted above, will return the number of times this face value was randomly encountered. Since we just encountered it again, this number is incremented (the ++ operator).

like image 109
Mureinik Avatar answered Nov 15 '22 03:11

Mureinik


frec is an array containing 7 numeric elements.

++freq[1+rand.nextInt(6)]; means pre-increment a random element from an array.


Example: if the second element from the array is 5:

++freq[1]; will make it 6.

like image 36
sybear Avatar answered Nov 15 '22 04:11

sybear