0

I am new to Java and trying to get the shortest path between several cities.

  • Start at some point (city) got through all the other cities and end at the same city

Parsing the date from JSON File:

{ "city": "City1", "latitude": 43.1641506, "longitude": 19.7600896 },
{ "city": "City2", "latitude": 60.4317477, "longitude": 10.0853171 },
{ "city": "City3", "latitude": 21.4317477, "longitude": 16.1854121 },
  • The output could be the optimal route is City1--> City3--> City2 --> City4 ....

My issue and question is is how to implement the City class that, any suggestions?

  • Are all cities linked directly to all other cities? If so that's an unusual problem - mostly travelling salesman problems have defined links between cities with defined costs. – sprinter Mar 18 '17 at 13:56
  • The title of the question concerns the TSP but your actual question is about how to represent a city elegantly. Is that correct? If so I suggest you change the title of the question because it really doesn't have anything to do with finding a path at this stage. – sprinter Mar 18 '17 at 13:59

1 Answers1

2

Ignoring the title of the question and answering your actual question directly:

  • I would suggest changing the name to City. It seems the class is intended to represent a city rather than an arbitrary point.
  • Unless there is some reason to expose the latitude and longitude through getters then I suggest not doing that. Better to encapsulate them in their own immutable class and have any logic to do with positions inside that class.

So I would suggest something like:

public class Position {
    private final double latitude;
    private final double longitude;

    public Position(double latitude, double longitude) {
        this.latitude = latitude;
        this.longitude = longitude;
    }

    public double distanceTo(Position other) {
        ...
    }
}

public class City {
    private final String name;
    private final Position position;

    public City(String name, double latitude, double longitude) {
        this.name = name;
        this.position = new Position(latitude, longitude);
    }

    public double distanceTo(City other) {
        return this.position.distanceTo(other.position);
    }
}

Those are clean simple classes that have a single purpose which will make your code easier to read and easier to change. They are also immutable (i.e. none of their values change after construction) which has lots of advantages (see answers to this question for details).

Community
  • 1
  • 1
sprinter
  • 27,148
  • 6
  • 47
  • 78