Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Update an array

 
Pan Niko
Ranch Hand
Posts: 86
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I have an integer array size of ten. Im trying to create a method that each time, will store in array the ten recent calculations. For example if i do 40 calculations in array i want to each time storing the 10 most recent. How i can achieve this?

thank you
 
Greg Charles
Sheriff
Posts: 2987
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Something like a rolling buffer? You need to keep a count of the calculations you do, and when it gets to 10, reset to 0. Then store the result at the index shown by the calculation count.


Another thing you can do is never reset the calculation count, and compute the index as count % 10.
 
Pan Niko
Ranch Hand
Posts: 86
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If each time reset the counter, that's mean the next time i will add something, will go to array[0] right? I looking something like if array is full and want to add one more, very first element deleted, move rest of elements one place up and and the new element at the last place.

Also, i didnt get your point with remainder.
 
Greg Charles
Sheriff
Posts: 2987
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You don't reset the counter to 0 each time ... just every 10th time.

The remainder operator lets you cycle through the array without checking the value of the counter and setting it back to 0 when it gets too big. That's because 10 % 10 is 0, 11 % 10 is 1 and so on. Any non-negative integer % 10 will be a an integer from 0 to 9, just like the indexes of your array.

If you want to shift the results every time, then loop thru the indexes from 1 to 9 and copy the array values to indexes 0 to 8, then put the new result in the array at index 9.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic