Shanu Reddy
Shanu Reddy

Reputation: 35

array usage in a loop

What does counts[d1 + d2] += 1 really do? Here is my code:

//call simulate(10)
public static void simulate(int rolls) {
        Random rand = new Random();
        int[] counts = new int[13];

        for (int k = 0; k < rolls; k++) {
            int d1 = rand.nextInt(6) + 1;
            int d2 = rand.nextInt(6) + 1;

            System.out.println(d1+"+"+d2+"+"+"="+(d1+d2));

            counts[d1 + d2] += 1;
        }

        for (int k = 2; k <= 12; k++) {
            System.out.println(k + "'s=\t" + counts[k] + "\t" + 100.0 * counts[k]/rolls);
        }
}

Upvotes: 0

Views: 63

Answers (1)

404 Brain Not Found
404 Brain Not Found

Reputation: 605

d1 and d2are 2 random numbers in range of 1-6. When combined the max result they can give is 12 making them a random index in counts[].

Now for the next part : counts[d1 + d2] += 1;

here += is a binary operator. What that means that you need 2 operands along for it to perform any action.

What it does is

counts[d1 + d2] += 1;

Gets interpreted as

counts[d1 + d2] = counts[d1 + d2] + 1;

And what you are doing here is re-initializing the variable in the array with index [d1 + d2] and adding 1 to it.

Upvotes: 2

Related Questions