Untitled

 avatar
unknown
java
4 months ago
1.9 kB
6
Indexable
import java.util.List;
import java.util.ArrayList;

public class TransportSystem {
	private List<Station> stations;

	public TransportSystem(List<Station> stations) {
		this.stations = stations;
	}

	public Route findFastestRoute() {
		Station start = stations.getFirst();
		Station target = stations.getLast();
		
		List<Route> allRoutes = new ArrayList<Route>();
		List<Connection> current = new ArrayList<Connection>();
		
		recursion(start, 0, current, target, allRoutes);
		Route res = null;
		
		if(allRoutes.isEmpty()) {
			return null;
		} else{
			res = allRoutes.get(0);
		}
		for(Route s:allRoutes) {
			if(s.getTime()<res.getTime()) {
				res = s;
			}
		}
		return res;
	}
	
	public void recursion(Station current, int time, List<Connection> currentRoute, Station target, List<Route> allRoutes ) {
		if(current == target) {
			allRoutes.add(new Route(time, new ArrayList<>(currentRoute)));
			return;
		}
		//rekusrion itereiere über alle connections
		for(Connection c : current.getConnections()) {
			int currenttime= time+c.getTime(); //addiere die neue Zeit
			if(!currentRoute.isEmpty()) { //Falls ich vorher schone ein Station hatt, muss ich kontrollieren ob es eine Zeitreduktion gibt
				if(currentRoute.getLast().getClass()==c.getClass()) { //falls geliche Transportm. Zeitabzug
					if(c instanceof Bus) {
						currenttime-=2;
					}
					else if(c instanceof Tram) {
						currenttime-=5;
					}
					else {
						currenttime-=10;
					}
				}
				
			}
			currentRoute.add(c); //füge diese Route zu allen möglichen Routen hinzu
			
			recursion(returnStation(c.getNextStation()),currenttime,currentRoute, target, allRoutes); //rufe rekursiv die nächste connectiona auf
			currentRoute.removeLast();
		}
		
		
	}
	
	public Station returnStation(char name) {
		for(Station s : stations) {
			if(s.getName()==name) {
				return s;
			}
		}
		return null;
	}
}
Editor is loading...
Leave a Comment