Answer the question
In order to leave comments, you need to log in
What structure to choose for an array where the order is not important, but is determined only by the elements?
For example, simulating a road:
class Road {
City city1, city2;
}
Answer the question
In order to leave comments, you need to log in
There are several options for storing undirected graphs.
1. Store any of the roads, and when accessing them, check for the presence of one of the 2
2. Always store only the road from the city with a lower number to the city with a larger one.
3. Keep 2 ways always.
Depending on the task, it may be more convenient to use one of these methods.
You do not need to create a new object, but create a selector method that will check the existence of the road and if it exists, return the existing one, if not, then create a new one. In this case, you can implement the check like this:
Set<Road> roads = new HashSet<Road>();
Road getRoad(c1, c2){
for(Road r:roads) if((r.city1.equals(c1) && r.city2.equals(c2)) || (r.city2.equals(c1) && r.city1.equals(c2))) return r;
Road r = new Road(c1, c2);
roads.add(r);
return r;
}
Yes, even if the road passes through 10 cities - use TreeSet().
SortedSet road1 = TreeSet<City>();
road1.add("Mos");
road1.add("Spb");
SortedSet road2 = TreeSet<City>();
road2.add("Spb");
road2.add("Mos");
assert road1.equals(road2);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question