I have a race course object which is an ArrayList which takes in Horse objects. I chose ArrayList because it's easy to implement. However, the downside of using an ArrayList is I can't easily keep track of the positions of each horse without going expensively iterating through the collection. For example, if I want to find 2 horses which are within an X amount of distance to each other, I would have to iterate through n^2
times.
Is there a better strategy to do this?
EDIT: A lot of requests to be specific on my race model, so I'll elaborate here.
The model is updated every iteration. So every horse has its own speed, acceleration, distance travelled etc. and every iteration through the collection updates these values. There is a requirement for if a horse is near another it will slow down, which I plan on doing by comparing their 'distance travelled' values.
I suppose you may add Horse objects to TreeSet Collection. You should implement a Comparable interface in Horse class and override compareTo() method, thus sorting horses by distance. Then you may use specific operations on treeSet like "higher()" that will return the first horse that is ran more than given one, etc. You can read more about this collection here. Also all operations are O(lgN) by time complexity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With