Skip to content
Snippets Groups Projects
Commit cc185aa7 authored by Gianluca's avatar Gianluca
Browse files

Da finire

parent 7bd71622
Branches
No related tags found
No related merge requests found
Showing
with 413 additions and 13 deletions
### IntelliJ IDEA ###
out/
!**/src/main/**/out/
!**/src/test/**/out/
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store
\ No newline at end of file
......@@ -7,5 +7,16 @@
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$USER_HOME$/Downloads/graphLib.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$USER_HOME$/Downloads/graphLib.jar!/doc" />
</JAVADOC>
<SOURCES />
</library>
</orderEntry>
</component>
</module>
\ No newline at end of file
package PACKAGE_NAME;public class BFS {
import it.uniupo.graphLib.Graph;
import it.uniupo.graphLib.GraphInterface;
import java.awt.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
public class BFS {
private GraphInterface myGraph;
BFS(GraphInterface g) {
myGraph = g;
}
//Con questa variamente utilizzi founded che è un array di Booleani, in questo modo puoi fare accesso posizionale ed ottimizzi l'algoritmo
public ArrayList<Integer> getNodesInOrderOfVisit(int sorgente) {
if (this.myGraph.getOrder() <= sorgente) {
throw new IllegalArgumentException("Sorgente errata");
}
ArrayList<Integer> returnList = new ArrayList<>();
returnList.add(sorgente);
boolean[] founded = new boolean[myGraph.getOrder()];
Queue<Integer> queue = new LinkedList<>();
founded[sorgente] = true;
queue.add(sorgente);
while (!queue.isEmpty()) {
int v = queue.remove();
Iterable<Integer> neighbors = this.myGraph.getNeighbors(v);
for (int neighbor : neighbors) {
if (!founded[neighbor]) {
founded[neighbor] = true;
queue.add(neighbor);
returnList.add(neighbor);
}
}
}
return returnList;
}
}
import it.uniupo.graphLib.*;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Graph myGraph = new UndirectedGraph("nodes: 5; edges: (3,4) weight 5; (1,2) weight -4; (0,4) weight 3; (1,4) weight 0");
System.out.println(myGraph);
System.out.println(myGraph.getOutEdges(4));
BFS myBFS = new BFS(myGraph);
System.out.println(myBFS.getNodesInOrderOfVisit(4));
}
}
\ No newline at end of file
# Pedaggi autostradali
#### (Esame proposto il 19/09/2023)
Si vuole scrivere un programma per elaborare statistiche sui pedaggi autostradali pagati dagli automobilisti lungo l'autostrada A4 Torino-Milano. Il file **pedaggi.txt** elenca ciascuna tratta autostradale, una per riga, con il relativo pedaggio, nel formato:
casello1;casello2;pedaggio
dove *casello1* e *casello2* sono due stringhe che indicano l'inizio e la fine della tratta autostradale, identificandola univocamente. *pedaggio* è un numero reale che rappresenta il costo del pedaggio per quella tratta. Le tratte autostradali sono riportate in ordine consecutivo lungo la direzione Torino-Milano. Si noti però che l’autostrada può essere percorsa in entrambi i sensi di marcia (ossia, anche da Milano verso Torino).
Un secondo file **auto.txt** riporta la lista delle automobili (identificate dal numero di targa) che sono transitate lungo l'autostrada A4, con l'indicazione del casello di entrata, quello di uscita e il giorno di percorrenza:
targa;casello1;casello2;giorno
La stessa targa può comparire più volte nel file: significa che l'automobile è entrata più volte in autostrada (in date differenti).
Per ogni targa, il programma deve visualizzare in output:
1. il pedaggio totale pagato
2. il numero totale di tratte autostradali percorse
3. il numero di ingressi distinti.
L'ordine con cui sono elencate le targhe è indifferente.
Infine, il programma deve visualizzare in output la targa dell'automobile che ha pagato il pedaggio più alto.
## Esempio
### Contenuto del file pedaggi.txt
Torino;Settimo Torinese;1.30
Settimo Torinese;Volpiano;1.00
Volpiano;Rondissone;2.10
Rondissone;Borgo d'Ale;2.10
Borgo d'Ale;Santhia;1.30
Santhia;Carisio;0.30
Carisio;Balocco;0.70
Balocco;Greggio;0.90
Greggio;Biandrate;1.00
Biandrate;Novara;1.00
Novara;Marcallo Mesero;3.20
Marcallo Mesero;Arluno;0.70
Arluno;Rho;0.90
Rho;Milano;2.90
### Contenuto del file auto.txt
FI245LE;Torino;Santhia;4/9/2024
BY010TE;Torino;Milano;7/9/2024
EX456OR;Carisio;Balocco;7/9/2024
EX456OR;Rho;Santhia;8/9/2024
BY010TE;Novara;Borgo d'Ale;11/9/2024
TR472UE;Biandrate;Greggio;12/9/2024
TR472UE;Milano;Torino;14/9/2024
### Esempio di output
FI245LE: 7.80 pedaggio pagato (5 tratte percorse in 1 ingressi)
BY010TE: 24.60 pedaggio pagato (20 tratte percorse in 2 ingressi)
EX456OR: 9.40 pedaggio pagato (9 tratte percorse in 2 ingressi)
TR472UE: 20.40 pedaggio pagato (15 tratte percorse in 2 ingressi)
L'auto che ha pagato il pedaggio maggiore ha targa BY010TE.
\ No newline at end of file
# Default ignored files
/shelf/
/workspace.xml
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="openjdk-21" 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$/Lab2.iml" filepath="$PROJECT_DIR$/Lab2.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/../../.." vcs="Git" />
</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$/TestGraph" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$USER_HOME$/Downloads/graphLib.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$USER_HOME$/Downloads/graphLib.jar!/doc" />
</JAVADOC>
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library" scope="TEST">
<library name="JUnit5.8.1">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/junit/jupiter/junit-jupiter/5.8.1/junit-jupiter-5.8.1.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/junit/jupiter/junit-jupiter-api/5.8.1/junit-jupiter-api-5.8.1.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/opentest4j/opentest4j/1.2.0/opentest4j-1.2.0.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/junit/platform/junit-platform-commons/1.8.1/junit-platform-commons-1.8.1.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/apiguardian/apiguardian-api/1.1.2/apiguardian-api-1.1.2.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/junit/jupiter/junit-jupiter-params/5.8.1/junit-jupiter-params-5.8.1.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/junit/jupiter/junit-jupiter-engine/5.8.1/junit-jupiter-engine-5.8.1.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/junit/platform/junit-platform-engine/1.8.1/junit-platform-engine-1.8.1.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
</component>
</module>
\ No newline at end of file
......@@ -4,9 +4,13 @@ import it.uniupo.graphLib.UndirectedGraph;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.*;
public class TestGraph {
//Inizio Test ES1
@Test
void testCreate() {
GraphInterface grafo = new DirectedGraph(3);
......@@ -66,4 +70,41 @@ public class TestGraph {
numeroNodi = bfsTest.getNodesInOrderOfVisit(3).size(); //<<-terza chiamata, stesso oggetto, parametro diverso
assertEquals(4, numeroNodi);
}
//Inizio Test Es2
@Test
public void testDistanzaUnNodo() {
GraphInterface grafo = new UndirectedGraph("1");
BFS bfsTest = new BFS(grafo);
assertEquals(0, bfsTest.getDistance(0)[0]);
}
@Test
public void testDistanzaDueNodiUnArco() {
GraphInterface grafo = new UndirectedGraph("2; 0,1;");
BFS bfsTest = new BFS(grafo);
assertEquals(1, bfsTest.getDistance(0)[1]);
}
@Test
public void testDistanzaGrafoComplesso() {
GraphInterface grafo = new UndirectedGraph("4; 0,1; 0,2; 1,3; 2,3");
BFS bfsTest = new BFS(grafo);
assertEquals(0, bfsTest.getDistance(2)[2]);
assertEquals(1, bfsTest.getDistance(2)[0]);
assertEquals(bfsTest.getDistance(2)[0], bfsTest.getDistance(2)[3]);
assertEquals(2, bfsTest.getDistance(2)[1]);
}
@Test
public void testInitDistanza() {
GraphInterface grafo = new UndirectedGraph("4; 0,1; 0,2; 1,3; 2,3");
BFS bfsTest = new BFS(grafo);
int[] expectedResultWithSource2 = {1, 2, 0, 1};
int[] expectedResultWithSource3 = {2, 1, 1, 0};
assertArrayEquals(expectedResultWithSource2, bfsTest.getDistance(2));
assertArrayEquals(expectedResultWithSource3, bfsTest.getDistance(3));
}
}
File added
File added
File added
import it.uniupo.graphLib.GraphInterface;
import it.uniupo.graphLib.UndirectedGraph;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.*;
public class BFS {
......@@ -14,6 +12,34 @@ public class BFS {
this.myGraph = g;
}
//ES 1
//Con questa variamente utilizzi founded al posto di S.
//Founded è un array di Booleani, in questo modo puoi fare accesso posizionale ed ottimizzi l'algoritmo. (La contains ha costo n)
public ArrayList<Integer> getNodesInOrderOfVisit(int sorgente) {
if (this.myGraph.getOrder() <= sorgente) {
throw new IllegalArgumentException("Sorgente errata");
}
ArrayList<Integer> returnList = new ArrayList<>();
returnList.add(sorgente);
boolean[] founded = new boolean[myGraph.getOrder()];
Queue<Integer> q = new LinkedList<>();
founded[sorgente] = true;
q.add(sorgente);
while (!q.isEmpty()) {
int u = q.remove();
Iterable<Integer> neighbors = this.myGraph.getNeighbors(u);
for (int v : neighbors) {
if (!founded[v]) {
founded[v] = true;
q.add(v);
returnList.add(v);
}
}
}
return returnList;
}
/*
public ArrayList<Integer> getNodesInOrderOfVisit(int sorgente) {
if (this.myGraph.getOrder() <= sorgente) {
throw new IllegalArgumentException("Dimensione della Sorgente errata");
......@@ -27,14 +53,117 @@ public class BFS {
while (!q.isEmpty()) {
int u = q.remove();
List<Integer> neighbors = (List<Integer>) this.myGraph.getNeighbors(u);
for (Integer neighbor : neighbors) {
if (!s.contains(neighbor)) {
s.add(neighbor);
q.add(neighbor);
valueToReturn.add(neighbor);
for (Integer v : neighbors) {
if (!s.contains(v)) {
s.add(v);
q.add(v);
valueToReturn.add(v);
}
}
}
return valueToReturn;
}
*/
//ES 2
public int[] getDistance(int sorgente) {
if (this.myGraph.getOrder() <= sorgente) {
throw new IllegalArgumentException("Dimensione della Sorgente errata");
}
boolean[] founded = new boolean[this.myGraph.getOrder()];
Queue<Integer> q = new LinkedList<>();
int[] returnArray = new int[this.myGraph.getOrder()];
Arrays.fill(returnArray, -1);
founded[sorgente] = true;
q.add(sorgente);
returnArray[sorgente] = 0;
while (!q.isEmpty()) {
int u = q.remove();
Iterable<Integer> neighbors = this.myGraph.getNeighbors(u);
for (Integer v : neighbors) {
if (!founded[v]) {
founded[v] = true;
q.add(v);
returnArray[v] = returnArray[u] + 1;
}
}
}
return returnArray;
}
//Funzioni aggiuntive che trovi qui
//https://www.dir.uniupo.it/pluginfile.php/1252187/mod_resource/content/23/BFSjava.pdf
public int getDistance(int sorgente, int nodo) {
if (this.myGraph.getOrder() <= sorgente) {
throw new IllegalArgumentException("Nodo sorgente non presente nel grafo");
}
if (this.myGraph.getOrder() <= nodo) {
throw new IllegalArgumentException("Nodo destinazione non presente nel grafo");
}
int[] distance = getDistance(sorgente);
return distance[nodo];
}
public GraphInterface bfsTree(int sorgente) {
if (this.myGraph.getOrder() <= sorgente) {
throw new IllegalArgumentException("Dimensione della Sorgente errata");
}
boolean[] founded = new boolean[this.myGraph.getOrder()];
Queue<Integer> q = new LinkedList<>();
GraphInterface alberoBFSdallaSorgente = new UndirectedGraph(this.myGraph.getOrder());
founded[sorgente] = true;
q.add(sorgente);
while (!q.isEmpty()) {
int u = q.remove();
Iterable<Integer> neighbors = this.myGraph.getNeighbors(u);
for (Integer v : neighbors) {
if (!founded[v]) {
founded[v] = true;
q.add(v);
alberoBFSdallaSorgente.addEdge(u, v);
//returnArray[v] = returnArray[u] + 1;
}
}
}
return alberoBFSdallaSorgente;
}
//Da finire
public ArrayList<Integer> camminoMinimo(int sorgente, int nodo) {
if (this.myGraph.getOrder() <= sorgente) {
throw new IllegalArgumentException("Dimensione della Sorgente errata");
}
if (this.myGraph.getOrder() <= nodo) {
throw new IllegalArgumentException("Dimensione della Destinazione errata");
}
boolean[] founded = new boolean[this.myGraph.getOrder()];
Queue<Integer> q = new LinkedList<>();
ArrayList<Integer> returnArray = new ArrayList<>();
founded[sorgente] = true;
q.add(sorgente);
returnArray.add(sorgente);
while (!q.isEmpty()) {
int u = q.remove();
Iterable<Integer> neighbors = this.myGraph.getNeighbors(u);
for (Integer v : neighbors) {
if (!founded[v]) {
founded[v] = true;
q.add(v);
returnArray.addLast(v);
if (v == nodo) {
return returnArray;
}
}
}
}
return null;
}
}
import it.uniupo.graphLib.Graph;
import it.uniupo.graphLib.UndirectedGraph;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Graph mioGrafo = new UndirectedGraph("3; 0 1; 1 2; 0 2;"); //Num Nodi + Archi
BFS prova = new BFS(mioGrafo);
System.out.println(prova.getNodesInOrderOfVisit(0));
Graph mioGrafo = new UndirectedGraph("6; 0 4; 4 3; 1 3; 1 2; 0 2; 0 5; 5 2"); //Num Nodi + Archi
BFS mioBFS = new BFS(mioGrafo);
int source = 4;
int destination = 1;
System.out.println(">>> Sorgente delle Operazione: " + source);
System.out.println(">>> Destinazione delle Operazione: " + destination);
System.out.println(">>> Visita BFS sul Grafo: " + mioBFS.getNodesInOrderOfVisit(source));
System.out.println(">>> Distanza dei nodi dalla sorgente: " + Arrays.toString(mioBFS.getDistance(source)));
System.out.println(">>> Distanza del nodo da " + source + " a " + destination + ": " + mioBFS.getDistance(source, destination));
System.out.println(">>> Albero di Visita con rafice la sorgente: \n" + mioBFS.bfsTree(source));
//Da qui in poi da finire
System.out.println(">>> Cammino più corto per andare da sorgente a destinazione: " + mioBFS.camminoMinimo(source, destination));
}
}
\ No newline at end of file
File added
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment