简体   繁体   中英

Finding the sum of an array Java

I've searched all over the place and I can't seem to find a solution to my problem. I have an array that contains how many times my random walk lands on a specified location. Now I need to find the sum of this array but for some reason the sum always gives 1000:(

int[] hx;
hx = new int[1000];
int hx_sum = 0;
for (int i = -500; i < 500; i++) {
   hx[i+500] = totals.get(i);
}
for(int w = 0; w < 1000; w++){
   hx_sum += hx[w];
}
System.out.print(hx_sum);
}

The result of my hx_sum is ALWAYS = 1000.

You do 1000 steps (NBR_WALK), and in each step you increment one point in your hash map. The map was initialized with all 0 before.

Quick question: What is the sum of 1000 increments?

Do you see the error? It is not really an error, it is just mathematically certain that no different result is possible.

If you don't see it, I suggest you take a dice, throw it 10 times, and increment each time the array element corresponding to the number (which you can draw on paper). Initialize the array with all 0 before you start. Then compute the sum of the array. It can only ever be 10.

This could look like:

Dice      1s         2s      3s     4s     5s    6s
  1      x
  5      x                                 x
  3      x                   x             x
  1      xx                  x             x

Now count the x s in the last line. Its 4, because you were rolling the dice 4 times, and every time you added 1 x . Also, in each line, there is exactly one more x then in the preceding line. Thus, after 1000 rounds you will have 1000 x.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM