Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a good data collection to represent a horse race?

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.

like image 336
Evil Washing Machine Avatar asked Nov 08 '22 19:11

Evil Washing Machine


1 Answers

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.

like image 52
Nikolay Tomitov Avatar answered Nov 15 '22 13:11

Nikolay Tomitov