Skip to content
Snippets Groups Projects
Commit def8e28a authored by Pedro Pablo Cardona Arroyave's avatar Pedro Pablo Cardona Arroyave
Browse files

Initial commit

parents
No related branches found
No related tags found
No related merge requests found
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CheckStyle-IDEA" serialisationVersion="2">
<checkstyleVersion>10.3.4</checkstyleVersion>
<scanScope>JavaOnly</scanScope>
<copyLibs>true</copyLibs>
<option name="thirdPartyClasspath" />
<option name="activeLocationIds" />
<option name="locations">
<list>
<ConfigurationLocation id="bundled-sun-checks" type="BUNDLED" scope="All" description="Sun Checks">(bundled)</ConfigurationLocation>
<ConfigurationLocation id="bundled-google-checks" type="BUNDLED" scope="All" description="Google Checks">(bundled)</ConfigurationLocation>
</list>
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GoogleJavaFormatSettings">
<option name="enabled" value="false" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/Real Task 9.iml" filepath="$PROJECT_DIR$/Real Task 9.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RunConfigurationProducerService">
<option name="ignoredProducers">
<set>
<option value="com.android.tools.idea.compose.preview.runconfiguration.ComposePreviewRunConfigurationProducer" />
</set>
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
public class Main {
public static void main(String[] args) {
Graph graph = new Graph();
graph.readAllNodes(Utils.readFile(Utils.generatePath("noder.txt")));
graph.readAllEdges(Utils.readFile(Utils.generatePath("kanter.txt")));
List<Edge> edges = Dijkstra.getShortestPath(graph,0,3);
int sum = 0;
for(Edge edge : edges){
System.out.println(edge.getStart().getNumber() + " -----> " +edge.getDestination().getNumber());
sum+= edge.getDrivingTime();
}
System.out.println("Final driving time is " + sum);
}
}
class Node{
private final int number;
private final double latitude;
private final double longitude;
private String[] typeArray;
private String name;
private final List<Edge> edges = new LinkedList<>();
public Node(int number, double latitude, double longitude) {
this.number = number;
this.latitude = latitude;
this.longitude = longitude;
}
public int getNumber() {
return number;
}
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
public String[] getTypeArray() {
return typeArray;
}
public String getName() {
return name;
}
public List<Edge> getEdges() {
return edges;
}
public void setName(String name){
this.name=name;
}
public void setType(String type){
if(typeArray == null){
this.typeArray = new String[6];
}
this.setInFreeSpace(type,this.getTypeArray());
}
private void setInFreeSpace(String type, String[] typeArray){
for(int i = 0; i<typeArray.length; i++){
if(typeArray[i]==null){
typeArray[i]=type;
i=typeArray.length;
}
}
}
public void addEdge(Node destination, int drivingTime, int distance, int speedLimit){
edges.add(new Edge(this,destination,drivingTime,distance,speedLimit));
}
public boolean isTypeOf(String typeName){
return Arrays.stream(typeArray).anyMatch(t -> t.equalsIgnoreCase(typeName));
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Node node)) return false;
return number == node.number;
}
@Override
public int hashCode() {
return Objects.hash(number);
}
}
class Edge implements Comparable<Edge> {
private final Node start;
private final Node destination;
private final int drivingTime;
private final int distance;
private final int speedLimit;
public Edge(Node start, Node destination, int drivingTime, int distance, int speedLimit) {
this.start = start;
this.destination = destination;
this.drivingTime = drivingTime;
this.distance = distance;
this.speedLimit = speedLimit;
}
public Node getStart() {
return start;
}
public Node getDestination() {
return destination;
}
public int getDrivingTime() {
return drivingTime;
}
public int getDistance() {
return distance;
}
public int getSpeedLimit() {
return speedLimit;
}
@Override
public int compareTo(Edge o) {
return Integer.compare(this.getDrivingTime(),o.getDrivingTime());
}
}
class Graph{
private final List<Node> nodes = new LinkedList<>();
public void setNodes(int number, double longitude, double latitude){
nodes.add(number, new Node(number,latitude,longitude));
}
public Node getNode(int index){
return nodes.get(index);
}
public void readAllNodes(List<String> data){
for (int i = 1; i<data.size(); i++){
//System.out.println(data.get(i));
String [] splitText = Utils.splitText(data.get(i),3);
//System.out.println(Arrays.toString(splitText));
this.setNodes(Integer.parseInt(splitText[0]),Double.parseDouble(splitText[1]),Double.parseDouble(splitText[2]));
}
}
public void readAllEdges(List<String> data){
for(int i = 1 ; i<data.size();i++){
String [] splitText = Utils.splitText(data.get(i),5);
System.out.println(Arrays.toString(splitText));
this.getNode(Integer.parseInt(splitText[0])).
addEdge(this.getNode(Integer.parseInt(splitText[1]))
,Integer.parseInt(splitText[2]),Integer.parseInt(splitText[3])
,Integer.parseInt(splitText[4]));
}
}
public void readNodeInformation(List<String> data){
for(String text : data){
if(!text.equals(data.get(0))){
String [] splitText = Utils.splitText(text,3);
this.setTypes(Integer.parseInt(splitText[0]),Integer.parseInt(splitText[1]),splitText[2]);
}
}
}
private void setTypes(int nodeNumber,int typeValue, String name){
Node node = this.getNode(nodeNumber);
if((typeValue&1) ==1) node.setType("Place name");
if((typeValue&2) == 2) node.setType("Gas station");
if((typeValue&4) == 4) node.setType("Charge station");
if((typeValue&8) == 8) node.setType("Eating place");
if((typeValue&16) == 16) node.setType("Drinking place");
if((typeValue&32) == 32) node.setType("Accommodation");
node.setName(name);
}
public int getNumberOfNodes(){
return nodes.size();
}
public int getNumberOfNodeByName(String name){
for(Node node: nodes){
if(node.getName() != null){
if(node.getName().equalsIgnoreCase(name)) {
return node.getNumber();
}
}
}
return -1;
}
}
class Dijkstra{
public static List<Edge> getShortestPath(Graph graph, int startNumber, int destinationNumber){
PriorityQueue<Edge> priorityQueue = new PriorityQueue<>();
Node startNode = graph.getNode(startNumber);
//boolean[] visitedNodes = new boolean[graph.getNumberOfNodes()];
int[] pathWeight = new int[graph.getNumberOfNodes()];
Arrays.fill(pathWeight, Integer.MAX_VALUE);
List<Edge>[] pathToNodes = new List[graph.getNumberOfNodes()];
//visitedNodes[startNumber] = true;
pathWeight[startNumber] = 0;
Arrays.fill(pathToNodes,new ArrayList<>());
priorityQueue.addAll(startNode.getEdges());
System.out.println("Debugging");
while (!priorityQueue.isEmpty()){
Edge nextEdge = priorityQueue.poll();
Node nextNode = nextEdge.getDestination();
int currentSum = pathWeight[nextEdge.getStart().getNumber()] + nextEdge.getDrivingTime();
if(currentSum < pathWeight[nextNode.getNumber()]){
pathWeight[nextNode.getNumber()] = currentSum;
pathToNodes[nextNode.getNumber()] = new ArrayList<>(pathToNodes[nextEdge.getStart().getNumber()]);
//pathToNodes[nextNode.getNumber()].addAll(pathToNodes[nextEdge.getStart().getNumber()]);
pathToNodes[nextNode.getNumber()].add(nextEdge);
priorityQueue.addAll(nextNode.getEdges());
}
}
return pathToNodes[destinationNumber];
}
public static ListOfPlaces getClosePlaces(Graph graph, int startNumber, String typOfPlace, int numberOfPlaces){
ListOfPlaces listOfPlaces = new ListOfPlaces(numberOfPlaces);
PriorityQueue<Edge> priorityQueue = new PriorityQueue<>();
Node startNode = graph.getNode(startNumber);
//boolean[] visitedNodes = new boolean[graph.getNumberOfNodes()];
int[] pathWeight = new int[graph.getNumberOfNodes()];
Arrays.fill(pathWeight, Integer.MAX_VALUE);
List<Edge>[] pathToNodes = new List[graph.getNumberOfNodes()];
//visitedNodes[startNumber] = true;
pathWeight[startNumber] = 0;
Arrays.fill(pathToNodes,new ArrayList<>());
priorityQueue.addAll(startNode.getEdges());
System.out.println("Debugging");
while (!priorityQueue.isEmpty()){
Edge nextEdge = priorityQueue.poll();
System.out.println(nextEdge.getStart()+ " -------> " + nextEdge.getDestination() + " Time: " + nextEdge.getDrivingTime());
Node nextNode = nextEdge.getDestination();
int currentSum = pathWeight[nextEdge.getStart().getNumber()] + nextEdge.getDrivingTime();
if(currentSum < pathWeight[nextNode.getNumber()]){
pathWeight[nextNode.getNumber()] = currentSum;
pathToNodes[nextNode.getNumber()] = new ArrayList<>(pathToNodes[nextEdge.getStart().getNumber()]);
//pathToNodes[nextNode.getNumber()].addAll(pathToNodes[nextEdge.getStart().getNumber()]);
pathToNodes[nextNode.getNumber()].add(nextEdge);
priorityQueue.addAll(nextNode.getEdges());
if (nextNode.getName() != null){
if(nextNode.isTypeOf(typOfPlace)){
listOfPlaces.addPlace(nextNode,currentSum);
}
}
}
}
return listOfPlaces;
}
}
class ListOfPlaces{
private final Map<Node, Integer> placeList = new HashMap<>();
int maxDriveTime = 0;
private final int maxSize;
public ListOfPlaces(int maxSize){
this.maxSize = maxSize;
}
public void addPlace(Node node, int driveTime){
if(placeList.size()<this.maxSize){
placeList.put(node,driveTime);
if(driveTime> this.maxDriveTime) this.maxDriveTime = driveTime;
}
else{
fixPlaceList(node,driveTime);
}
}
private void fixPlaceList(Node node, int driveTime){
if (placeList.containsKey(node) && placeList.get(node)<driveTime){
placeList.put(node,driveTime);
}
else{
Node testNode;
int testDriveTime;
Node[] nodeList = (Node[]) placeList.keySet().toArray();
for(int i = 0; i<maxSize;i++){
if(placeList.get(nodeList[i])<driveTime){
testNode = nodeList[i];
testDriveTime = placeList.get(nodeList[i]);
placeList.remove(testNode);
placeList.put(node,driveTime);
fixPlaceList(testNode,testDriveTime);
}
}
}
}
}
class Utils{
/**
* Static method that return a list that contains all the lines from an extern txt file
* by using the NIO library.
* @param fileName String name of the file to read.
* @return List<String> List that contains all the lines of the file.
*/
public static List<String> readFile(String fileName){
List<String> data = null;
Path path= Paths.get(fileName);
try{
data = Files.readAllLines(path);
}catch(IOException e){
e.printStackTrace();
}
return data;
}
/**
* Static method that generates an absolute path of a file that
* must be allocated in the same folder that this code to work correctly.
* @param fileName String name of the file.
* @return String absolute path of the file.
*/
public static String generatePath(String fileName){
Path currentDirectoryPath = Paths.get("").toAbsolutePath();
return currentDirectoryPath + System.getProperty("file.separator") +fileName;
}
public static String[] splitText(String string, int numberOfWords){
String[] splitText = new String[numberOfWords];
StringBuilder sb = new StringBuilder();
int index = 0;
for (int i = 0; i<string.length();i++){
if(Character.isWhitespace(string.charAt(i))){
String word = sb.toString();
if(!word.isBlank()){
splitText[index]=word;
index++;
sb = new StringBuilder();
}
} else{
sb.append(string.charAt(i));
}
if(i == string.length()-1){
splitText[index] = sb.toString();
}
}
return splitText;
}
}
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment