C
C
Clean Coder2020-01-16 12:14:32
Java
Clean Coder, 2020-01-16 12:14:32

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;
}

But then Road(Spb, Msk) and Road(Msk. Spb) modeling the same track will be two different objects. How can it be better then?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
T
tsarevfs, 2020-01-16
@HustleCoder

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.

A
antonwx, 2020-01-16
@antonwx

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;
}

If there are more cities, it makes sense to use sets instead of listing cities in separate variables.
Ps I wrote from a mobile phone, there may be errors

A
Alexey Cheremisin, 2020-01-16
@leahch

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 question

Ask a Question

731 491 924 answers to any question