What is a good data collection for presenting horse racing?

I have a course object, which is an ArrayList that accepts Horse objects. I chose ArrayList because it is easy to implement. However, the disadvantage of using ArrayList is that I cannot easily track the positions of each horse without spending an expensive iteration through the collection. For example, if I want to find 2 horses that are within X distance of each other, I will have to go through n^2 times.

Is there a better strategy for this?

EDIT: A lot of requests for a specific model of my race, so I'll tell you here.

The model is updated at each iteration. Thus, each horse has its own speed, acceleration, distance, etc., And each iteration through the collection updates these values. There is a requirement that the horse be next to another, it will slow down, which I plan to do by comparing their "distance traveled".

+5
source share
2 answers

Suppose you can add Horse objects to the TreeSet collection. You must implement the Comparable interface in the Horse class and override the compareTo () method, thus sorting the horses by distance. Then you can use certain operations on the treeSet, such as "upper ()", which will return the first horse that will work more than the specified one, etc. You can learn more about this collection. Also, all operations are O (logN) in terms of time complexity.

+1
source

If you keep a sorted list of updates for the horse’s position, then you can determine all pairs of horses X at a distance from each other in one scan, N times (a tradeoff that keeps the list sorted is log (n) per update).

If you want all horses X to be at a distance from the given horse H. You can also save the horse's hash map in the array index and potentially avoid repeating the entire array.

0
source

Source: https://habr.com/ru/post/1243834/


All Articles