0

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);
        }
}
3
  • 4
    d1 and d2 are 2 random numbers in range of 1-6. When combined they are within 12 making then a random index in counts. Commented Jun 12, 2018 at 4:58
  • 6
    It increases value at index d1 + d2 (random index) by 1. Commented Jun 12, 2018 at 4:58
  • yes it's not my code .If it was mine i did't asked Commented Jun 12, 2018 at 5:05

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You do not re-initialize the variable, you increment it by 1.

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.