diff --git a/.gitignore b/.gitignore index 767e5c7..342b181 100644 --- a/.gitignore +++ b/.gitignore @@ -22,6 +22,8 @@ hs_err_pid* # IntelliJ -.idea/* -**/.idea/* +#.idea/* +#**/.idea/* +**/.vs/* +**/x64/* diff --git a/2018/pitagora/pitagora.iml b/2017-18/pitagora/pitagora.iml similarity index 100% rename from 2018/pitagora/pitagora.iml rename to 2017-18/pitagora/pitagora.iml diff --git a/2018/pitagora/src/it/unive/dais/po/pitagora/Lato.java b/2017-18/pitagora/src/it/unive/dais/po/pitagora/Lato.java similarity index 100% rename from 2018/pitagora/src/it/unive/dais/po/pitagora/Lato.java rename to 2017-18/pitagora/src/it/unive/dais/po/pitagora/Lato.java diff --git a/2018/pitagora/src/it/unive/dais/po/pitagora/Main.java b/2017-18/pitagora/src/it/unive/dais/po/pitagora/Main.java similarity index 100% rename from 2018/pitagora/src/it/unive/dais/po/pitagora/Main.java rename to 2017-18/pitagora/src/it/unive/dais/po/pitagora/Main.java diff --git a/2018/pitagora/src/it/unive/dais/po/pitagora/Numeric.java b/2017-18/pitagora/src/it/unive/dais/po/pitagora/Numeric.java similarity index 100% rename from 2018/pitagora/src/it/unive/dais/po/pitagora/Numeric.java rename to 2017-18/pitagora/src/it/unive/dais/po/pitagora/Numeric.java diff --git a/2018/tinylib/src/it/unive/dais/po/tinylib/Main.java b/2017-18/tinylib/src/it/unive/dais/po/tinylib/Main.java similarity index 100% rename from 2018/tinylib/src/it/unive/dais/po/tinylib/Main.java rename to 2017-18/tinylib/src/it/unive/dais/po/tinylib/Main.java diff --git a/2018/tinylib/src/it/unive/dais/po/tinylib/MyIterable.java b/2017-18/tinylib/src/it/unive/dais/po/tinylib/MyIterable.java similarity index 100% rename from 2018/tinylib/src/it/unive/dais/po/tinylib/MyIterable.java rename to 2017-18/tinylib/src/it/unive/dais/po/tinylib/MyIterable.java diff --git a/2018/tinylib/src/it/unive/dais/po/tinylib/MyIterator.java b/2017-18/tinylib/src/it/unive/dais/po/tinylib/MyIterator.java similarity index 100% rename from 2018/tinylib/src/it/unive/dais/po/tinylib/MyIterator.java rename to 2017-18/tinylib/src/it/unive/dais/po/tinylib/MyIterator.java diff --git a/2018/tinylib/src/it/unive/dais/po/tinylib/MyList.java b/2017-18/tinylib/src/it/unive/dais/po/tinylib/MyList.java similarity index 100% rename from 2018/tinylib/src/it/unive/dais/po/tinylib/MyList.java rename to 2017-18/tinylib/src/it/unive/dais/po/tinylib/MyList.java diff --git a/2018/tinylib/src/it/unive/dais/po/tinylib/MyNode.java b/2017-18/tinylib/src/it/unive/dais/po/tinylib/MyNode.java similarity index 100% rename from 2018/tinylib/src/it/unive/dais/po/tinylib/MyNode.java rename to 2017-18/tinylib/src/it/unive/dais/po/tinylib/MyNode.java diff --git a/2018/tinylib/src/it/unive/dais/po/tinylib/MyNodeList.java b/2017-18/tinylib/src/it/unive/dais/po/tinylib/MyNodeList.java similarity index 100% rename from 2018/tinylib/src/it/unive/dais/po/tinylib/MyNodeList.java rename to 2017-18/tinylib/src/it/unive/dais/po/tinylib/MyNodeList.java diff --git a/2018/tinylib/src/it/unive/dais/po/tinylib/MyNodeListIterator.java b/2017-18/tinylib/src/it/unive/dais/po/tinylib/MyNodeListIterator.java similarity index 100% rename from 2018/tinylib/src/it/unive/dais/po/tinylib/MyNodeListIterator.java rename to 2017-18/tinylib/src/it/unive/dais/po/tinylib/MyNodeListIterator.java diff --git a/2018/tinylib/src/it/unive/dais/po/tinylib/MySequence.java b/2017-18/tinylib/src/it/unive/dais/po/tinylib/MySequence.java similarity index 100% rename from 2018/tinylib/src/it/unive/dais/po/tinylib/MySequence.java rename to 2017-18/tinylib/src/it/unive/dais/po/tinylib/MySequence.java diff --git a/2018/tinylib/src/it/unive/dais/po/tinylib/NotFoundException.java b/2017-18/tinylib/src/it/unive/dais/po/tinylib/NotFoundException.java similarity index 100% rename from 2018/tinylib/src/it/unive/dais/po/tinylib/NotFoundException.java rename to 2017-18/tinylib/src/it/unive/dais/po/tinylib/NotFoundException.java diff --git a/2018/tinylib/src/it/unive/dais/po/tinylib/OverloadTest.java b/2017-18/tinylib/src/it/unive/dais/po/tinylib/OverloadTest.java similarity index 100% rename from 2018/tinylib/src/it/unive/dais/po/tinylib/OverloadTest.java rename to 2017-18/tinylib/src/it/unive/dais/po/tinylib/OverloadTest.java diff --git a/2018/tinylib/tinylib.iml b/2017-18/tinylib/tinylib.iml similarity index 100% rename from 2018/tinylib/tinylib.iml rename to 2017-18/tinylib/tinylib.iml diff --git a/2019/TinyJDK/TinyJDK.iml b/2018-19/TinyJDK/TinyJDK.iml similarity index 100% rename from 2019/TinyJDK/TinyJDK.iml rename to 2018-19/TinyJDK/TinyJDK.iml diff --git a/2019/TinyJDK/out/production/TinyJDK/META-INF/TinyJDK.kotlin_module b/2018-19/TinyJDK/out/production/TinyJDK/META-INF/TinyJDK.kotlin_module similarity index 100% rename from 2019/TinyJDK/out/production/TinyJDK/META-INF/TinyJDK.kotlin_module rename to 2018-19/TinyJDK/out/production/TinyJDK/META-INF/TinyJDK.kotlin_module diff --git a/2019/TinyJDK/out/production/TinyJDK/TinyJDK.iml b/2018-19/TinyJDK/out/production/TinyJDK/TinyJDK.iml similarity index 100% rename from 2019/TinyJDK/out/production/TinyJDK/TinyJDK.iml rename to 2018-19/TinyJDK/out/production/TinyJDK/TinyJDK.iml diff --git a/2019/TinyJDK/src/collections/Main.java b/2018-19/TinyJDK/src/collections/Main.java similarity index 100% rename from 2019/TinyJDK/src/collections/Main.java rename to 2018-19/TinyJDK/src/collections/Main.java diff --git a/2019/TinyJDK/src/collections/MyAbstractArrayListSet.java b/2018-19/TinyJDK/src/collections/MyAbstractArrayListSet.java similarity index 100% rename from 2019/TinyJDK/src/collections/MyAbstractArrayListSet.java rename to 2018-19/TinyJDK/src/collections/MyAbstractArrayListSet.java diff --git a/2019/TinyJDK/src/collections/MyArrayList.java b/2018-19/TinyJDK/src/collections/MyArrayList.java similarity index 100% rename from 2019/TinyJDK/src/collections/MyArrayList.java rename to 2018-19/TinyJDK/src/collections/MyArrayList.java diff --git a/2019/TinyJDK/src/collections/MyArrayListSet.java b/2018-19/TinyJDK/src/collections/MyArrayListSet.java similarity index 100% rename from 2019/TinyJDK/src/collections/MyArrayListSet.java rename to 2018-19/TinyJDK/src/collections/MyArrayListSet.java diff --git a/2019/TinyJDK/src/collections/MyArrayListSortedSet.java b/2018-19/TinyJDK/src/collections/MyArrayListSortedSet.java similarity index 100% rename from 2019/TinyJDK/src/collections/MyArrayListSortedSet.java rename to 2018-19/TinyJDK/src/collections/MyArrayListSortedSet.java diff --git a/2019/TinyJDK/src/collections/MyCollection.java b/2018-19/TinyJDK/src/collections/MyCollection.java similarity index 100% rename from 2019/TinyJDK/src/collections/MyCollection.java rename to 2018-19/TinyJDK/src/collections/MyCollection.java diff --git a/2019/TinyJDK/src/collections/MyIterable.java b/2018-19/TinyJDK/src/collections/MyIterable.java similarity index 100% rename from 2019/TinyJDK/src/collections/MyIterable.java rename to 2018-19/TinyJDK/src/collections/MyIterable.java diff --git a/2019/TinyJDK/src/collections/MyIterator.java b/2018-19/TinyJDK/src/collections/MyIterator.java similarity index 100% rename from 2019/TinyJDK/src/collections/MyIterator.java rename to 2018-19/TinyJDK/src/collections/MyIterator.java diff --git a/2019/TinyJDK/src/collections/MyList.java b/2018-19/TinyJDK/src/collections/MyList.java similarity index 100% rename from 2019/TinyJDK/src/collections/MyList.java rename to 2018-19/TinyJDK/src/collections/MyList.java diff --git a/2019/TinyJDK/src/collections/MyListMap.java b/2018-19/TinyJDK/src/collections/MyListMap.java similarity index 100% rename from 2019/TinyJDK/src/collections/MyListMap.java rename to 2018-19/TinyJDK/src/collections/MyListMap.java diff --git a/2019/TinyJDK/src/collections/MyMap.java b/2018-19/TinyJDK/src/collections/MyMap.java similarity index 100% rename from 2019/TinyJDK/src/collections/MyMap.java rename to 2018-19/TinyJDK/src/collections/MyMap.java diff --git a/2019/TinyJDK/src/collections/MySet.java b/2018-19/TinyJDK/src/collections/MySet.java similarity index 100% rename from 2019/TinyJDK/src/collections/MySet.java rename to 2018-19/TinyJDK/src/collections/MySet.java diff --git a/2019/TinyJDK/src/collections/MySortedSet.java b/2018-19/TinyJDK/src/collections/MySortedSet.java similarity index 100% rename from 2019/TinyJDK/src/collections/MySortedSet.java rename to 2018-19/TinyJDK/src/collections/MySortedSet.java diff --git a/2019/TinyJDK/src/collections/NotFoundException.java b/2018-19/TinyJDK/src/collections/NotFoundException.java similarity index 100% rename from 2019/TinyJDK/src/collections/NotFoundException.java rename to 2018-19/TinyJDK/src/collections/NotFoundException.java diff --git a/2019/TinyJDK/src/collections/Pair.java b/2018-19/TinyJDK/src/collections/Pair.java similarity index 100% rename from 2019/TinyJDK/src/collections/Pair.java rename to 2018-19/TinyJDK/src/collections/Pair.java diff --git a/2019/TinyJDK/src/misc/AbstractErrors.java b/2018-19/TinyJDK/src/misc/AbstractErrors.java similarity index 100% rename from 2019/TinyJDK/src/misc/AbstractErrors.java rename to 2018-19/TinyJDK/src/misc/AbstractErrors.java diff --git a/2019/TinyJDK/src/misc/ErrorInInvoke.java b/2018-19/TinyJDK/src/misc/ErrorInInvoke.java similarity index 100% rename from 2019/TinyJDK/src/misc/ErrorInInvoke.java rename to 2018-19/TinyJDK/src/misc/ErrorInInvoke.java diff --git a/2019/TinyJDK/src/misc/GenericSort.java b/2018-19/TinyJDK/src/misc/GenericSort.java similarity index 100% rename from 2019/TinyJDK/src/misc/GenericSort.java rename to 2018-19/TinyJDK/src/misc/GenericSort.java diff --git a/2019/TinyJDK/src/patterns/consumer_producer/Main.java b/2018-19/TinyJDK/src/patterns/consumer_producer/Main.java similarity index 100% rename from 2019/TinyJDK/src/patterns/consumer_producer/Main.java rename to 2018-19/TinyJDK/src/patterns/consumer_producer/Main.java diff --git a/2019/TinyJDK/src/patterns/singleton/Main.java b/2018-19/TinyJDK/src/patterns/singleton/Main.java similarity index 100% rename from 2019/TinyJDK/src/patterns/singleton/Main.java rename to 2018-19/TinyJDK/src/patterns/singleton/Main.java diff --git a/2019/TinyJDK/src/patterns/singleton/RandomSingleton.java b/2018-19/TinyJDK/src/patterns/singleton/RandomSingleton.java similarity index 100% rename from 2019/TinyJDK/src/patterns/singleton/RandomSingleton.java rename to 2018-19/TinyJDK/src/patterns/singleton/RandomSingleton.java diff --git a/2019/TinyJDK/src/threads/SynchronizedMain.java b/2018-19/TinyJDK/src/threads/SynchronizedMain.java similarity index 100% rename from 2019/TinyJDK/src/threads/SynchronizedMain.java rename to 2018-19/TinyJDK/src/threads/SynchronizedMain.java diff --git a/2019/TinyJDK/src/threads/pool/Main.java b/2018-19/TinyJDK/src/threads/pool/Main.java similarity index 100% rename from 2019/TinyJDK/src/threads/pool/Main.java rename to 2018-19/TinyJDK/src/threads/pool/Main.java diff --git a/2019/TinyJDK/src/threads/pool/ThreadPool.java b/2018-19/TinyJDK/src/threads/pool/ThreadPool.java similarity index 100% rename from 2019/TinyJDK/src/threads/pool/ThreadPool.java rename to 2018-19/TinyJDK/src/threads/pool/ThreadPool.java diff --git a/2019/lezione18-19/lezione18-19.iml b/2018-19/lezione18-19/lezione18-19.iml similarity index 100% rename from 2019/lezione18-19/lezione18-19.iml rename to 2018-19/lezione18-19/lezione18-19.iml diff --git a/2019/lezione18-19/out/production/lezione18-19/META-INF/lezione18-19.kotlin_module b/2018-19/lezione18-19/out/production/lezione18-19/META-INF/lezione18-19.kotlin_module similarity index 100% rename from 2019/lezione18-19/out/production/lezione18-19/META-INF/lezione18-19.kotlin_module rename to 2018-19/lezione18-19/out/production/lezione18-19/META-INF/lezione18-19.kotlin_module diff --git a/2019/lezione18-19/src/Main__Collections.java b/2018-19/lezione18-19/src/Main__Collections.java similarity index 100% rename from 2019/lezione18-19/src/Main__Collections.java rename to 2018-19/lezione18-19/src/Main__Collections.java diff --git a/2019/lezione18-19/src/Main__Experiments.java b/2018-19/lezione18-19/src/Main__Experiments.java similarity index 100% rename from 2019/lezione18-19/src/Main__Experiments.java rename to 2018-19/lezione18-19/src/Main__Experiments.java diff --git a/2019/lezione18-19/src/Main__Functional.java b/2018-19/lezione18-19/src/Main__Functional.java similarity index 100% rename from 2019/lezione18-19/src/Main__Functional.java rename to 2018-19/lezione18-19/src/Main__Functional.java diff --git a/2019/lezione18-19/src/collections/MyArrayList.java b/2018-19/lezione18-19/src/collections/MyArrayList.java similarity index 100% rename from 2019/lezione18-19/src/collections/MyArrayList.java rename to 2018-19/lezione18-19/src/collections/MyArrayList.java diff --git a/2019/lezione18-19/src/collections/MyCollection.java b/2018-19/lezione18-19/src/collections/MyCollection.java similarity index 100% rename from 2019/lezione18-19/src/collections/MyCollection.java rename to 2018-19/lezione18-19/src/collections/MyCollection.java diff --git a/2019/lezione18-19/src/collections/MyIterator.java b/2018-19/lezione18-19/src/collections/MyIterator.java similarity index 100% rename from 2019/lezione18-19/src/collections/MyIterator.java rename to 2018-19/lezione18-19/src/collections/MyIterator.java diff --git a/2019/lezione18-19/src/collections/Pair.java b/2018-19/lezione18-19/src/collections/Pair.java similarity index 100% rename from 2019/lezione18-19/src/collections/Pair.java rename to 2018-19/lezione18-19/src/collections/Pair.java diff --git a/2019/lezione18-19/src/zoo/Animale.java b/2018-19/lezione18-19/src/zoo/Animale.java similarity index 100% rename from 2019/lezione18-19/src/zoo/Animale.java rename to 2018-19/lezione18-19/src/zoo/Animale.java diff --git a/2019/lezione18-19/src/zoo/Cane.java b/2018-19/lezione18-19/src/zoo/Cane.java similarity index 100% rename from 2019/lezione18-19/src/zoo/Cane.java rename to 2018-19/lezione18-19/src/zoo/Cane.java diff --git a/2019/lezione18-19/src/zoo/Gatto.java b/2018-19/lezione18-19/src/zoo/Gatto.java similarity index 100% rename from 2019/lezione18-19/src/zoo/Gatto.java rename to 2018-19/lezione18-19/src/zoo/Gatto.java diff --git a/2019/lezione18-19/src/zoo/PastoreTedesco.java b/2018-19/lezione18-19/src/zoo/PastoreTedesco.java similarity index 100% rename from 2019/lezione18-19/src/zoo/PastoreTedesco.java rename to 2018-19/lezione18-19/src/zoo/PastoreTedesco.java diff --git a/2019-20/Lezioni/.idea/codeStyles/codeStyleConfig.xml b/2019-20/Lezioni/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 0000000..a55e7a1 --- /dev/null +++ b/2019-20/Lezioni/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/2019-20/Lezioni/.idea/description.html b/2019-20/Lezioni/.idea/description.html new file mode 100644 index 0000000..db5f129 --- /dev/null +++ b/2019-20/Lezioni/.idea/description.html @@ -0,0 +1 @@ +Simple Java application that includes a class with main() method \ No newline at end of file diff --git a/2019-20/Lezioni/.idea/inspectionProfiles/Project_Default.xml b/2019-20/Lezioni/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 0000000..6da4be7 --- /dev/null +++ b/2019-20/Lezioni/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,25 @@ + + + + \ No newline at end of file diff --git a/2019-20/Lezioni/.idea/misc.xml b/2019-20/Lezioni/.idea/misc.xml new file mode 100644 index 0000000..1e6469c --- /dev/null +++ b/2019-20/Lezioni/.idea/misc.xml @@ -0,0 +1,9 @@ + + + + + + + + \ No newline at end of file diff --git a/2019-20/Lezioni/.idea/modules.xml b/2019-20/Lezioni/.idea/modules.xml new file mode 100644 index 0000000..8617dec --- /dev/null +++ b/2019-20/Lezioni/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/2019-20/Lezioni/.idea/project-template.xml b/2019-20/Lezioni/.idea/project-template.xml new file mode 100644 index 0000000..1f08b88 --- /dev/null +++ b/2019-20/Lezioni/.idea/project-template.xml @@ -0,0 +1,3 @@ + \ No newline at end of file diff --git a/2019-20/Lezioni/.idea/uiDesigner.xml b/2019-20/Lezioni/.idea/uiDesigner.xml new file mode 100644 index 0000000..e96534f --- /dev/null +++ b/2019-20/Lezioni/.idea/uiDesigner.xml @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/2019-20/Lezioni/.idea/vcs.xml b/2019-20/Lezioni/.idea/vcs.xml new file mode 100644 index 0000000..b2bdec2 --- /dev/null +++ b/2019-20/Lezioni/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/2019-20/Lezioni/.idea/workspace.xml b/2019-20/Lezioni/.idea/workspace.xml new file mode 100644 index 0000000..6c92eb0 --- /dev/null +++ b/2019-20/Lezioni/.idea/workspace.xml @@ -0,0 +1,233 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + C:\Users\spano\AppData\Roaming\Subversion + + + + + 1583492471839 + + + + + + + + + + + + + + + + + + file://$PROJECT_DIR$/src/it/unive/dais/po2/other/ForEachTest.java + 12 + + + file://$PROJECT_DIR$/src/esercizi/EsercizioCache.java + 36 + + + + + + + \ No newline at end of file diff --git a/2019-20/Lezioni/Lezioni.iml b/2019-20/Lezioni/Lezioni.iml new file mode 100644 index 0000000..ac9b28d --- /dev/null +++ b/2019-20/Lezioni/Lezioni.iml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/2019-20/Lezioni/out/production/Lezioni/META-INF/Lezioni.kotlin_module b/2019-20/Lezioni/out/production/Lezioni/META-INF/Lezioni.kotlin_module new file mode 100644 index 0000000..a49347a Binary files /dev/null and b/2019-20/Lezioni/out/production/Lezioni/META-INF/Lezioni.kotlin_module differ diff --git a/2019-20/Lezioni/src/esercizi/Andrei.java b/2019-20/Lezioni/src/esercizi/Andrei.java new file mode 100644 index 0000000..b438d05 --- /dev/null +++ b/2019-20/Lezioni/src/esercizi/Andrei.java @@ -0,0 +1,154 @@ +package esercizi; + +import org.jetbrains.annotations.NotNull; + +import java.util.*; +import java.util.function.Function; + +public class Andrei { + + public static class Point { + public final double x, y, z; + + public Point(double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; + } + + public Point move(double dx, double dy, double dz) { + return new Point(this.x + dx, this.y + dy, this.z + dz); + } + + @Override + public String toString() { + return String.format("(%g, %g, %g)", x, y, z); + } + } + + public interface Solid extends Comparable { + double area(); + + double volume(); + + PositionedSolid at(Point origin); + + static int compareBy(Function f, S s1, S s2) { + return Double.compare(f.apply(s1), f.apply(s2)); + } + + static Comparator comparatorBy(Function f) { + return (s1, s2) -> compareBy(f, s1, s2); + } + + default int compareTo(Solid s) { + return compareBy(Solid::volume, this, s); + } + + } + + public interface Polyhedron extends Solid { + double perimeter(); + + @Override + PositionedPolyhedron at(Point origin); + } + + public interface PositionedSolid { + Point origin(); + } + + public interface PositionedPolyhedron extends PositionedSolid, Iterable { + } + + public static class Cube implements Polyhedron { + private double side; + + public Cube(double side) { + this.side = side; + } + + @Override + public double area() { + return 4 * Math.pow(side, 2); + } + + @Override + public double volume() { + return Math.pow(side, 3); + } + + @Override + public double perimeter() { + return side * 12; + } + + @Override + public PositionedPolyhedron at(Point origin) { + return new PositionedPolyhedron() { + @Override + public Point origin() { + return origin; + } + + @NotNull + @Override + public Iterator iterator() { + Point[] vertici = {origin, origin.move(side, 0, 0), origin.move(0, side, 0), origin.move(0, side, 0), origin.move(side, side, 0), origin.move(side, 0, side)/*ecc*/}; + return Arrays.asList(vertici).iterator(); + } + }; + } + + } + + static class Sphere implements Solid { + private double ray; + + public Sphere(double ray) { + this.ray = ray; + } + + @Override + public double area() { + return 4 * 3.14 * Math.pow(ray, 2); + } + + @Override + public double volume() { + return (4. / 3.) * 3.14 * Math.pow(ray, 3); + } + + @Override + public PositionedSolid at(Point origin) { + return new PositionedSolid() { + @Override + public Point origin() { + return origin; + } + }; + } + } + + public static void main(String[] args) { + + Cube cube1 = new Cube(11.), cube2 = new Cube(23.); + Sphere sphere1 = new Sphere(12.), sphere2 = new Sphere(35.); + List solids = List.of(cube1, cube2, sphere1, sphere2); + List cubes = new ArrayList<>(List.of(cube1, cube2)); + List spheres = List.of(sphere1, sphere2); + List polys = cubes; + + Collections.sort(cubes); + + + Point o = new Point(1., -1.5, 2.); + for (Polyhedron poly : polys) { + for (Point p : poly.at(o)) { + System.out.println(p); //question mark? + } + } + } + + +} diff --git a/2019-20/Lezioni/src/esercizi/DynamicDispatch.java b/2019-20/Lezioni/src/esercizi/DynamicDispatch.java new file mode 100644 index 0000000..ebd5a1f --- /dev/null +++ b/2019-20/Lezioni/src/esercizi/DynamicDispatch.java @@ -0,0 +1,73 @@ +package esercizi; + +public class DynamicDispatch { + + public static class A { + + public void m() { + System.out.println("A::m"); + } + + public void p(int n) {} + public void p(double n) {} + + } + /* + A + SLOT1: m --> A::m + SLOT2: p(int) --> A::p(int) + SLOT3: p(double) --> A::p(double) + + B + SUPER: A + SLOT1: m --> B::m + SLOT2: p(int) --> A::p(int) + SLOT3: p(double) --> A::p(double) + SLOT4: p(String) --> B::p(String) + SLOT5: q(String) --> B::q(String) + */ + + public static class B extends A { + + @Override + public void m() { + System.out.println("B::m"); + } + + public void p(String n) {} + public void q(String n) {} + } + + public static class C { + + public void a() {} + public void p(String n) {} + public void q(String n) {} + public void m() { + System.out.println("C::m"); + } + } + + /* + D + SUPER: B + SLOT1: m --> B::m + SLOT2: p(int) --> A::p(int) + SLOT3: p(double) --> A::p(double) + SLOT4: p(String) --> B::p(String) + SLOT5: q(String) --> D::q(String) + */ + public static class D extends B { + @Override + public void q(String s) {} + } + + public static void main(String[] args) { + A a = new B(); + a.m(); + + B b = new D(); + b.q("ciao"); + } + +} diff --git a/2019-20/Lezioni/src/esercizi/Es_RandomIterator.java b/2019-20/Lezioni/src/esercizi/Es_RandomIterator.java new file mode 100644 index 0000000..55aa55f --- /dev/null +++ b/2019-20/Lezioni/src/esercizi/Es_RandomIterator.java @@ -0,0 +1,65 @@ +package esercizi; + +import org.jetbrains.annotations.NotNull; + +import java.util.Iterator; +import java.util.Random; + +public class Es_RandomIterator { + + public static void main2(String[] args) { + Iterator it = new RandomIterator(10, -50, 20); + int cnt = 0; + while(it.hasNext()) { + int n = it.next(); + System.out.println(String.format("#%d: %d", cnt++, n)); + } + } + + public static void main(String[] args) { + int cnt = 0; + for (int n : new RandomSequence(100)) { + System.out.println(String.format("#%d: %d", cnt++, n)); + } + } + + private static class RandomSequence implements Iterable { + private int amount; + + public RandomSequence(int amount) { + this.amount = amount; + } + + @NotNull + @Override + public Iterator iterator() { + return new RandomIterator(amount, 0, 100); + } + } + + + private static class RandomIterator implements Iterator { + private static Random rnd = new Random(); + private int amount, a, b; + + public RandomIterator(int amount, int a, int b) { + assert b > a; + this.amount = amount; + this.a = a; + this.b = b; + } + + @Override + public boolean hasNext() { + return amount > 0; + } + + @Override + public Integer next() { + --amount; + return rnd.nextInt(b - a + 1) + a; + } + } + + +} diff --git a/2019-20/Lezioni/src/esercizi/Es_SkipIterator.java b/2019-20/Lezioni/src/esercizi/Es_SkipIterator.java new file mode 100644 index 0000000..103e7f4 --- /dev/null +++ b/2019-20/Lezioni/src/esercizi/Es_SkipIterator.java @@ -0,0 +1,60 @@ +package esercizi; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class Es_SkipIterator { + + public static class SkipArrayList extends ArrayList { + @Override + public Iterator iterator() { + // senza usare l'iteratore originale + return new Iterator() { + private int pos = 0; + @Override + public boolean hasNext() { + return pos < size(); + } + + @Override + public T next() { + T x = get(pos); + pos += 2; + return x; + } + }; + // usando l'iteratore originale + /*Iterator it = super.iterator(); + return new Iterator() { + @Override + public boolean hasNext() { + return it.hasNext(); + } + + @Override + public T next() { + T x = it.next(); + if (it.hasNext()) it.next(); + return x; + } + };*/ + } + } + + + public static void main(String[] args) { + List l = new SkipArrayList<>(); + for (int i = 0; i < 21; ++i) + l.add(i); + + Iterator it = l.iterator(); + while(it.hasNext()) { + int n = it.next(); + System.out.println(n); + } + } + + + +} diff --git a/2019-20/Lezioni/src/esercizi/EsercizioCache.java b/2019-20/Lezioni/src/esercizi/EsercizioCache.java new file mode 100644 index 0000000..91600e8 --- /dev/null +++ b/2019-20/Lezioni/src/esercizi/EsercizioCache.java @@ -0,0 +1,175 @@ +package esercizi; + +import it.unive.dais.po2.myjdk.Pair; +import org.jetbrains.annotations.NotNull; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.BiFunction; +import java.util.function.Supplier; + +public class EsercizioCache { + + + public static Pair cputime(Supplier f) { + long now0 = System.nanoTime(); + T r = f.get(); + long now1 = System.nanoTime(); + return new Pair<>(r, now1 - now0); + } + + // cache funzionale + + public static class FCache { + private final @NotNull BiFunction, K, V> f; + @NotNull + private final Map m = new HashMap<>(); + + public FCache(@NotNull BiFunction, K, V> f) { + this.f = f; + } + + @NotNull + public V lookup(@NotNull K k) { + if (m.containsKey(k)) { + V r = m.get(k); + System.out.println(String.format("hit(%s) = %s", k, r)); + return r; + } else { + V v = f.apply(this, k); + m.put(k, v); + return v; + } + } + } + + // cache astratta + + public static abstract class AbstractCache { + @NotNull + private final Map m = new HashMap<>(); + + protected AbstractCache() {} + + @NotNull + protected abstract V onMiss(@NotNull K k); + + @NotNull + protected V recur(@NotNull K k) { + return lookup(k); + } + + @NotNull + public V lookup(@NotNull K k) { + if (m.containsKey(k)) { + V r = m.get(k); + System.out.println(String.format("hit(%s) = %s", k, r)); + return r; + } else { + V v = onMiss(k); + m.put(k, v); + return v; + } + } + } + + + + + public static void main(String[] args) { + AbstractCache cache1 = new AbstractCache<>() { + @NotNull + @Override + protected Long onMiss(@NotNull Integer n) { + return n < 2 ? 1 : recur(n - 1) + recur(n - 2); + } + }; + + } + + + + // functional version + + public static long cacheFib(FCache c, int n) { + return n < 2 ? 1 : c.lookup(n - 1) + c.lookup(n - 2); + } + + public static long slowFib(int n) { + return n < 2 ? 1 : slowFib(n - 1) + slowFib(n - 2); + } + + public static void main3(String[] args) { + final int N = 45; + + // slowFib + for (int i = 0; i < N; ++i) { + final int n = i; + Pair r = cputime(() -> slowFib(n)); + System.out.println(String.format("slowFib(%d) = %d [%g s]", n, r.first, ((double) r.second / 1000000000.))); + } + // cacheFib + FCache cache1 = new FCache<>(EsercizioCache::cacheFib); + for (int i = 0; i < N; ++i) { + final int n = i; + Pair r = cputime(() -> cache1.lookup(n)); + System.out.println(String.format("cacheFib(%d) = %d [%g s]", n, r.first, ((double) r.second / 1000000000.))); + } + } + + + // versione parametrica + + public static long fastFibRecur(long n, Map cache) { + return n < 2 ? 1L : fastFib(n - 1, cache) + fastFib(n - 2, cache); + } + + public static long fastFib(long n, Map cache) { + if (cache.containsKey(n)) return cache.get(n); + else { + long r = fastFibRecur(n, cache); + cache.put(n, r); + return r; + } + } + + public static class CachedFib { + private final Map cache = new HashMap<>(); + + private long fibRecur(long n) { + return n < 2 ? 1L : fib(n - 1) + fib(n - 2); + } + + public long fib(long n) { + if (cache.containsKey(n)) return cache.get(n); + else { + long r = fibRecur(n); + cache.put(n, r); + return r; + } + } + } + + public static void main2(String[] args) { + + // versione senza oggetto + Map m = new HashMap<>(); + for (int i = 0; i < 100; ++i) { + long n = i; + Pair r = cputime(() -> fastFib(n, m)); + System.out.println(String.format("fib(%d) = %d [%g s]", n, r.first, ((double) r.second / 1000000000.))); + } + + // versione con oggetto + CachedFib cache = new CachedFib(); + for (int i = 0; i < 100; ++i) { + long n = i; + Pair r = cputime(() -> cache.fib(n)); + System.out.println(String.format("fib(%d) = %d [%g s]", n, r.first, ((double) r.second / 1000000000.))); + } + + } + + + +} \ No newline at end of file diff --git a/2019-20/Lezioni/src/esercizi/MapIterator.java b/2019-20/Lezioni/src/esercizi/MapIterator.java new file mode 100644 index 0000000..d6116f2 --- /dev/null +++ b/2019-20/Lezioni/src/esercizi/MapIterator.java @@ -0,0 +1,62 @@ +package esercizi; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.function.Function; + +public class MapIterator { + + + + public static Iterator mapIterator(Iterator it, Function f) { + return new Iterator() { + @Override + public boolean hasNext() { + return it.hasNext(); + } + + @Override + public B next() { + try { + A a = it.next(); + return f.apply(a); + } + catch (RuntimeException e) { + System.err.println(String.format("exception caught: %s", e.getMessage())); + if (hasNext()) return next(); + else throw e; + } + } + }; + } + + + public static void main(String[] args) { + List l = new ArrayList<>(); + for (int i = -10; i < 20; ++i) { + l.add(i); + } + Iterator it = mapIterator(l.iterator(), (n) -> (double) n); + while (it.hasNext()) { + double x = it.next(); + System.out.println(x); + } + + Iterator it2 = mapIterator(l.iterator(), + new Function<>() { + @Override + public Double apply(Integer n) { + if (n > 0) return (double) n; + else throw new RuntimeException(); + } + }); + while (it2.hasNext()) { + double x = it2.next(); + System.out.println(x); + } + + + } + +} diff --git a/2019-20/Lezioni/src/esercizi/PO1.java b/2019-20/Lezioni/src/esercizi/PO1.java new file mode 100644 index 0000000..d7ececb --- /dev/null +++ b/2019-20/Lezioni/src/esercizi/PO1.java @@ -0,0 +1,127 @@ +package esercizi; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Random; + +public class PO1 { + + private static final Random rnd = new Random(); + + public static class Dungeon { + private final Room[][] rooms; + private final int w, h; + + public Dungeon(int w, int h) { + rooms = new Room[w][h]; + this.w = w; + this.h = h; + for (int y = 0; y < h; ++y) { + for (int x = 0; x < w; ++x) { + rooms[x][y] = new Room(); + } + } + for (int y = 0; y < h; ++y) { + for (int x = 0; x < w; ++x) { + Room r = rooms[x][y]; + r.n = getRoom(x, y - 1); + r.s = getRoom(x, y + 1); + r.o = getRoom(x - 1, y); + r.e = getRoom(x + 1, y); + } + } + } + + public Room getRoom(int x, int y) { + if (x < 0 || y < 0 || x >= w || y >= h) return null; + return rooms[x][y]; + } + + private void reset() { + for (int y = 0; y < h; ++y) { + for (int x = 0; x < w; ++x) { + rooms[x][y].visited = false; + } + } + } + + public double maxScore(int x, int y) { + reset(); + return visit(getRoom(x, y)); + } + + private static double visit(@Nullable Room start) { + if (start == null || start.visited) return 0.; + return start.getScore() + visit(start.n) + visit(start.s) + visit(start.e) + visit(start.o); + } + + } + + public static void main(String[] args) { + Dungeon dung1 = new Dungeon(3, 3); + double score = dung1.maxScore(0, 0); + } + + + public static class Room { + @NotNull + private final Collection treasures; + @Nullable + Room n, o, s, e; + boolean visited = false; + + public Room(@NotNull Collection treasures) { + this(treasures, null, null, null, null); + } + + public Room() { + this(null, null, null, null); + } + + public Room(@NotNull Collection treasures, @Nullable Room n, @Nullable Room o, @Nullable Room s, @Nullable Room e) { + this.treasures = treasures; + this.n = n; + this.o = o; + this.s = s; + this.e = e; + } + + public Room(@Nullable Room n, @Nullable Room o, @Nullable Room s, @Nullable Room e) { + Collection ts = new ArrayList<>(); + for (int i = 0; i < rnd.nextInt(10); ++i) + ts.add(new Treasure(rnd.nextInt(10), rnd.nextInt(50), rnd.nextInt(100))); + this.treasures = ts; + this.n = n; + this.o = o; + this.s = s; + this.e = e; + } + + public double getScore() { + double r = 0.; + for (Treasure t : treasures) { + r += t.getValue(); + } + return r; + } + + } + + public static class Treasure { + private final int gold, silver, bronze; + + public Treasure(int g, int s, int b) { + this.gold = g; + this.silver = s; + this.bronze = b; + } + + public double getValue() { + return gold * 5. + silver * 2. + bronze; + } + } + +} diff --git a/2019-20/Lezioni/src/esercizi/ScittoGennaio2019__Pool.java b/2019-20/Lezioni/src/esercizi/ScittoGennaio2019__Pool.java new file mode 100644 index 0000000..7ec745b --- /dev/null +++ b/2019-20/Lezioni/src/esercizi/ScittoGennaio2019__Pool.java @@ -0,0 +1,99 @@ +package esercizi; + +import java.util.concurrent.LinkedBlockingQueue; + +public class ScittoGennaio2019__Pool { + + public interface Pool { + void add(T x); // popola la pool con un nuovo elemento + R acquire() throws InterruptedException; // acquisisce una risorsa + void release(R x); // rilascia una risorsa e la rimette nella pool + } + + // a + public interface BasicPool extends Pool {} + + // b + public static class SimplePool implements BasicPool { + private LinkedBlockingQueue q = new LinkedBlockingQueue<>(); + + @Override + public void add(T x) { + q.add(x); + } + + @Override + public T acquire() throws InterruptedException { + return q.take(); + } + + @Override + public void release(T x) { + add(x); + } + } + + // c + + public static class Resource { + private final T elem; + private final AutoPool pool; + public Resource(T x, AutoPool p) { + this.elem = x; + this.pool = p; + } + + public T get() { return elem; } + + @Override + @SuppressWarnings("deprecation") + public void finalize() { + release(); + } + + public void release() { + pool.release(this); + } + } + + public static class AutoPool implements Pool> { + + + private LinkedBlockingQueue q = new LinkedBlockingQueue<>(); + + @Override + public void add(T x) { + q.add(x); + } + + @Override + public Resource acquire() throws InterruptedException { + return new Resource<>(q.take(), this); + } + + @Override + public void release(Resource x) { + q.add(x.elem); + } + + } + + public static void main(String[] args) { + AutoPool p = new AutoPool<>(); + try { + Resource x = p.acquire(); + + String s = x.get().toLowerCase(); + +// x.release(); + + + } catch (InterruptedException e) { + e.printStackTrace(); + } + + // .. + + } + +} diff --git a/2019-20/Lezioni/src/esercizi/ScrittoGennaio2019.java b/2019-20/Lezioni/src/esercizi/ScrittoGennaio2019.java new file mode 100644 index 0000000..2a1bccd --- /dev/null +++ b/2019-20/Lezioni/src/esercizi/ScrittoGennaio2019.java @@ -0,0 +1,75 @@ +package esercizi; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.Random; + +public class ScrittoGennaio2019 { + + /*1a1*/ + @FunctionalInterface + public interface Function { + B apply(A x); + } + + /*1a2*/ + public static Iterator mapIterator(Iterator it, Function f) { + return new Iterator<>() { + @Override + public boolean hasNext() { + return it.hasNext(); + } + + @Override + public B next() { + return f.apply(it.next()); + } + }; + } + + /*1b1*/ + public static class Pair { + public final A a; + public final B b; + + public Pair(A a, B b) { + this.a = a; + this.b = b; + } + } + + /*1b2*/ + public static Iterator> pairIterator(Iterator it) { + return new Iterator<>()/*se non specifico non riesce ad inferire*/ { + A last; + + @Override + public boolean hasNext() { + if (it.hasNext()) + last = it.next(); + return it.hasNext(); + } + + @Override + public Pair next() { + return new Pair<>(last, it.next()); + } + }; + } + + /*1c*/ + public static void main(String[] args) { + ArrayList al = new ArrayList<>(); + Random rnd = new Random(); + for (int i = 0; i < 10; ++i) + al.add(rnd.nextInt(10)); + + Iterator> cateti = pairIterator(al.iterator()); + + Iterator ipotenuse = mapIterator(cateti, p -> Math.sqrt(p.a * p.a + p.b * p.b)); + + while (ipotenuse.hasNext()) + System.out.println("Ipotenusa " + ipotenuse.next()); + } +} + diff --git a/2019-20/Lezioni/src/esercizi/ScrittoGennaio2020.java b/2019-20/Lezioni/src/esercizi/ScrittoGennaio2020.java new file mode 100644 index 0000000..899ac8d --- /dev/null +++ b/2019-20/Lezioni/src/esercizi/ScrittoGennaio2020.java @@ -0,0 +1,47 @@ +package esercizi; + +import org.jetbrains.annotations.NotNull; + +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; +import java.util.function.Function; +import java.util.function.Supplier; + +public class ScrittoGennaio2020 { + + public static class Point { + + } + + public interface Solid extends Comparable { + double area(); + double volume(); + PositionedSolid at(Point origin); + + static int compareBy(Function f, S s1, S s2) { + return Double.compare(f.apply(s1), f.apply(s2)); + } + static Comparator comparatorBy(Function f) { + return (s1, s2) -> compareBy(f, s1, s2); + } + default int compareTo(Solid s) { + Function f = Solid::volume; // (Solid x) -> x.volume() + Supplier g = this::volume; // () -> this.volume() + return compareBy(Solid::volume, this, s); + } + } + + public interface Polyhedron extends Solid { + double perimeter(); + @Override + PositionedPolyhedron at(Point origin); + } + + public interface PositionedSolid { + Point origin(); + } + + public interface PositionedPolyhedron extends PositionedSolid, Iterable {} + +} diff --git a/2019-20/Lezioni/src/esercizi/ScrittoGiugno2019.java b/2019-20/Lezioni/src/esercizi/ScrittoGiugno2019.java new file mode 100644 index 0000000..d007bf5 --- /dev/null +++ b/2019-20/Lezioni/src/esercizi/ScrittoGiugno2019.java @@ -0,0 +1,73 @@ +package esercizi; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.*; + +public class ScrittoGiugno2019 { + + public static class Node implements Iterable { + @NotNull + private final T data; + @Nullable + private final Node left, right; + + public Node(@NotNull T data, @Nullable Node l, @Nullable Node r) { + this.data = data; + left = l; + right = r; + } + + public Node(@NotNull T data) { + this(data, null, null); + } + + public Node(@NotNull T data, @NotNull Node l) { + this(data, l, null); + } + + private void visit(@NotNull Collection c) { + c.add(data); + if (left != null) left.visit(c); + if (right != null) right.visit(c); + } + + @NotNull + @Override + public Iterator iterator() { + Collection r = new ArrayList<>(); + visit(r); + return r.iterator(); + } + + @Override + public String toString() { + return String.format("%s(%s %s)", + data, + left == null ? "_" : left, + right == null ? "_" : right); + } + } + + + public static void main(String[] args) { + + Node l1 = new Node<>(2, new Node<>(4), new Node<>(5)), + r1 = new Node<>(3, + new Node<>(6, + null, + new Node<>(7))), + root = new Node<>(1, l1, r1); + + + for (int i : root) { + System.out.println(i); + } + + System.out.println(root); + + } + + +} diff --git a/2019-20/Lezioni/src/esercizi/camporese/Laureando.java b/2019-20/Lezioni/src/esercizi/camporese/Laureando.java new file mode 100644 index 0000000..c548fcd --- /dev/null +++ b/2019-20/Lezioni/src/esercizi/camporese/Laureando.java @@ -0,0 +1,32 @@ +package esercizi.camporese; + +public class Laureando extends Studente { + private int votoDiLaurea; + + public Laureando(String nome, int eta, int classe, int mediaVoti, int votoDiLaurea) { + super(nome, eta, classe, mediaVoti); + this.votoDiLaurea = votoDiLaurea; + } + + public int compareTo(Laureando o) { + int diff = votoDiLaurea - o.votoDiLaurea; + return diff == 0 ? eta - o.eta : diff; + } + + @Override + public int compareTo(Persona o) { + if (o instanceof Laureando) { + return compareTo((Laureando) o); + } + else return super.compareTo(o); + } + + /* + if (o instanceof Studente) { + Studente other = (Studente) o; + int diffClasse = classe - other.classe; + return diffClasse == 0 ? eta - other.eta : diffClasse; + } + else return super.compareTo(o); + */ +} diff --git a/2019-20/Lezioni/src/esercizi/camporese/Persona.java b/2019-20/Lezioni/src/esercizi/camporese/Persona.java new file mode 100644 index 0000000..7f709ed --- /dev/null +++ b/2019-20/Lezioni/src/esercizi/camporese/Persona.java @@ -0,0 +1,32 @@ +package esercizi.camporese; + +public class Persona implements Comparable, Cloneable { + protected final String nome; + public final int eta; + + public Persona(Persona p) { + this.nome = p.nome; + this.eta = p.eta; + } + + public Persona(String nome, int eta) { + this.nome = nome; + this.eta = eta; + } + + @Override + public int compareTo(Persona other) { + return eta - other.eta; + } + + @Override + public String toString() { + return nome + ", " + eta; + } + + @Override + public Persona clone() { + return new Persona(this); + } + +} diff --git a/2019-20/Lezioni/src/esercizi/camporese/Studente.java b/2019-20/Lezioni/src/esercizi/camporese/Studente.java new file mode 100644 index 0000000..aeb88f0 --- /dev/null +++ b/2019-20/Lezioni/src/esercizi/camporese/Studente.java @@ -0,0 +1,50 @@ +package esercizi.camporese; + +public class Studente extends Persona { + + private int classe; + private final int mediaVoti; + + public Studente(String nome, int eta, int classe, int mediaVoti) { + super(nome, eta); + this.classe = classe; + this.mediaVoti = mediaVoti; + } + + public Studente(Studente s) { + super(s); + this.classe = s.classe; + this.mediaVoti = s.mediaVoti; + } + + public int getClasse() { return classe; } + + public int getMediaVoti() { + return this.mediaVoti; + } + + public void prossimoAnno() { + ++classe; + } + + @Override + public int compareTo(Persona o) { + if (o instanceof Studente) { + Studente other = (Studente) o; + int diffClasse = classe - other.classe; + return diffClasse == 0 ? eta - other.eta : diffClasse; + } + else return super.compareTo(o); + } + + @Override + public String toString() { + return super.toString() + ", " + classe + ", " + mediaVoti; + } + + @Override + public Studente clone() { + return new Studente(this); + } + +} diff --git a/2019-20/Lezioni/src/esercizi/camporese/main/Es_Camporese.java b/2019-20/Lezioni/src/esercizi/camporese/main/Es_Camporese.java new file mode 100644 index 0000000..900006b --- /dev/null +++ b/2019-20/Lezioni/src/esercizi/camporese/main/Es_Camporese.java @@ -0,0 +1,93 @@ +package esercizi.camporese.main; + +import esercizi.camporese.Persona; +import esercizi.camporese.Studente; +import org.jetbrains.annotations.NotNull; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.function.BiFunction; +import java.util.function.Function; + +public class Es_Camporese { + + @NotNull + public static ArrayList mapFilter(Iterable l, boolean ancheBocciati, Function f) { + ArrayList c = new ArrayList<>(); + for (A a : l) + if (ancheBocciati || (((Studente) a).getMediaVoti()) >= 6) + c.add(f.apply(a)); + return c; + } + + public static B fold(Iterable l, B zero, BiFunction f) { + B acc = zero; + for (A a : l) + acc = f.apply(a, acc); + return acc; + } + + public static void printIterable(Iterable l, String str) { + System.out.println(str); + for (A a : l) + System.out.println(a); + } + + + public static void main(String[] args) { + ArrayList persone = new ArrayList<>(); + persone.add(new Persona("Alvise", 43)); + persone.add(new Persona("Federico", 26)); + persone.add(new Persona("Stefano", 35)); + persone.add(new Persona("Matteo", 29)); + persone.add(new Studente("Francesco", 20, 2, 3)); + + /*USA PERSONA::COMPARETO*/ + Collections.sort(persone); + /*USA COMPARE*/ + /* + Collections.sort(persone, (o1, o2) -> o1.età - o2.età); + */ + printIterable(persone, "\nPERSONE ORDINATE PER ETA':\n"); + + ArrayList studenti = new ArrayList<>(); + studenti.add(new Studente("Francesco", 20, 2, 3)); + studenti.add(new Studente("Andrea", 23, 2, 6)); + studenti.add(new Studente("Daniele", 22, 3, 5)); + studenti.add(new Studente("Michele", 21, 2, 7)); + studenti.add(new Studente("Nicola", 20, 1, 10)); + + /* + NON PUOI USARE Collections.sort(studenti); SE NON USI I GENERICS SU PERSONA + perchè useresti il compareTo di Persona e non quello di Studente + siccome Studente estende Persona che implementa Comparable + */ + /*USA STUDENTE::COMPARETO*/ + //Collections.sort(studenti); + /*USA COMPARE*/ + studenti.sort((o1, o2) -> { + int diffAnnoCorso = o1.getClasse() - o2.getClasse(); + return diffAnnoCorso == 0 ? o1.eta - o2.eta : diffAnnoCorso; + }); + printIterable(studenti, "\nSTUDENTI ORDINATI PER (ANNOCORSO, ETA'):\n"); + + ArrayList tuttiVengonoPromossi = mapFilter(studenti, true, (x) -> + { + Studente daRestituire = x.clone(); + daRestituire.prossimoAnno(); + return daRestituire; + }); + printIterable(tuttiVengonoPromossi, "\nSTUDENTI CHE SI SPERA ARRIVINO NELLA NUOVA CLASSE:\n"); + + ArrayList studentiPromossi = mapFilter(studenti, false, (x) -> + { + Studente daRestituire = x.clone(); + daRestituire.prossimoAnno(); + return daRestituire; + }); + printIterable(studentiPromossi, "\nSTUDENTI PROMOSSI VERAMENTE:\n"); + + System.out.println("\nMEDIA VOTI DELLE PERSONE PROMOSSE: " + fold(tuttiVengonoPromossi, 0, (Studente x, Integer acc) -> acc + x.getMediaVoti()) / tuttiVengonoPromossi.size() + "\n"); + } +} + diff --git a/2020/Lezioni/src/it/unive/dais/po2/myjdk/MyArrayList.java b/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MyArrayList.java similarity index 79% rename from 2020/Lezioni/src/it/unive/dais/po2/myjdk/MyArrayList.java rename to 2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MyArrayList.java index d99f9e8..be37c1f 100644 --- a/2020/Lezioni/src/it/unive/dais/po2/myjdk/MyArrayList.java +++ b/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MyArrayList.java @@ -1,5 +1,8 @@ package it.unive.dais.po2.myjdk; +import java.util.Collection; + +// TODO: togliere il prefisso My da tutti i nomi dei tipi e mostrare la differenza tra tipi omonimi in package diversi public class MyArrayList implements MyList { private Object[] a; @@ -10,9 +13,19 @@ public MyArrayList() { this.actualSize = 0; } + public MyArrayList(MyCollection c) { + this(); + MyIterator it = c.iterator(); + while (it.hasNext()) { + add(it.next()); + } + + } + @Override public T get(int i) throws OutOfBoundsException { - if (i >= actualSize) throw new OutOfBoundsException(); + if (i >= actualSize) + throw new OutOfBoundsException("get: invalid position " + i); //noinspection unchecked return (T) a[i]; } @@ -64,6 +77,8 @@ public void clear() { this.actualSize = 0; } + + @Override public MyIterator iterator() { return new MyIterator<>() { diff --git a/2020/Lezioni/src/it/unive/dais/po2/myjdk/MyCollection.java b/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MyCollection.java similarity index 99% rename from 2020/Lezioni/src/it/unive/dais/po2/myjdk/MyCollection.java rename to 2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MyCollection.java index 069871e..5f5936d 100644 --- a/2020/Lezioni/src/it/unive/dais/po2/myjdk/MyCollection.java +++ b/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MyCollection.java @@ -11,4 +11,5 @@ public interface MyCollection extends MyIterable { default boolean isEmpty() { return size() == 0; } + } diff --git a/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MyHashMap.java b/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MyHashMap.java new file mode 100644 index 0000000..b594fea --- /dev/null +++ b/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MyHashMap.java @@ -0,0 +1,18 @@ +package it.unive.dais.po2.myjdk; + +public class MyHashMap implements MyMap { + @Override + public V get(K k) throws NotFoundException { + return null; + } + + @Override + public void put(K k, V v) { + + } + + @Override + public void clear() { + + } +} diff --git a/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MyHashSet.java b/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MyHashSet.java new file mode 100644 index 0000000..4a19860 --- /dev/null +++ b/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MyHashSet.java @@ -0,0 +1,62 @@ +package it.unive.dais.po2.myjdk; + +public class MyHashSet extends MyLinkedSet { + private HashFun h; + + public interface HashFun { + long hash(E e); + } + + private static class DefaultHashFun implements HashFun { + @Override + public long hash(E e) { + return e.hashCode(); + } + } + + private class DefaultHashFun__nonstatic implements HashFun { + @Override + public long hash(T e) { + return e.hashCode(); + } + } + + public MyHashSet(HashFun h) { + super(); + this.h = h; + } + + + public MyHashSet() { + super(); + // lambda syntax + this.h = (T x) -> x.hashCode(); + // method reference syntax + this.h = T::hashCode; + // anonymous class syntax + this.h = new HashFun() { + @Override + public long hash(T e) { + return e.hashCode(); + } + }; + // non-anonymous instance + this.h = new DefaultHashFun(); + // non-anonymous non-static instance + this.h = new DefaultHashFun__nonstatic(); + } + + @Override + public void add(T x) { + MyIterator it = iterator(); + boolean found = false; + while (it.hasNext()) { + T e = it.next(); + //if (x.hashCode() == e.hashCode()) + if (h.hash(x) == h.hash(e)) + found = true; + } + if (!found) + l.add(x); + } +} diff --git a/2020/Lezioni/src/it/unive/dais/po2/myjdk/MyHashMap.java b/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MyIdentityMap.java similarity index 57% rename from 2020/Lezioni/src/it/unive/dais/po2/myjdk/MyHashMap.java rename to 2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MyIdentityMap.java index 1364d87..3bf2765 100644 --- a/2020/Lezioni/src/it/unive/dais/po2/myjdk/MyHashMap.java +++ b/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MyIdentityMap.java @@ -1,11 +1,14 @@ package it.unive.dais.po2.myjdk; -public class MyHashMap implements MyMap { - private MyArrayList> m; +import java.util.ArrayList; +import java.util.Iterator; + +public class MyIdentityMap implements MyMap { + private ArrayList> m; @Override public V get(K k) throws NotFoundException { - MyIterator> it = m.iterator(); + Iterator> it = m.iterator(); while (it.hasNext()) { Pair p = it.next(); if (p.first.equals(k)) return p.second; @@ -15,15 +18,20 @@ public V get(K k) throws NotFoundException { @Override public void put(K k, V v) { - MyIterator> it = m.iterator(); + Iterator> it = m.iterator(); while (it.hasNext()) { Pair p = it.next(); if (p.first.equals(k)) { + // TODO: fare la stessa cosa ma con le coppie immutabili p.second = v; return; } - // TODO: fare la stessa cosa con le coppie immutabili } m.add(new Pair<>(k, v)); } + + @Override + public void clear() { + m = new ArrayList<>(); + } } diff --git a/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MyIterable.java b/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MyIterable.java new file mode 100644 index 0000000..1f40cd6 --- /dev/null +++ b/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MyIterable.java @@ -0,0 +1,17 @@ +package it.unive.dais.po2.myjdk; + +import java.util.function.Consumer; + +public interface MyIterable { + + MyIterator iterator(); + + default void forEach(Consumer c) { + MyIterator it = this.iterator(); + while (it.hasNext()) { + T x = it.next(); + c.accept(x); + } + } + +} diff --git a/2020/Lezioni/src/it/unive/dais/po2/myjdk/MyIterator.java b/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MyIterator.java similarity index 100% rename from 2020/Lezioni/src/it/unive/dais/po2/myjdk/MyIterator.java rename to 2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MyIterator.java diff --git a/2020/Lezioni/src/it/unive/dais/po2/myjdk/MyLinkedList.java b/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MyLinkedList.java similarity index 65% rename from 2020/Lezioni/src/it/unive/dais/po2/myjdk/MyLinkedList.java rename to 2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MyLinkedList.java index 67db350..f26d6c9 100644 --- a/2020/Lezioni/src/it/unive/dais/po2/myjdk/MyLinkedList.java +++ b/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MyLinkedList.java @@ -1,8 +1,10 @@ package it.unive.dais.po2.myjdk; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +// TODO: sistemare le possibili eccezioni NullPointerException public class MyLinkedList implements MyList { @Override @@ -10,13 +12,22 @@ public MyIterator iterator() { return null; } + // TODO: come esercizio provare a rendere questa classe statica in modo che abbia il suo generic; e poi modificare MyLinkedList opportunamente protected class Node { + @Nullable public T data; + @Nullable public Node next; - public Node(T data, Node next) { + + public Node(@Nullable T data, @NotNull Node next) { this.data = data; this.next = next; } + + public Node(@Nullable T data) { + this.data = data; + this.next = null; + } } @Nullable @@ -27,18 +38,18 @@ public MyLinkedList() { } public void add(T e) { - head = new Node(e, head); + head = head == null ? new Node(e) : new Node(e, head); } @Override public int size() { int r = 0; - for (Node n = head; n.next != null; ++r); + for (@Nullable Node n = head; n.next != null; ++r); return r; } @Override - public boolean contains(T x) { + public boolean contains(@NotNull T x) { MyIterator it = iterator(); while (it.hasNext()) { T e = it.next(); @@ -52,10 +63,11 @@ public void clear() { head = null; } + @Nullable public T get(int pos) throws OutOfBoundsException { Node n = head; for (; pos > 0; --pos) - if ((n = head.next) == null) throw new OutOfBoundsException(); + if ((n = head.next) == null) throw new OutOfBoundsException("get: invalid position " + pos); return n.data; } @@ -64,7 +76,7 @@ public void add(int i, T x) { int r = 0; Node n = head; for (; n.next != null && r < i; ++r); - n.next = new Node(x, n.next); // TODO: da testare + n.next = new Node(x, n.next); } @@ -74,16 +86,16 @@ public boolean remove(int i) { Node n = head; for (; n.next != null && r < i - 1; ++r); if (n.next != null) { - n.next = n.next.next; // TODO: da testare + n.next = n.next.next; } return true; } @Override public boolean remove(T x) { - // TODO: da implementare + // TODO: da fare per casa throw new RuntimeException("not implemented"); } +} -} \ No newline at end of file diff --git a/2020/Lezioni/src/it/unive/dais/po2/myjdk/MyLinkedSet.java b/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MyLinkedSet.java similarity index 89% rename from 2020/Lezioni/src/it/unive/dais/po2/myjdk/MyLinkedSet.java rename to 2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MyLinkedSet.java index 61bf8c8..daa6da0 100644 --- a/2020/Lezioni/src/it/unive/dais/po2/myjdk/MyLinkedSet.java +++ b/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MyLinkedSet.java @@ -1,5 +1,6 @@ package it.unive.dais.po2.myjdk; +// TODO: LinkedSet non è un bel nome, non si capisce: meglio trovarne un'altro public class MyLinkedSet implements MySet { protected MyLinkedList l; diff --git a/2020/Lezioni/src/it/unive/dais/po2/myjdk/MyList.java b/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MyList.java similarity index 100% rename from 2020/Lezioni/src/it/unive/dais/po2/myjdk/MyList.java rename to 2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MyList.java diff --git a/2020/Lezioni/src/it/unive/dais/po2/myjdk/MyMap.java b/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MyMap.java similarity index 88% rename from 2020/Lezioni/src/it/unive/dais/po2/myjdk/MyMap.java rename to 2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MyMap.java index 52abf48..5dd0d4d 100644 --- a/2020/Lezioni/src/it/unive/dais/po2/myjdk/MyMap.java +++ b/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MyMap.java @@ -3,4 +3,5 @@ public interface MyMap { V get(K k) throws NotFoundException; void put(K k, V v); + void clear(); } diff --git a/2020/Lezioni/src/it/unive/dais/po2/myjdk/MySet.java b/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MySet.java similarity index 100% rename from 2020/Lezioni/src/it/unive/dais/po2/myjdk/MySet.java rename to 2019-20/Lezioni/src/it/unive/dais/po2/myjdk/MySet.java diff --git a/2020/Lezioni/src/it/unive/dais/po2/myjdk/NotFoundException.java b/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/NotFoundException.java similarity index 100% rename from 2020/Lezioni/src/it/unive/dais/po2/myjdk/NotFoundException.java rename to 2019-20/Lezioni/src/it/unive/dais/po2/myjdk/NotFoundException.java diff --git a/2020/Lezioni/src/it/unive/dais/po2/myjdk/OutOfBoundsException.java b/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/OutOfBoundsException.java similarity index 52% rename from 2020/Lezioni/src/it/unive/dais/po2/myjdk/OutOfBoundsException.java rename to 2019-20/Lezioni/src/it/unive/dais/po2/myjdk/OutOfBoundsException.java index 00c0b9d..46968d8 100644 --- a/2020/Lezioni/src/it/unive/dais/po2/myjdk/OutOfBoundsException.java +++ b/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/OutOfBoundsException.java @@ -1,5 +1,7 @@ package it.unive.dais.po2.myjdk; public class OutOfBoundsException extends Exception { - + public OutOfBoundsException(String message) { + super(message); + } } diff --git a/2020/Lezioni/src/it/unive/dais/po2/myjdk/Pair.java b/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/Pair.java similarity index 99% rename from 2020/Lezioni/src/it/unive/dais/po2/myjdk/Pair.java rename to 2019-20/Lezioni/src/it/unive/dais/po2/myjdk/Pair.java index 2ffe513..fa7ce6b 100644 --- a/2020/Lezioni/src/it/unive/dais/po2/myjdk/Pair.java +++ b/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/Pair.java @@ -9,4 +9,5 @@ public Pair(A a, B b) { this.first = a; this.second = b; } + } diff --git a/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/TestList.java b/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/TestList.java new file mode 100644 index 0000000..cc58492 --- /dev/null +++ b/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/TestList.java @@ -0,0 +1,18 @@ +package it.unive.dais.po2.myjdk; + +public class TestList { + public static void main(String[] args) { + try { + MyList a = new MyArrayList<>(); + a.add(23); + a.add(11); + + int n = a.get(1); + System.out.println("elemento in posizione 1: " + n); + + } catch (OutOfBoundsException e) { + System.out.println("eccezione: " + e.getMessage()); + } + + } +} diff --git a/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/TestMap.java b/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/TestMap.java new file mode 100644 index 0000000..02a93d4 --- /dev/null +++ b/2019-20/Lezioni/src/it/unive/dais/po2/myjdk/TestMap.java @@ -0,0 +1,23 @@ +package it.unive.dais.po2.myjdk; + +public class TestMap { + + public static void main(String[] args) { + try { + + MyMap m = new MyIdentityMap<>(); + m.put("alvise", 42); + m.put("francesco", 12); + m.put("gianni", 56); + m.put("pippo", 78); + + int eta_di_gianni = m.get("gianni"); + System.out.println("risultato: " + eta_di_gianni); + + m.clear(); + + } catch (NotFoundException e) { + e.printStackTrace(); + } + } +} diff --git a/2019-20/Lezioni/src/it/unive/dais/po2/other/FilosofiACena__Francesco.java b/2019-20/Lezioni/src/it/unive/dais/po2/other/FilosofiACena__Francesco.java new file mode 100644 index 0000000..da97db5 --- /dev/null +++ b/2019-20/Lezioni/src/it/unive/dais/po2/other/FilosofiACena__Francesco.java @@ -0,0 +1,107 @@ +package it.unive.dais.po2.other; + +import org.jetbrains.annotations.Nullable; +import java.util.ArrayList; +import java.util.Collection; + +public class FilosofiACena__Francesco { + + public static class Monitor { + @Nullable + private static Monitor instance = null; + + private int postiTot; + private boolean[] bacchetta; + + private Monitor(int postiTot) { + this.postiTot = postiTot; + this.bacchetta = new boolean[postiTot]; + for (int i = 0; i < postiTot; ++i) + bacchetta[i] = true; + } + + public synchronized void raccogli_sx(int posto) throws InterruptedException { + while (!bacchetta[posto]) + this.wait(); + bacchetta[posto] = false; + } + + public synchronized void raccogli_dx(int posto) throws InterruptedException { + raccogli_sx((posto + 1) % postiTot); + } + + public synchronized void deposita_sx(int posto) { + + bacchetta[posto] = true; + } + + public synchronized void deposita_dx(int posto) { + deposita_sx((posto + 1) % postiTot); + this.notifyAll(); + } + + public static synchronized Monitor getInstance(int postiTot) { + if (instance == null) + instance = new Monitor(postiTot); + return instance; + } + } + + public static void codiceFilosofo(int posto, Monitor tavola) throws InterruptedException { + while (true) { + /*PENSA*/ + System.out.println("Filosofo " + posto + " pensa"); + Thread.sleep(1000); + tavola.raccogli_sx(posto);/*raccoglie la bacchetta sinistra*/ + tavola.raccogli_dx(posto);/*raccoglie la bacchetta destra*/ + /*MANGIA*/ + System.out.println("Filosofo " + posto + " mangia"); + Thread.sleep(1000); + tavola.deposita_sx(posto);/*deposita la bacchetta sinistra*/ + tavola.deposita_dx(posto);/*deposita la bacchetta destra*/ + } + } + + public static class Filosofo extends Thread implements Runnable { + private int posto; + private Monitor tavola; + + public Filosofo(int posto, Monitor tavola) { + this.posto = posto; + this.tavola = tavola; + } + + @Override + public void run() { + try { + codiceFilosofo(posto, tavola); + } catch (InterruptedException ex) { + ex.printStackTrace(); + } + } + } + + public static void main(String[] args) { + int nFilosofi = 5; + final Monitor tavola = Monitor.getInstance(5); + Collection filosofi = new ArrayList<>(); + for (int i = 0; i < nFilosofi; ++i) { +// Filosofo filosofo = new Filosofo(i, tavola); + final int[] posto = new int[] { i }; // trucco dell'array final con 1 solo elemento + + Thread filosofo = new Thread(() -> { + try { + codiceFilosofo(posto[0], tavola); + } + catch (InterruptedException e) { + e.printStackTrace(); + } + }); + + filosofo.start(); + filosofi.add(filosofo); + } + } +} + + diff --git a/2019-20/Lezioni/src/it/unive/dais/po2/other/ForEachTest.java b/2019-20/Lezioni/src/it/unive/dais/po2/other/ForEachTest.java new file mode 100644 index 0000000..edd96ab --- /dev/null +++ b/2019-20/Lezioni/src/it/unive/dais/po2/other/ForEachTest.java @@ -0,0 +1,38 @@ +package it.unive.dais.po2.other; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.function.Consumer; + +public class ForEachTest { + + public static class StrangeArrayList extends ArrayList { + @Override + public void forEach(Consumer c) { + System.out.println("ciao"); + Iterator it = iterator(); + int cnt = 0; + while(it.hasNext() && cnt < 5) { + T x = it.next(); + c.accept(x); + ++cnt; + } + } + } + + + public static void main(String[] args) { + List l1 = new StrangeArrayList<>(); + for (int i = 0; i < 10; ++i) { + l1.add(i); + } + + for (Integer n : l1) { + System.out.println(n); + } + l1.forEach(n -> System.out.println(n)); + + + } +} diff --git a/2019-20/Lezioni/src/it/unive/dais/po2/other/FunctionalPrimitives.java b/2019-20/Lezioni/src/it/unive/dais/po2/other/FunctionalPrimitives.java new file mode 100644 index 0000000..8b300db --- /dev/null +++ b/2019-20/Lezioni/src/it/unive/dais/po2/other/FunctionalPrimitives.java @@ -0,0 +1,161 @@ +package it.unive.dais.po2.other; + +import it.unive.dais.po2.zoo.Animal; +import it.unive.dais.po2.zoo.ColoredAnimal; +import it.unive.dais.po2.zoo.Dog; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Predicate; + +public class FunctionalPrimitives { + + public static List map(Iterable l, Function f) { + List c = new ArrayList<>(); + for (A a : l) { + B b = f.apply(a); + c.add(b); + } + return c; + } + + public static List map2(Iterable l, Function f) { + return fold(l, new ArrayList<>(), (x, acc) -> { + acc.add(f.apply(x)); + return acc; + }); + } + + public static void filter__imperative(Iterable l, Function p) { + Iterator it = l.iterator(); + while (it.hasNext()) { + A a = it.next(); + if (!p.apply(a)) it.remove(); + } + } + + public static List filter__pure(Iterable l, Function p) { + List r = new ArrayList<>(); + for (A a : l) { + if (p.apply(a)) r.add(a); + } + return r; + } + + public static void iter(Iterable l, Consumer f) { + for (A a : l) { + f.accept(a); + } + } + + public static B fold(Iterable l, B zero, BiFunction f) { + B acc = zero; + for (A a : l) { + acc = f.apply(a, acc); + } + return acc; + } + + public static B fold_recur(Iterable l, B zero, BiFunction f) { + return fold_recur(l.iterator(), zero, f); + } + + // fold : list A -> B -> (A * B -> B) -> B + public static B fold_recur(Iterator it, B zero, BiFunction f) { + // caso ricorsivo + if (it.hasNext()) { + return fold_recur(it, f.apply(it.next(), zero), f); + } + // caso base + else { + return zero; + } + // equivalente ma in una solo espressione + //return it.hasNext() ? fold_recur(it, f.apply(it.next(), zero), f) : zero; + } + + public static void f() { // function_f: + int i = 0; // li r0, #0 + while (i < 10) { // loop: + // cmp r0, #10 + // jeq exit + System.out.println("ciao " + i); // call ... + i = i + 1; // add r0, #1, r0 + } // jmp loop + // exit: + // balbalbla + } + + public static void g(int i) { // function_g: + if (i > 0) { // ld sp, r0 + // cmp r0, #0 + // jeq exit + System.out.println("ciao " + i); // call ... + g(i - 1); // sub r0, #1 + // st r0, sp + } // jmp function_g + // exit: + // blablabla + } + + @FunctionalInterface + interface TriFunction { + R apply(A a, B b, C c); + } + + + public static void main(String[] args) { + + g(10); // st #10, sp + // jmp function_g + + List l1 = new ArrayList<>(); + for (int i = 0; i < 10; ++i) { + l1.add(i); + } + Collection r1 = map(l1, (x) -> x * 2); + int sum = fold(r1, 0, (x, acc) -> x + acc); + + + List l2 = new ArrayList<>(); + for (int i = 0; i < 10; ++i) { + l2.add(new Dog(i, "red")); + } + List r2 = map(l2, (ColoredAnimal x) -> new Dog(x.getWeight() - 5, x.getColor())); + + iter(l2, (Dog d) -> System.out.println(d)); + for (Dog d : l2) System.out.println(d); + List r = map(l2, (Dog d) -> { System.out.println(d); return null; }); + + + String s = "ciao"; + boolean b = s.isEmpty(); + Function f = String::isEmpty; + Predicate p = String::isEmpty; + + int i = s.indexOf('c'); + BiFunction g = String::indexOf; + + int j = s.lastIndexOf('c', 8); + TriFunction h = String::lastIndexOf; + + { + List l = new ArrayList<>(); + l.add("pippo"); + l.add("baudo"); + l.add("pluto"); + String s2 = String.join(",", l); + BiFunction, String> k = String::join; + } + + Function id = Function.identity(); + Function id2 = (x) -> x; // fun x -> x + + } + +} diff --git a/2019-20/Lezioni/src/it/unive/dais/po2/other/FunctionalTest.java b/2019-20/Lezioni/src/it/unive/dais/po2/other/FunctionalTest.java new file mode 100644 index 0000000..24b3b1a --- /dev/null +++ b/2019-20/Lezioni/src/it/unive/dais/po2/other/FunctionalTest.java @@ -0,0 +1,122 @@ +package it.unive.dais.po2.other; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; + +public class FunctionalTest { + + public static Collection map(Collection l, Function f) { + Collection c = new ArrayList<>(); + for (A a : l) { + B b = f.apply(a); + c.add(b); + } + return c; + } + + public static void print(Collection c) { + map(c, new Function() { + @Override + public Void apply(X x) { + System.out.println(x); + return null; + } + }); + + } + + private static class MiaFunzionePerMap implements Function { + @Override + public Integer apply(Integer x) { + return x + 1; + } + } + + + public static void main(String[] args) { + + List l = new ArrayList<>(); + for (int i = 0; i < 10; ++i) { + l.add(i); + } + print(l); + + // LE 4 FORME DI LAMBDA IN JAVA + Function f = x -> x + 1; + Function f2 = new Function() { + @Override + public Integer apply(Integer x) { + return x + 1; + } + }; + + Supplier g = () -> { + if (l.size() > 4) return 1; + else return 2; + }; + Supplier g2 = new Supplier() { + @Override + public Integer get() { + if (l.size() > 4) return 1; + else return 2; + } + }; + + Consumer h = (x) -> { + for (int i = 0; i < x; ++i) + System.out.println(i); + }; + Consumer h2 = new Consumer() { + @Override + public void accept(Integer x) { + for (int i = 0; i < x; ++i) + System.out.println(i); + } + }; + + Runnable r = () -> { + System.out.println("ciao"); + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + System.out.println("ciao"); + } + }; + + + // ESEMPI DI CHIAMATA ALLA map() + + // questa è la stessa cosa fatta con una lambda + Collection x1 = map(l, x -> x + 1); + // questa è con la classe anonima + Collection x2 = map(l, new Function() { + @Override + public Integer apply(Integer x) { + return x + 1; + } + }); + // questa terza variante usa direttamente una classe NON-anonima + Collection x3 = map(l, new MiaFunzionePerMap()); + + print(l); + + /* + TRADUZIONE DA ANONYMOUS CLASS A LAMBDA + LA LAMBDA E' UNO ZUCCHERO SINTATTICO PER UNA ANONYMOUS CLASS + Collection r = map(l, new Function() { + @Override + public B apply(A x) { + BODY; + } + }); + + Collection r = map(l, x -> BODY); + */ + + } +} diff --git a/2020/Lezioni/src/it/unive/dais/po2/other/IteratorTest.java b/2019-20/Lezioni/src/it/unive/dais/po2/other/IteratorTest.java similarity index 74% rename from 2020/Lezioni/src/it/unive/dais/po2/other/IteratorTest.java rename to 2019-20/Lezioni/src/it/unive/dais/po2/other/IteratorTest.java index 919b0b2..c85aefd 100644 --- a/2020/Lezioni/src/it/unive/dais/po2/other/IteratorTest.java +++ b/2019-20/Lezioni/src/it/unive/dais/po2/other/IteratorTest.java @@ -1,5 +1,7 @@ package it.unive.dais.po2.other; +import it.unive.dais.po2.myjdk.MyIterator; + import java.util.*; public class IteratorTest { @@ -19,7 +21,7 @@ public static void sum(Iterable a) { System.out.println(r); } - public static void main(String[] args) { + public static void main2(String[] args) { ArrayList a = new ArrayList<>(); populate(a); @@ -64,4 +66,27 @@ public void populate() { } } + + + + + public static void main(String[] args) { + + List l = new ArrayList<>(); + for (int i = 0; i < 10; ++i) { + l.add(i); + } + + Iterator it = l.iterator(); + while (it.hasNext()) { + int n = it.next(); + System.out.println(n); + } + + for (int n : l) { + System.out.println(n); + } + + } + } diff --git a/2019-20/Lezioni/src/it/unive/dais/po2/other/IteratorTest__Mattia.java b/2019-20/Lezioni/src/it/unive/dais/po2/other/IteratorTest__Mattia.java new file mode 100644 index 0000000..f688b32 --- /dev/null +++ b/2019-20/Lezioni/src/it/unive/dais/po2/other/IteratorTest__Mattia.java @@ -0,0 +1,83 @@ +package it.unive.dais.po2.other; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Iterator; + +public class IteratorTest__Mattia { + + public static class MyArrayList extends ArrayList { /* eredito tutti i membri di ArrayList */ + + public enum IteratorKind {DEFAULT, EVEN, ODD} + + /* + * Gli assegnamenti fatti in concomitanza con la dichiarazione dei field, + * avvengono prima dell' inizializzazione del costruttore + */ + private IteratorKind kind; /* private field di MyArrayList*/ + + /* + * Costruttore definito affinchè sia possibile decidere in fase + * di creazione dell'oggetto MyArrayList, quale comportamento dovrà + * avere l'iteratore (nel momento del suo utilizzo) + */ + public MyArrayList(IteratorKind kind) { + this.kind = kind; + } + + /* Costruttore di default, dichiarato esplicitamente (perchè dichiarato un altro costruttore)*/ + public MyArrayList() { + /* assicura il corretto comportamento del metodo Next, + * nel caso in cui non venga definito dall'utente un + * comportamento speciale per l'iteratore in caso di costruzione + * dell'oggetto MyArrayList + */ + this.kind = IteratorKind.DEFAULT; + } + + + /* + * Overrido il metodo iterator dell'interfaccia Iterable (ereditata con ArrayList) + * affinchè venga ritornato il mio oggetto Iterator (opportunamente modificato) + * al posto dell'Iterator classico (ereditato) di ArrayList*/ + @NotNull + @Override + public Iterator iterator() { + return new Iterator<>() { + + private int i = 0; /* private field della nuova */ + + @Override + public boolean hasNext() { + return i < size(); /* Zucchero sintattico per: MyArrayList.this.size(); */ + } + + @Override + public T next() { + @Nullable T toReturn = null; + + switch (kind) { + case DEFAULT: + toReturn = get(i++); + break; + case EVEN: + toReturn = get(i++); + if (hasNext())/* scarto il prossimo valore solo se questo è presente */ + get(i++); + break; + case ODD: + get(i++); + if (hasNext()) /* scarto il prossimo valore solo se questo è presente */ + toReturn = get(i++); + } + + return toReturn; + } + }; + + } + + } +} diff --git a/2019-20/Lezioni/src/it/unive/dais/po2/other/RevArrayList.java b/2019-20/Lezioni/src/it/unive/dais/po2/other/RevArrayList.java new file mode 100644 index 0000000..77ca60c --- /dev/null +++ b/2019-20/Lezioni/src/it/unive/dais/po2/other/RevArrayList.java @@ -0,0 +1,73 @@ +package it.unive.dais.po2.other; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class RevArrayList extends ArrayList { + public RevArrayList() { + super(); + } + + public RevArrayList(int cap) { + super(cap); + } + + public static class RevIterator__static implements Iterator { + private List l; + private int pos; + + public RevIterator__static(List l) { + this.l = l; + this.pos = l.size() - 1; + } + + @Override + public boolean hasNext() { + return pos >= 0; + } + + @Override + public T next() { + return l.get(pos--); + } + } + + private class RevIterator__nonstatic implements Iterator { + + private int pos = RevArrayList.this.size() - 1; + + @Override + public boolean hasNext() { + return pos >= 0; + } + + @Override + public T next() { + return RevArrayList.this.get(pos--); + } + } + + @Override + public Iterator iterator() { + //return new RevIterator(this); // classe globale + //return new RevIterator__static(this); // classe nested STATICA + //return new RevIterator__nonstatic(); // classe nested NON STATIC + + return new Iterator() { // anonymous class + private int pos = size() - 1; + + @Override + public boolean hasNext() { + return pos >= 0; + } + + @Override + public T next() { + T r = get(pos); + pos = pos - 2; + return r; + } + }; + } +} diff --git a/2019-20/Lezioni/src/it/unive/dais/po2/other/RevIterator.java b/2019-20/Lezioni/src/it/unive/dais/po2/other/RevIterator.java new file mode 100644 index 0000000..e45cfeb --- /dev/null +++ b/2019-20/Lezioni/src/it/unive/dais/po2/other/RevIterator.java @@ -0,0 +1,25 @@ +package it.unive.dais.po2.other; + +import java.util.Iterator; +import java.util.List; + +public class RevIterator implements Iterator { + private List l; + private int pos; + + public RevIterator(List l) { + this.l = l; + this.pos = l.size() - 1; + } + + @Override + public boolean hasNext() { + return pos >= 0; + } + + @Override + public T next() { + return l.get(pos--); + } +} + diff --git a/2019-20/Lezioni/src/it/unive/dais/po2/other/RevTest.java b/2019-20/Lezioni/src/it/unive/dais/po2/other/RevTest.java new file mode 100644 index 0000000..0c6f196 --- /dev/null +++ b/2019-20/Lezioni/src/it/unive/dais/po2/other/RevTest.java @@ -0,0 +1,23 @@ +package it.unive.dais.po2.other; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; + + +public class RevTest { + + public static void main(String[] args) { + Collection l = new RevArrayList<>(); + for (int i = 0; i < 10; ++i) { + l.add(i); + } + + Iterator it = l.iterator(); + while (it.hasNext()) { + int n = it.next(); + System.out.println(n); + } + } +} diff --git a/2019-20/Lezioni/src/it/unive/dais/po2/other/SortingTest.java b/2019-20/Lezioni/src/it/unive/dais/po2/other/SortingTest.java new file mode 100644 index 0000000..2558372 --- /dev/null +++ b/2019-20/Lezioni/src/it/unive/dais/po2/other/SortingTest.java @@ -0,0 +1,131 @@ +package it.unive.dais.po2.other; + +import it.unive.dais.po2.zoo.Dog; +import org.jetbrains.annotations.NotNull; + +import java.util.*; + +public class SortingTest { + + + private static final String ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + + public static String randomAlphaNumeric(int count) { + StringBuilder builder = new StringBuilder(); + while (count-- != 0) { + int character = (int) (Math.random() * ALPHA_NUMERIC_STRING.length()); + builder.append(ALPHA_NUMERIC_STRING.charAt(character)); + } + return builder.toString(); + } + + public static void main(String[] args) { + Random rand = new Random(); + List l = new ArrayList<>(); + for (int i = 0; i < 10; ++i) { + l.add(rand.nextInt(100)); + } + List l2 = new ArrayList<>(); + for (int i = 0; i < 10; ++i) { + l2.add(randomAlphaNumeric(10)); + } + + List l3 = new ArrayList<>(); + for (int i = 0; i < 10; ++i) { + l3.add(new Dog(rand.nextInt(100), randomAlphaNumeric(5))); + } + + List l4 = new ArrayList<>(); + for (int i = 0; i < 10; ++i) { + l4.add(new Rectangle(rand.nextDouble(), rand.nextDouble())); + } + + List l5 = new ArrayList<>(); + for (int i = 0; i < 10; ++i) { + l5.add(new Square(rand.nextDouble() * 10.)); + } + + System.out.println(l); + Collections.sort(l); + System.out.println(l); + + System.out.println(l2); + Collections.sort(l2); + System.out.println(l2); + + System.out.println(l3); + Collections.sort(l3); + System.out.println(l3); + + System.out.println(l4); + Collections.sort(l4, new Comparator() { + @Override + public int compare(Rectangle o1, Rectangle o2) { + return Double.compare(o1.base, o2.base); + // confronto a mano tra due double + /*if (Math.abs(o1.base - o2.base) <= Double.MIN_VALUE) + return 0; + else if (o1.base - o2.base > 0.) return 1; + else return -1;*/ + // confronto a mano tra due double con if funzionale + // return Math.abs(o1.base - o2.base) <= Double.MIN_VALUE ? 0 : o1.base - o2.base > 0. ? 1 : -1; + } + }); + System.out.println(l4); + Collections.sort(l4, new Comparator() { + @Override + public int compare(Rectangle o1, Rectangle o2) { + return Double.compare(o1.height, o2.height); + } + }); + Collections.sort(l4, (o1, o2) -> Double.compare(o1.height, o2.height)); + // questo non compila + //Collections.sort(l4, (Square s1, Square s2) -> Double.compare(s1.diag(), s2.diag())); + System.out.println(l4); + + + System.out.println(l5); + Collections.sort(l5, (Square s1, Square s2) -> Double.compare(s1.diag(), s2.diag())); + System.out.println(l5); + Collections.sort(l5, (s1, s2) -> Double.compare(s1.area(), s2.area())); + System.out.println(l5); + + } + + + private static class Rectangle { + public final double base, height; + + public Rectangle(double b, double h) { + this.base = b; + this.height = h; + } + + public double area() { return base * height; } + public double perimeter() { return (base + height) * 2.; } + + @Override + public String toString() { + return String.format("Rectangle[%g * %g]", base, height); + } + } + + private static class Square extends Rectangle { + public Square(double l) { + super(l, l); + } + + public double side() { return base; } + public double diag() { return side() * Math.sqrt(2.); } + + @Override + public String toString() { + return String.format("Square[%g]", side()); + } + } + + + // firme "fake" delle sort + static > void sort__(List list) {} + static void sort__(List list, Comparator c) {} +} diff --git a/2019-20/Lezioni/src/it/unive/dais/po2/patterns/ConsumerProducer.java b/2019-20/Lezioni/src/it/unive/dais/po2/patterns/ConsumerProducer.java new file mode 100644 index 0000000..57ffc57 --- /dev/null +++ b/2019-20/Lezioni/src/it/unive/dais/po2/patterns/ConsumerProducer.java @@ -0,0 +1,123 @@ +package it.unive.dais.po2.patterns; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.concurrent.locks.ReentrantLock; + +public class ConsumerProducer { + + private static Random rnd = new Random(); + + private static int rand(int a, int b) { + return rnd.nextInt(b - a + 1) + a; + } + + // se fosse necessario synchronized + private static synchronized int rand__sync(int a, int b) { + return rnd.nextInt(b - a + 1) + a; + } + + // se fosse necessario synchronized: dezuccherata + private static synchronized int rand__sync_desugared(int a, int b) { + synchronized (ConsumerProducer.class) { + return rnd.nextInt(b - a + 1) + a; + } + } + + // se fosse necessario usare i lock + private static int rand__lock(int a, int b) { + ReentrantLock l = new ReentrantLock(); + try { + return rnd.nextInt(b - a + 1) + a; + } finally { + l.unlock(); + } + } + + private static void log(String msg) { + Thread self = Thread.currentThread(); + System.out.println(String.format("%s[%d]: %s", self.getName(), self.getId(), msg)); + } + + private static Object dummy = new Object(); + + public static class Consumer extends Thread { + private List l1; + private List l2; + + public Consumer(List l1, List l2) { + this.l1 = l1; + this.l2 = l2; + } + + @Override + public void run() { + while (true) { + synchronized (dummy) { + if (!l1.isEmpty() && !l2.isEmpty()) { + int n1 = l1.remove(0); + int n2 = l2.remove(0); + log(String.format("Consumer: pop: %d, %d (size: %d, %d) %s %s", n1, n2, l1.size(), l2.size(), l1, l2)); + } + } + try { + Thread.sleep(rand(1, 50)); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } + + public static class Producer extends Thread { + private List l1; + private List l2; + + public Producer(List l1, List l2) { + this.l1 = l1; + this.l2 = l2; + } + + private int counter = 0; + + @Override + public void run() { + while (true) { + int n = counter++; + synchronized (dummy) { + l1.add(n); + l2.add(n); + log(String.format("Producer: push: %d (size: %d, %d) %s %s", n, l1.size(), l2.size(), l1, l2)); + } + try { + Thread.sleep(rand(1, 50)); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } + + public static void main(String[] args) { + try { + List l1 = new ArrayList<>(); + List l2 = new ArrayList<>(); + Consumer c = new Consumer(l1, l2); + Producer p1 = new Producer(l1, l2); + Producer p2 = new Producer(l1, l2); + + c.start(); + p1.start(); + p2.start(); + + c.join(); + p1.join(); + p2.join(); + + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + +} diff --git a/2019-20/Lezioni/src/it/unive/dais/po2/patterns/Singleton.java b/2019-20/Lezioni/src/it/unive/dais/po2/patterns/Singleton.java new file mode 100644 index 0000000..04deade --- /dev/null +++ b/2019-20/Lezioni/src/it/unive/dais/po2/patterns/Singleton.java @@ -0,0 +1,28 @@ +package it.unive.dais.po2.patterns; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +// verione minimal di un singleton, ma non è riutilizzabile + +public class Singleton { + + @Nullable + private static Singleton instance = null; + + // fa ciò che fa la cache con una entry + @NotNull + public static Singleton getInstance() { + if (instance == null) { + instance = new Singleton(); + } + return instance; + } + + + public static void main(String[] args) { + Singleton s = Singleton.getInstance(); + } + + +} diff --git a/2019-20/Lezioni/src/it/unive/dais/po2/patterns/SyncSingleton.java b/2019-20/Lezioni/src/it/unive/dais/po2/patterns/SyncSingleton.java new file mode 100644 index 0000000..06fac0c --- /dev/null +++ b/2019-20/Lezioni/src/it/unive/dais/po2/patterns/SyncSingleton.java @@ -0,0 +1,53 @@ +package it.unive.dais.po2.patterns; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class SyncSingleton { + + public static class Display { + // eventuali campi privati non-statici + + @Nullable + private static Display instance = null; + + private int cnt; + + private Display(int n) { + this.cnt = n; + // inizializzazione di tutti i tuoi campi privati non-statici + } + + // metodi che modificano lo stato + public synchronized int getCounter() { + return cnt; + } + + public synchronized void setCounter(int n) { + cnt = n; + } + + public synchronized void incrementCounter() { + ++cnt; + } + + @NotNull + public static synchronized Display getInstance(int cnt) { + if (instance == null) { + instance = new Display(cnt); + } + synchronized (instance) { + instance.cnt *= 3; // esempio di modifica dello stato + } + return instance; + } + + } + + public static void main(String[] args) { + Display d = Display.getInstance(50); + Display d2 = Display.getInstance(50); + } + + +} diff --git a/2019-20/Lezioni/src/it/unive/dais/po2/patterns/factory/Circle.java b/2019-20/Lezioni/src/it/unive/dais/po2/patterns/factory/Circle.java new file mode 100644 index 0000000..b426049 --- /dev/null +++ b/2019-20/Lezioni/src/it/unive/dais/po2/patterns/factory/Circle.java @@ -0,0 +1,24 @@ +package it.unive.dais.po2.patterns.factory; + +class Circle implements Shape { + private final double ray; + + Circle(double ray) { + this.ray = ray; + } + + @Override + public void draw() { + System.out.println(String.format("Circle[ray:%g]", ray)); + } + + @Override + public double area() { + return Math.PI * ray * ray; + } + + @Override + public double perimeter() { + return Math.PI * 2. * ray; + } +} diff --git a/2019-20/Lezioni/src/it/unive/dais/po2/patterns/factory/Main.java b/2019-20/Lezioni/src/it/unive/dais/po2/patterns/factory/Main.java new file mode 100644 index 0000000..681234c --- /dev/null +++ b/2019-20/Lezioni/src/it/unive/dais/po2/patterns/factory/Main.java @@ -0,0 +1,14 @@ +package it.unive.dais.po2.patterns.factory; + +public class Main { + + public static void main(String[] args) { + try { + ShapeFactory factory = new ShapeFactoryWider(4.); + Shape shape1 = factory.create("rectangle", 10, 11); + Shape shape2 = factory.create("circle", 19); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/2019-20/Lezioni/src/it/unive/dais/po2/patterns/factory/Rectangle.java b/2019-20/Lezioni/src/it/unive/dais/po2/patterns/factory/Rectangle.java new file mode 100644 index 0000000..1dc7a08 --- /dev/null +++ b/2019-20/Lezioni/src/it/unive/dais/po2/patterns/factory/Rectangle.java @@ -0,0 +1,26 @@ +package it.unive.dais.po2.patterns.factory; + +class Rectangle implements Shape { + + private final double base, height; + + Rectangle(double base, double height) { + this.base = base; + this.height = height; + } + + @Override + public void draw() { + System.out.println(String.format("Rectangle[%gx%g]", base, height)); + } + + @Override + public double area() { + return base * height; + } + + @Override + public double perimeter() { + return (base + height) * 2.; + } +} diff --git a/2019-20/Lezioni/src/it/unive/dais/po2/patterns/factory/Shape.java b/2019-20/Lezioni/src/it/unive/dais/po2/patterns/factory/Shape.java new file mode 100644 index 0000000..e40f9fa --- /dev/null +++ b/2019-20/Lezioni/src/it/unive/dais/po2/patterns/factory/Shape.java @@ -0,0 +1,7 @@ +package it.unive.dais.po2.patterns.factory; + +public interface Shape { + void draw(); + double area(); + double perimeter(); +} diff --git a/2019-20/Lezioni/src/it/unive/dais/po2/patterns/factory/ShapeFactory.java b/2019-20/Lezioni/src/it/unive/dais/po2/patterns/factory/ShapeFactory.java new file mode 100644 index 0000000..018221a --- /dev/null +++ b/2019-20/Lezioni/src/it/unive/dais/po2/patterns/factory/ShapeFactory.java @@ -0,0 +1,17 @@ +package it.unive.dais.po2.patterns.factory; + +import org.jetbrains.annotations.NotNull; + +public class ShapeFactory { + + @NotNull + public Shape create(String name, double... data) throws Exception { + if (name.toLowerCase().equals("rectangle")) + return new Rectangle(data[0], data[1]); + else if (name.toLowerCase().equals("circle")) + return new Circle(data[0]); + else throw new Exception("invalid shape: " + name); + } + + +} diff --git a/2019-20/Lezioni/src/it/unive/dais/po2/patterns/factory/ShapeFactoryWider.java b/2019-20/Lezioni/src/it/unive/dais/po2/patterns/factory/ShapeFactoryWider.java new file mode 100644 index 0000000..f87f514 --- /dev/null +++ b/2019-20/Lezioni/src/it/unive/dais/po2/patterns/factory/ShapeFactoryWider.java @@ -0,0 +1,23 @@ +package it.unive.dais.po2.patterns.factory; + +import org.jetbrains.annotations.NotNull; + +public class ShapeFactoryWider extends ShapeFactory { + + private final double amp; + + public ShapeFactoryWider(double amp) { + this.amp = amp; + } + + @Override + @NotNull + public Shape create(String name, double... data) throws Exception { + if (name.toLowerCase().equals("rectangle")) + return new Rectangle(data[0] * amp, data[1] * amp); + else if (name.toLowerCase().equals("circle")) + return new Circle(data[0] * amp); + else throw new Exception("invalid shape: " + name); + } + +} diff --git a/2019-20/Lezioni/src/it/unive/dais/po2/threading/ThreadCreationMain.java b/2019-20/Lezioni/src/it/unive/dais/po2/threading/ThreadCreationMain.java new file mode 100644 index 0000000..ca05694 --- /dev/null +++ b/2019-20/Lezioni/src/it/unive/dais/po2/threading/ThreadCreationMain.java @@ -0,0 +1,92 @@ +package it.unive.dais.po2.threading; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Random; + +public class ThreadCreationMain { + + + private static void count(String id, long millis, int times) { + try { + for (int i = 0; i < times; ++i) { + System.out.println(id + ": " + i); + Thread.sleep(millis); + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + + public static class CounterThread extends Thread { + private String name; + private long millis; + private int times; + + public CounterThread(String name, long millis, int times) { + this.name = name; + this.millis = millis; + this.times = times; + } + + @Override + public void run() { + count(name, millis, times); + } + } + + private static Random rnd = new Random(); + + private static int rand(int a, int b) { + return rnd.nextInt(b - a + 1) + a; + } + + public static void main(String[] args) { + + Collection threads = new ArrayList<>(); + for (int i = 0; i < rand(5, 20); ++i) { + final String name = String.format("thread#%d", i); + final long millis = rand(200, 800); + final int times = rand(10, 30); + + // creazione di un thread passando un Runnable al costruttore + // Runnable = lambda senza argomenti e senza ritorno + Thread t1 = new Thread(() -> { + count(name, millis, times); + }); + // stessa cosa ma con la lambda dezuccherata in un Runnable + Thread t2 = new Thread(new Runnable() { + @Override + public void run() { + count(name, millis, times); + } + }); + // creazione di un thread tramite una anonymous class con override al volo del metodo run + Thread t3 = new Thread() { + @Override + public void run() { + count(name, millis, times); + } + }; + // creazione di una istanza di CounterThread, cioè di un sottotipo di Thread + // e passaggio dei parametri al costruttore + Thread t4 = new CounterThread(name, millis, times); + + Thread t = t1; + t.start(); + threads.add(t); + } + + // attendo che tutti i thread creati finiscano + for (Thread t : threads) { + try { + t.join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + } + +} diff --git a/2019-20/Lezioni/src/it/unive/dais/po2/zoo/Animal.java b/2019-20/Lezioni/src/it/unive/dais/po2/zoo/Animal.java new file mode 100644 index 0000000..02ded64 --- /dev/null +++ b/2019-20/Lezioni/src/it/unive/dais/po2/zoo/Animal.java @@ -0,0 +1,22 @@ +package it.unive.dais.po2.zoo; + +import org.jetbrains.annotations.NotNull; + +public class Animal implements Creature, Comparable { + protected int weight; + + public Animal(int weight) { + this.weight = weight; + } + + public int getWeight() { return weight; } + + public void eat(Animal a) { + this.weight += a.weight; + } + + @Override + public int compareTo(@NotNull Animal o) { + return this.weight - o.weight; + } +} diff --git a/2020/Lezioni/src/it/unive/dais/po2/zoo/Cat.java b/2019-20/Lezioni/src/it/unive/dais/po2/zoo/Cat.java similarity index 67% rename from 2020/Lezioni/src/it/unive/dais/po2/zoo/Cat.java rename to 2019-20/Lezioni/src/it/unive/dais/po2/zoo/Cat.java index 9b04d47..3852fb5 100644 --- a/2020/Lezioni/src/it/unive/dais/po2/zoo/Cat.java +++ b/2019-20/Lezioni/src/it/unive/dais/po2/zoo/Cat.java @@ -1,10 +1,10 @@ package it.unive.dais.po2.zoo; -public class Cat extends ColoredAnimal { +public class Cat extends ColoredAnimal { - public Cat(int w, String c, Cat p) { - super(w, c, p); + public Cat(int w, String c) { + super(w, c); } @Override @@ -13,7 +13,6 @@ public void eat(Animal a) { color = color + " fat"; } - public void meow() { System.out.println("miao!"); } diff --git a/2019-20/Lezioni/src/it/unive/dais/po2/zoo/ColoredAnimal.java b/2019-20/Lezioni/src/it/unive/dais/po2/zoo/ColoredAnimal.java new file mode 100644 index 0000000..c6c6b1d --- /dev/null +++ b/2019-20/Lezioni/src/it/unive/dais/po2/zoo/ColoredAnimal.java @@ -0,0 +1,13 @@ +package it.unive.dais.po2.zoo; + +public abstract class ColoredAnimal extends Animal { + protected String color; + + protected ColoredAnimal(int w, String c) { + super(w); + this.color = c; + } + + public String getColor() { return color; } + +} diff --git a/2020/Lezioni/src/it/unive/dais/po2/zoo/Creature.java b/2019-20/Lezioni/src/it/unive/dais/po2/zoo/Creature.java similarity index 100% rename from 2020/Lezioni/src/it/unive/dais/po2/zoo/Creature.java rename to 2019-20/Lezioni/src/it/unive/dais/po2/zoo/Creature.java diff --git a/2019-20/Lezioni/src/it/unive/dais/po2/zoo/Dog.java b/2019-20/Lezioni/src/it/unive/dais/po2/zoo/Dog.java new file mode 100644 index 0000000..d6b02a5 --- /dev/null +++ b/2019-20/Lezioni/src/it/unive/dais/po2/zoo/Dog.java @@ -0,0 +1,37 @@ +package it.unive.dais.po2.zoo; + +import org.jetbrains.annotations.NotNull; + +public class Dog extends ColoredAnimal { + private int bava; + + public Dog(int w, String c) { + super(w, c); + bava = w / 10; + } + + @Override + public void eat(Animal a) { + weight += a.weight / 2; + } + + public void bark() { + System.out.println("bau!"); + } + + @Override + public int compareTo(@NotNull Animal o) { + if (o instanceof Dog) { + Dog u = (Dog) o; + return (this.bava + this.weight) - (o.weight + u.bava); + } + else { + return super.compareTo(o); + } + } + + @Override + public String toString() { + return String.format("Dog[%d, %s]", weight, color); + } +} diff --git a/2019-20/Lezioni/src/it/unive/dais/po2/zoo/Main.java b/2019-20/Lezioni/src/it/unive/dais/po2/zoo/Main.java new file mode 100644 index 0000000..0377492 --- /dev/null +++ b/2019-20/Lezioni/src/it/unive/dais/po2/zoo/Main.java @@ -0,0 +1,70 @@ +package it.unive.dais.po2.zoo; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.function.Function; + +public class Main { + + public static void main(String[] args) { + Dog fido = new Dog(15, "bruno"); + Dog baldo = new Dog(20, "bianco"); + + List dogs = new ArrayList<>(); + dogs.add(fido); + dogs.add(baldo); + + /* + List l3 = new ArrayList(); + l3.add(new Cat(10, "idfif")); + + // wildcards + + List l = new ArrayList<>(); + Animal a1 = l.get(0); + + l.set(0, new Dog(10, "fido")); + l.add(new Dog(10, "fido")); + + + List l2 = new ArrayList<>(); + Animal a2 = l2.get(0); + + l2.set(0, new Dog(10, "fido")); + l2.set(0, new Animal(10)); + l2.add(new Dog(10, "fido")); + + Function f1 = (Animal s) -> new Cat(s.weight, "blu"); + Function f = f1;*/ + + + + // TODO: provare a mettere a posto in modo che compili +/* Animal jackie = new Dog(2, "nero"); + Dog pluto = new Animal(50); + Animal selene = new Cat(4, "grigio"); + + // sumsumption NON valide + Dog fido2 = selene; + Cat selene2 = selene; + + Cat tigre = new Cat(20); + Animal cane = new Dog(50, tigre); + Animal p = fido.getPartner(); + + selene.eat(fido); + + Animal a = new Persian(6, fido); + a.meow(); // NON COMPILA + a.eat(fido); + + a.eat(a); // mangiare se stessi si può fare +*/ + + } + +} + + diff --git a/2020/Lezioni/src/it/unive/dais/po2/zoo/Persian.java b/2019-20/Lezioni/src/it/unive/dais/po2/zoo/Persian.java similarity index 70% rename from 2020/Lezioni/src/it/unive/dais/po2/zoo/Persian.java rename to 2019-20/Lezioni/src/it/unive/dais/po2/zoo/Persian.java index 05663a9..b29467f 100644 --- a/2020/Lezioni/src/it/unive/dais/po2/zoo/Persian.java +++ b/2019-20/Lezioni/src/it/unive/dais/po2/zoo/Persian.java @@ -1,8 +1,8 @@ package it.unive.dais.po2.zoo; public class Persian extends Cat { - public Persian(int w, Cat p) { - super(w, "beige", p); + public Persian(int w) { + super(w, "beige"); } @Override diff --git a/2020-21/Lezioni/.idea/.gitignore b/2020-21/Lezioni/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/2020-21/Lezioni/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/2020-21/Lezioni/.idea/codeStyles/Project.xml b/2020-21/Lezioni/.idea/codeStyles/Project.xml new file mode 100644 index 0000000..645f4a0 --- /dev/null +++ b/2020-21/Lezioni/.idea/codeStyles/Project.xml @@ -0,0 +1,22 @@ + + + + + + + + \ No newline at end of file diff --git a/2020-21/Lezioni/.idea/codeStyles/codeStyleConfig.xml b/2020-21/Lezioni/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 0000000..a55e7a1 --- /dev/null +++ b/2020-21/Lezioni/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/2020-21/Lezioni/.idea/inspectionProfiles/Project_Default.xml b/2020-21/Lezioni/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 0000000..89b5350 --- /dev/null +++ b/2020-21/Lezioni/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,19 @@ + + + + \ No newline at end of file diff --git a/2020-21/Lezioni/.idea/misc.xml b/2020-21/Lezioni/.idea/misc.xml new file mode 100644 index 0000000..6c05f06 --- /dev/null +++ b/2020-21/Lezioni/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/2020-21/Lezioni/.idea/modules.xml b/2020-21/Lezioni/.idea/modules.xml new file mode 100644 index 0000000..8617dec --- /dev/null +++ b/2020-21/Lezioni/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/2020-21/Lezioni/.idea/uiDesigner.xml b/2020-21/Lezioni/.idea/uiDesigner.xml new file mode 100644 index 0000000..e96534f --- /dev/null +++ b/2020-21/Lezioni/.idea/uiDesigner.xml @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/2020-21/Lezioni/.idea/vcs.xml b/2020-21/Lezioni/.idea/vcs.xml new file mode 100644 index 0000000..b2bdec2 --- /dev/null +++ b/2020-21/Lezioni/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/2020-21/Lezioni/Lezioni.iml b/2020-21/Lezioni/Lezioni.iml new file mode 100644 index 0000000..6f78716 --- /dev/null +++ b/2020-21/Lezioni/Lezioni.iml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/functional/IteratorTest.java b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/functional/IteratorTest.java new file mode 100644 index 0000000..1c4adf2 --- /dev/null +++ b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/functional/IteratorTest.java @@ -0,0 +1,137 @@ +package it.unive.dais.po2.aa2020_21.functional; + +import org.jetbrains.annotations.NotNull; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.function.Function; + +public class IteratorTest { + + @NotNull + public static Iterator skipIterator(@NotNull Iterator it, int step) { + // TODO da implementare come esercizio: deve comportarsi come l'iteratore di SkipArrayList più in basso + throw new RuntimeException("not implemented"); + } + + // modo 1.A: rovesciare l'iteratore di input + public static Iterator revIterator(Iterator it) { + // lista dritta, iteratore rovescio + List l = new ArrayList<>(); + while (it.hasNext()) { + l.add(it.next()); + } + return new Iterator() { + private int pos = l.size() - 1; + + @Override + public boolean hasNext() { + return pos >= 0; + } + + @Override + public A next() { + return l.get(pos--); + } + }; + } + + // modo 1.B: rovesciare l'iteratore di input + public static Iterator revIterator2(Iterator it) { + // lista rovescia, iteratore dritto + List l = new ArrayList<>(); + while (it.hasNext()) { + l.add(0, it.next()); + } + return l.iterator(); + } + + // modo 2: rovesciare l'iteratore overridandolo + public static class RevArrayList extends ArrayList { + @Override + public Iterator iterator() { // produce un iteratore che va al contrario + return new Iterator() { + private int pos = RevArrayList.this.size() - 1; + + @Override + public boolean hasNext() { + return pos >= 0; + } + + @Override + public T next() { + return RevArrayList.this.get(pos--); + } + }; + } + } + + // classe che offre iteratori capaci di skippare ("saltare") elementi secondo un valore di step + public static class SkipArrayList extends ArrayList { + private final int step; + + public SkipArrayList(int step) { + this.step = step; + } + + @Override + public Iterator iterator() { // produce un iteratore che va al contrario + return new Iterator() { + private int pos = step < 0 ? SkipArrayList.this.size() - 1 : 0; + + @Override + public boolean hasNext() { + return step < 0 ? (pos >= 0) : (pos < SkipArrayList.this.size()); + } + + @Override + public T next() { + T x = SkipArrayList.this.get(pos); + pos += step; + return x; + } + }; + } + } + + public static Iterator mapIterator(Iterator it, Function f) { + + return new Iterator() { + @Override + public boolean hasNext() { + return it.hasNext(); + } + + @Override + public B next() { + return f.apply(it.next()); + } + }; + } + + public static Iterator mapAndRevIterator(Iterator it, Function f) { + return revIterator(mapIterator(it, f)); + } + + + public static void main(String[] args) { + + List l = new SkipArrayList<>(-3); + for (int i = 0; i < 10; ++i) { + char[] a = new char[i]; + for (int j = 0; j < a.length; ++j) + a[j] = 'a'; + l.add(new String(a)); + } + + Iterator it = mapIterator(l.iterator(), (String s) -> s.length()); + while (it.hasNext()) { + int n = it.next(); + System.out.println(n); + } + + } + + +} diff --git a/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/functional/TestFun.java b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/functional/TestFun.java new file mode 100644 index 0000000..b53957c --- /dev/null +++ b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/functional/TestFun.java @@ -0,0 +1,145 @@ +package it.unive.dais.po2.aa2020_21.functional; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; + +public class TestFun { +/* + // VERSIONE IN C: puntatori a funzione + int f(int n, int(*g)(int)) { // f ha tipo: int(*)(int, int(*)(int)) + return g(n); + } + + int increment(int x) { return x + 1; } // increment ha tipo: int(*)(int) + + int main() { + int y = f(7, &increment); + } + + // VERSIONE IN F#: funzioni come valori del primo ordine + let f (n, g) = g(n) // f : int * (int -> int) -> int + + let increment x = x + 1 // increment : int -> int + + let main () = + let y = f(7, increment) + let z = f(10, fun x -> x - 1) // lambda +*/ + + // le 4 forme di lambda (non serve definire le proprio, ci sono nel JDK) + @FunctionalInterface + public interface Function { + B apply(A x); + } + + public interface Consumer { + void accept(A x); + } + + public interface Supplier { + A get(); + } + + public interface Runnable { + void run(); + } + + // altre functional interface + @FunctionalInterface + public interface BiFunction { + R apply(A x, B y); + } + + public interface TriFunction { + R apply(A x, B b, C c); + } + + public interface QuadFunction { + R apply(A x, B b, C c, D d); + } + + + public static int f(int n, Function g) { + return g.apply(n); + } + + + private int delta = 4; + + public static int increment(int x) { return x + 1; } + + public int decrement(int x) { return x - this.delta; } + + public void increaseDelta() { ++this.delta; } + + public int miometodo(int a, String b, ArrayList>> m) { return 0; } + + public int generateNum() { return 23; } + + private static class DecrementFun implements Function { + @Override + public Integer apply(Integer x) { + return x - 1; + } + } + + /* la funzione map in F# + let rec map f l = // map : ('a -> 'b) -> 'a list -> 'b list + match l with + | [] -> [] + | x :: xs -> f x :: map f xs + */ + + public static List map(Iterable c, Function f) { // POLIMORFISMO PARAMETRICO FIRST-CLASS + List r = new ArrayList<>(); + for(A a : c) r.add(f.apply(a)); + return r; + } + + + public static void main(String[] args) { + + Collection a1 = new ArrayList<>(); + + List l1 = TestFun.map(a1, String::length); + List l2 = TestFun.map(a1, (s) -> s.concat("ciao")); + + + + int z = f(10, new DecrementFun()); // istanza di classe passata come argomento e subsunta al tipo Function + + TestFun mytestfun = new TestFun(); // istanza di tipo TestFun + + // method reference + Function u = TestFun::increment; // reference ad un metodo statico + BiFunction u2 = TestFun::decrement; // reference ad un metodo non-statico di un oggetto arbitrario di tipo TestFun + Function u3 = mytestfun::decrement; // reference ad un metodo non-statico di un particolare oggetto di tipo TestFun + + // reference ad un metodo non-statico di un particolare oggetto di tipo TestFun: abbiamo solo i parametri visibili come type argument + TriFunction>>, Integer> u4 = mytestfun::miometodo; + // reference ad un metodo non-statico di un oggetto arbitrario di tipo TestFun: abbiamo un parametro IN PIU' di tipo TestFun + QuadFunction>>, Integer> u5 = TestFun::miometodo; + + Function j1 = TestFun::generateNum; // reference ad un metodo non-statico di un oggetto arbitrario di tipo TestFun + Supplier j2 = mytestfun::generateNum; // reference ad un metodo non-statico di un particolare oggetto di tipo TestFun + + Consumer k1 = TestFun::increaseDelta; // reference ad un metodo non-statico di un oggetto arbitrario di tipo TestFun + Runnable k2 = mytestfun::increaseDelta; // reference ad un metodo non-statico di un particolare oggetto di tipo TestFun + + + int y = f(7, TestFun::increment); // reference ad un metodo statico passato come Function + + int z1 = f(10, new Function() { // anonymous class + @Override + public Integer apply(Integer x) { + return x - 1; + } + }); + + int z2 = f(10, (x) -> x - 1); // lambda + + } + +} diff --git a/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/generics/Container.java b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/generics/Container.java new file mode 100644 index 0000000..839c261 --- /dev/null +++ b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/generics/Container.java @@ -0,0 +1,149 @@ +package it.unive.dais.po2.aa2020_21.generics; + +import java.util.ArrayList; + +public class Container { + + public static class MyIntList { + + private final int[] a; + private int cnt; + + public MyIntList() { + a = new int[100]; + cnt = 0; + } + + public void add(int v) { + a[cnt++] = v; + } + + public int size() { + return cnt; + } + + public int get(int i) { + return a[i]; + } + } + + public static class MyPolyList { + + private final Object[] a; + private int cnt; + + public MyPolyList() { + a = new Object[100]; + cnt = 0; + } + + public void add(Object v) { + a[cnt++] = v; + } + + public int size() { + return cnt; + } + + public Object get(int i) { + return a[i]; + } + } + + public static class MyGenList { + + private final Object[] a; + private int cnt; + + public MyGenList() { + a = new Object[100]; + cnt = 0; + } + + public void add(T v) { + a[cnt++] = v; + } + + public int size() { + return cnt; + } + + public T get(int i) { + return (T) a[i]; + } + } + + + public static void main(String[] args) { + + // monomorfo per int + { + // costruzione + MyIntList l = new MyIntList(); + + // popolamento + for (int i = 0; i < 10; ++i) + l.add(i); + + // lettura + for (int i = 0; i < l.size(); ++i) + System.out.println(l.get(i)); + } + + // polimorfo subtyping + { + // costruzione + MyPolyList l = new MyPolyList(); + + // popolamento + for (int i = 0; i < 10; ++i) + l.add(i); + + l.add("ciao"); + l.add(6.78); + l.add(new ArrayList()); + + // lettura + for (int i = 0; i < l.size(); ++i) { + String x = (String) l.get(i); + String y = x.toLowerCase(); + System.out.println(y); + } + } + + // generics + { + // costruzione + MyGenList l = new MyGenList(); + + // popolamento + for (int i = 0; i < 10; ++i) + l.add(i); + + // lettura + for (int i = 0; i < l.size(); ++i) { + Integer n = l.get(i); + System.out.println(n); + } + } + + // generics altro esempio + { + // costruzione + MyGenList l = new MyGenList(); + + // popolamento + l.add(new Zoo.Dog()); + l.add(new Zoo.Cat()); + l.add(new Zoo.Cocker()); + + // lettura + for (int i = 0; i < l.size(); ++i) { + Zoo.Animal n = l.get(i); // getto sempre oggetti di tipo Zoo.Animal perché l : MyGenList + System.out.println(n); + } + } + } + + +} diff --git a/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/generics/TestCollection.java b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/generics/TestCollection.java new file mode 100644 index 0000000..791a227 --- /dev/null +++ b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/generics/TestCollection.java @@ -0,0 +1,86 @@ +package it.unive.dais.po2.aa2020_21.generics; + +import java.util.*; + +public class TestCollection { + + + private static Random rnd = new Random(); + + public static void populate(Collection c) { + for (int i = 0; i < rnd.nextInt(); ++i) + c.add(i); + } + + public static void print(Iterable c) { + Iterator it = c.iterator(); + while(it.hasNext()) { + Integer n = it.next(); + System.out.println(n); + } + + /* FOR EACH è uno ZUCCHERO SINTATTICO + for (T x : e) { + st1; + ... + stn; + } + + ----->>>> si DEZUCCHERA in questo: + + Iterator it = e.iterator(); + while(it.hasNext()) { + T x = it.next(); + st1; + ... + stn; + + } + */ + } + + public static double average(Collection c) { + double r = 0.; + for (int n : c) { + r += n; + } + return r / c.size(); + } + + public static int median(List c) { + Collections.sort(c); // ordiniamo la List + return c.get(c.size() / 2); + } + + public static int median(Collection c) { + Iterator it = c.iterator(); + int r = 0; + for (int i = 0; i < c.size() / 2; ++i) + r = it.next(); + return r; + } + + + public static void main(String[] args) { + Collection a = new ArrayList<>(); + populate(a); + print(a); + System.out.println(String.format("avg = %g, median = %d", average(a), median(a))); + + LinkedList b = new LinkedList<>(); + populate(b); + print(b); + System.out.println(String.format("avg = %g, median = %d", average(b), median(b))); + + HashSet c = new HashSet<>(); + populate(c); + print(c); + System.out.println(String.format("avg = %g, median = %d", average(c), median(c))); // c non è una List quindi chiama l'overload median(Collection) + + + + } + + + +} diff --git a/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/generics/Zoo.java b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/generics/Zoo.java new file mode 100644 index 0000000..a16e7c3 --- /dev/null +++ b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/generics/Zoo.java @@ -0,0 +1,85 @@ +package it.unive.dais.po2.aa2020_21.generics; + +import java.util.ArrayList; +import java.util.Collection; + +public class Zoo { + + public static class Animal { + protected int weight; + + public void eat(Animal a) { + this.weight += a.weight; + } + } + + public static class Humanoid extends Animal { + public void marry(Humanoid d) {} + } + + public static class Elf extends Humanoid { + private int mana; + public int getMana() { return mana; } + } + + public static class Dwarf extends Humanoid { + + } + + public static class Dog extends Animal { + public void bark() { } + + @Override + public void eat(Animal a) { + this.weight += a.weight / 2; + } + } + + public static class Cocker extends Dog { + @Override + public void eat(Animal a) { + this.weight += a.weight / 3; + } + + } + + public static class Cat extends Animal { + public void meow() { + System.out.println("meow"); + } + } + + public static class Siamese extends Cat { + @Override + public void meow() { + System.out.println("maauuuu"); + } + } + + private static Dog makeAnimal() { + return new Dog(); + } + + + public static void main(String[] args) { + + Animal fido = makeAnimal(); + Animal dodi = new Dog(); + dodi = new Cat(); + Dog lilly = new Dog(); + fido.eat(lilly); // SUBSUMPTION + fido.eat(dodi); + + Humanoid john = new Humanoid(); + Humanoid alice = new Humanoid(); + Elf tara = new Elf(); + + john.marry(tara); + + + Collection dogs = new ArrayList(); + dogs.add(lilly); + dogs.add(new Dog()); + } + +} diff --git a/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/others/Singleton.java b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/others/Singleton.java new file mode 100644 index 0000000..cdb9477 --- /dev/null +++ b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/others/Singleton.java @@ -0,0 +1,28 @@ +package it.unive.dais.po2.aa2020_21.others; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import javax.swing.*; + +public class Singleton { + + @Nullable + private static Singleton instance = null; + + private int field; + + private Singleton(int x) { + this.field = x; + } + + public int getField() { return field; } + + @NotNull + public static Singleton getInstance(int x) { + if (instance == null || instance.field != x) { + instance = new Singleton(x); + } + return instance; + } +} \ No newline at end of file diff --git a/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/others/SingletonMain.java b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/others/SingletonMain.java new file mode 100644 index 0000000..3b6991e --- /dev/null +++ b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/others/SingletonMain.java @@ -0,0 +1,16 @@ +package it.unive.dais.po2.aa2020_21.others; + +public class SingletonMain { + + public static void main(String[] args) { + try { + Singleton s1 = Singleton.getInstance(7); + Singleton s2 = Singleton.getInstance(8); + Singleton s3 = Singleton.getInstance(9); + } catch (Exception e) { + e.printStackTrace(); + } + + } + +} diff --git a/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/others/Sorting.java b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/others/Sorting.java new file mode 100644 index 0000000..37ed229 --- /dev/null +++ b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/others/Sorting.java @@ -0,0 +1,151 @@ +package it.unive.dais.po2.aa2020_21.others; + +import it.unive.dais.po2.aa2020_21.generics.Zoo; +import java.util.*; +import java.util.function.Function; +import static it.unive.dais.po2.aa2020_21.functional.IteratorTest.mapIterator; + +public class Sorting { + + + public static void main(String[] args) { + + Collection c = new ArrayList<>(); + + Zoo.Dog fido = new Zoo.Dog(); + Zoo.Dog pluto = new Zoo.Dog(); + c.add(fido); + + // static boolean addAll(Collection c, T... elements) + //Collections.addAll(c, fido, pluto); // TODO da rivedere dopo + + List c2 = new ArrayList<>(); + sort(c2); + + sort(c2, new Comparator() { // (cane1, cane2) -> { return cane1.peli - cane2.peli; } + @Override + public int compare(Cane cane1, Cane cane2) { + return cane1.peli - cane2.peli; + } + }); + + sort(c2, new Comparator() { + @Override + public int compare(Animale a, Animale b) { + return a.peso - b.peso; + } + }); + + + List c3 = new ArrayList<>(); + sort(c3, (o1, o2) -> o1.foglie - o2.foglie); + + Iterator r = mapIterator(c2.iterator(), Sorting::mymapfun); + + // altri test coi wildcard + + List u1 = new ArrayList<>(); + u1.add(new Cane(50, 50)); + u1.add(new Dalmata(50, 50, 50)); + Cane ca1 = u1.get(0); // non compila + Animale ca2 = u1.get(0); // non compila + + List u2 = new ArrayList<>(); + u2.add(new Cane(50, 50)); // non compila + u2.add(new Dalmata(50, 50, 50)); // non compila + Cane ca3 = u2.get(0); + Animale ca4 = u2.get(0); + + } + + private static Integer mymapfun(Animale a) { + return a.peso; + } + + public static class Creatura {} + + + public static class Pianta extends Creatura { + public int foglie; + } + + public static class Girasole extends Pianta {} + + + public static class Animale extends Creatura implements Comparable { + protected int peso; + public Animale(int peso) { + this.peso = peso; + } + public void eat(Animale a) { + this.peso += a.peso; + } + + public Animale mate(Animale a) { + return new Animale((this.peso + a.peso) / 2); + } + + @Override + public int compareTo(Animale x) { + return this.peso - x.peso; + } + + public void m() {} + public void m(int x) {} + public double m(double y, int x) { return 0.; } + public int m(Animale a) { return 1; } + public void m(Cane a) {} + //public int m(Cane a) {} // overload invalido perché ambiguo + } + + public static class Cane extends Animale { + protected int peli; + + public Cane(int peso, int peli) { + super(peso); + this.peli = peli; + } + + @Override + public void eat(Animale a) { + this.peso += this.peso / 2; + } + + @Override + public Cane mate(Animale a) { + return new Cane((this.peso + a.peso) / 3, this.peli); + } + + @Override + public int compareTo(Animale x) { + if (x instanceof Cane) { + Cane y = (Cane) x; + return (this.peso * this.peli) - (y.peso * y.peli); + } + return super.compareTo(x); + } + + } + + public static class Dalmata extends Cane { + public int chiazze; + + public Dalmata(int peso, int peli, int chiazze) { + super(peso, peli); + this.chiazze = chiazze; + } + } + + static > void sort(List list) { + Collections.sort(list); + } + + static void sort(List list, Comparator c) { + Collections.sort(list, c); + } + + + + + +} diff --git a/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/patterns/ConsumerProducer.java b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/patterns/ConsumerProducer.java new file mode 100644 index 0000000..2d75baf --- /dev/null +++ b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/patterns/ConsumerProducer.java @@ -0,0 +1,58 @@ +package it.unive.dais.po2.aa2020_21.patterns; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; + +public class ConsumerProducer { + + private static final BlockingQueue l = new LinkedBlockingQueue<>(); + + public static class Consumer extends Thread { + + @Override + public void run() { + System.out.println("consumer started"); + while (true) { + try { + int n = l.take(); + System.out.printf("consumer: %d\n", n); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } + + public static class Producer extends Thread { + @Override + public void run() { + System.out.println("producer started"); + Random rnd = new Random(); + while (true) { + l.add(rnd.nextInt() % 100); + } + } + } + + public static void main(String[] args) { + try { + + Thread c1 = new Consumer(); + Thread p1 = new Producer(); + + c1.start(); + p1.start(); + + c1.join(); + p1.join(); + + } catch (Exception e) { + e.printStackTrace(); + } + + } + +} diff --git a/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/patterns/ThreadPool.java b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/patterns/ThreadPool.java new file mode 100644 index 0000000..ea4342a --- /dev/null +++ b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/patterns/ThreadPool.java @@ -0,0 +1,127 @@ +package it.unive.dais.po2.aa2020_21.patterns; + +import org.jetbrains.annotations.NotNull; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class ThreadPool { + + private final List threads = new ArrayList<>(); + private long timeout = 5L * 60 * 1000; + + public ThreadPool() {} + + public ThreadPool(int prespawn) { + // TODO + } + + public void setTimeoutInMillis(long tm) { + timeout = tm; + } + + // COME SI DEZUCCHERA IL COSTRUTTO SYNCHRONIZED + /*public synchronized void m1() { + synchronized (this) { + // blocco + } + } + public static synchronized void m2() { + Class c = ThreadPool.class; + synchronized (c) { + // blocco + } + }*/ + + private class PooledThread extends Thread { + @NotNull + private Runnable r; + + private long lastUsed = System.currentTimeMillis(); + + public PooledThread(Runnable r) { + this.r = r; + } + + @Override + public void run() { + while (true) { + try { + r.run(); + } catch (Exception e) { + System.out.printf("%s: exception caught\n", this); + } + synchronized (threads) { + // threads.lock() + // try { + threads.add(this); + lastUsed = System.currentTimeMillis(); + // } + // finally { threads.unlock() } + } + + // RESOURCE ALLOCATOR + /* + PREAMBOLO ad esempio lock + try { BLOCCO } ad esempio la critical section + finally { EPILOGO } ad esempio unlock + */ + try { + wait(); // TODO controllare se la notify() può accadere prima della wait() + } catch (InterruptedException e) { + e.printStackTrace(); + throw new RuntimeException(String.format("%s: interrupted. Aborting...", this)); + } + } + } + + @Override + public String toString() { + return String.format("thread#%d[%s]", getId(), getName()); + } + + public void setRunnable(Runnable r) { + this.r = r; + } + + public boolean hasExpired() { + long now = System.currentTimeMillis(); + return now - lastUsed > timeout; + } + } + + @NotNull + public Thread acquire(@NotNull Runnable r) { + PooledThread t; + synchronized (threads) { + threads.removeIf(PooledThread::hasExpired); + if (threads.isEmpty()) { + t = new PooledThread(r); + t.start(); + } else { + t = threads.remove(0); + t.setRunnable(r); + t.notify(); + } + } + return t; + } + + public static void main(String[] args) { + + ThreadPool pool = new ThreadPool(); + + Thread t = pool.acquire(() -> { + for (int i = 0; i < 10; ++i) { + Thread self = Thread.currentThread(); + System.out.printf("%s[%d]: %d", self.getName(), self.getId(), i); + } + }); + + // TODO testare la pool + + + } + +} diff --git a/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/patterns/ThreadTest.java b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/patterns/ThreadTest.java new file mode 100644 index 0000000..c3855aa --- /dev/null +++ b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/patterns/ThreadTest.java @@ -0,0 +1,48 @@ +package it.unive.dais.po2.aa2020_21.patterns; + +public class ThreadTest { + + public static void loop() { + for (int i = 0; i < 10; ++i) { + System.out.printf("thread#%d: %d\n", Thread.currentThread().getId(), i); + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + public static class MyThread extends Thread { + + public MyThread() { super(); } + + @Override + public void run() { + loop(); + } + + } + + public static void main(String[] args) { + Thread t1 = new MyThread(); + Thread t2 = new MyThread(); + t1.start(); + t2.start(); + + new Thread(() -> { loop(); }).start(); + + loop(); + + + try { + t1.join(); + t2.join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + + } + +} diff --git a/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/AbstractResizableCollection.java b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/AbstractResizableCollection.java new file mode 100644 index 0000000..54a1c9a --- /dev/null +++ b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/AbstractResizableCollection.java @@ -0,0 +1,51 @@ +package it.unive.dais.po2.aa2020_21.tinyjdk; + +public abstract class AbstractResizableCollection implements Collection { + + protected Object[] a; + protected int actualSize; + + protected void actualAdd(T x) { + if (actualSize >= a.length) { + Object[] newa = new Object[a.length * 2]; + System.arraycopy(a, 0, newa, 0, a.length); + a = newa; + } + a[actualSize++] = x; + } + + + @Override + public boolean contains(T x) { + for (Object o_ : a) { + T o = (T) o_; + if (o.equals(x)) return true; + } + return false; + } + + @Override + public int size() { + return actualSize; + } + + @Override + public void remove(T x) { + assert x != null; + for (int i = 0; i < actualSize; ++i) { + T o = (T) a[i]; + if (o.equals(x)) { + if (actualSize - (i + 1) >= 0) System.arraycopy(a, i + 1, a, i + 1 - 1, actualSize - (i + 1)); + --actualSize; + break; + } + } + } + + @Override + public void removeAll(T x) { + // TODO da fare per casa + } + + +} diff --git a/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/AbstractResizableList.java b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/AbstractResizableList.java new file mode 100644 index 0000000..2bb5cec --- /dev/null +++ b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/AbstractResizableList.java @@ -0,0 +1,32 @@ +package it.unive.dais.po2.aa2020_21.tinyjdk; + +public abstract class AbstractResizableList extends AbstractResizableCollection implements List { + @Override + public T get(int index) { + checkPos(index); + return (T) a[index]; + } + + @Override + public void set(int index, T x) { + checkPos(index); + a[index] = x; + } + + @Override + public void remove(int index) { + if (actualSize - 1 - index >= 0) System.arraycopy(a, index + 1, a, index, actualSize - 1 - index); + --actualSize; + } + + @Override + public void add(int index, T x) { + // TODO da fare per casa + } + + + protected void checkPos(int index) { + if (index < 0 || index >= size()) throw new RuntimeException(String.format("index %d is greater than size %d", index, size())); + } + +} diff --git a/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/ArrayList.java b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/ArrayList.java new file mode 100644 index 0000000..2b75889 --- /dev/null +++ b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/ArrayList.java @@ -0,0 +1,88 @@ +package it.unive.dais.po2.aa2020_21.tinyjdk; + +public class ArrayList extends AbstractResizableList implements List { + + public ArrayList() { + this(0); + } + + public ArrayList(int capacity) { + a = new Object[capacity]; + actualSize = 0; + } + + @Override + public void add(T x) { + actualAdd(x); + } + + @SuppressWarnings("unused") + private static class myStaticIterator implements Iterator { + + private final ArrayList a; + private int pos = 0; + + public myStaticIterator(ArrayList a) { + this.a = a; + } + + @Override + public boolean hasNext() { + return pos < a.size(); + } + + @Override + public E next() { + return a.get(pos++); + } + } + + @SuppressWarnings("unused") + private class myIterator implements Iterator { + + private int pos = 0; + + @Override + public boolean hasNext() { + return pos < ArrayList.this.size(); + } + + @Override + public T next() { + return ArrayList.this.get(pos++); + } + } + + + @Override + public Iterator iterator() { + //return new ArrayListIterator(this); // versione con classe pubblica in un file a sé stante + //return new myStaticIterator(this); // versione con classe nested STATICA: equivalente alla versione con classe pubblica su file + //return new myIterator(); // versione con classe nested NON-STATICA (non servono type arguments) + + // versione con classe ANONIMA + final int zero = 0; // esempio di variabile locale usata dalla classe anonima + return new Iterator<>() { + private int pos = zero; // riferimento ad una variabile nello scope del metodo: la CHIUSURA dell'ambiente consente proprio questo, cioè l'oggetto costruito + // tramite la classe anonima porta con sé un pezzo dello scope in cui è stato definito, a patto che l'accesso alle variabili + // sia solamente in lettura e non le modifichi. Ecco perché devono essere final! + + @Override + public boolean hasNext() { + return pos < ArrayList.this.size(); + } + + @Override + public T next() { + return ArrayList.this.get(pos++); + } + }; + } + + + + + + + +} diff --git a/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/ArrayListIterator.java b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/ArrayListIterator.java new file mode 100644 index 0000000..207d0d4 --- /dev/null +++ b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/ArrayListIterator.java @@ -0,0 +1,22 @@ +package it.unive.dais.po2.aa2020_21.tinyjdk; + +@SuppressWarnings("unused") +public class ArrayListIterator implements Iterator { + + private final ArrayList a; + private int pos = 0; + + public ArrayListIterator(ArrayList a) { + this.a = a; + } + + @Override + public boolean hasNext() { + return pos < a.size(); + } + + @Override + public E next() { + return a.get(pos++); + } +} diff --git a/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/Collection.java b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/Collection.java new file mode 100644 index 0000000..a0d7faf --- /dev/null +++ b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/Collection.java @@ -0,0 +1,9 @@ +package it.unive.dais.po2.aa2020_21.tinyjdk; + +public interface Collection extends Iterable { + void add(T x); + boolean contains(T x); + int size(); + void remove(T x); + void removeAll(T x); +} diff --git a/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/HashMap.java b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/HashMap.java new file mode 100644 index 0000000..d944c9f --- /dev/null +++ b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/HashMap.java @@ -0,0 +1,89 @@ +package it.unive.dais.po2.aa2020_21.tinyjdk; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.LinkedList; + + +public class HashMap implements Map { + + @NotNull + private final ArrayList>> a; + + + public HashMap(int capacity) { + this.a = new ArrayList<>(capacity); + for (int i = 0; i < a.size(); ++i) { + a.set(i, new LinkedList<>()); + } + } + + private int indexOf(@NotNull K key) { + return key.hashCode() % a.size(); + } + + @Override + public void put(@NotNull K key, @Nullable V value) { + int i = indexOf(key); + LinkedList> l = a.get(i); + l.add(new Pair<>(key, value)); + } + + @Override + public @Nullable V get(@NotNull K key) throws KeyNotFoundException { + LinkedList> l = a.get(indexOf(key)); + for (Pair p : l) { + if (p.first.equals(key)) + return p.second; + } + throw new KeyNotFoundException("HashMap.get()"); + } + + @Override + public int size() { + int r = 0; + Iterator>> it = a.iterator(); + while (it.hasNext()) { + LinkedList> l = it.next(); + r += l.size(); + } + return r; + } + + + @Override + public Iterator> iterator() { // TODO da testare + // versione alternativa con lista d'appoggio +// List> r = new ArrayList>(); +// for (LinkedList> l : a) +// for (Pair p : l) +// r.add(p); +// return r.iterator(); + + return new Iterator>() { + private int i = 0, j = 0; + + @Override + public boolean hasNext() { + return i < a.size(); // TODO da pensare se è sufficiente così o se serve j < a.get(i).size() || + } + + @Override + public Pair next() { + LinkedList> p = a.get(i); + Pair r = p.get(j++); + if (j >= p.size()) { + ++i; + j = 0; + } + return r; + } + }; + } + + @Override + public void remove(@NotNull K key) { + + } +} diff --git a/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/IdentitySet.java b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/IdentitySet.java new file mode 100644 index 0000000..b9fcc6d --- /dev/null +++ b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/IdentitySet.java @@ -0,0 +1,15 @@ +package it.unive.dais.po2.aa2020_21.tinyjdk; + +public class IdentitySet extends AbstractResizableCollection implements Set { + + @Override + public void add(T x) { + if (!contains(x)) actualAdd(x); + } + + @Override + public Iterator iterator() { + // TODO rifattorizzare gli iteratori di ArrayList e spostarli in AbstractResizableCollection + throw new RuntimeException(); + } +} diff --git a/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/Iterable.java b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/Iterable.java new file mode 100644 index 0000000..96c9eff --- /dev/null +++ b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/Iterable.java @@ -0,0 +1,5 @@ +package it.unive.dais.po2.aa2020_21.tinyjdk; + +public interface Iterable { + Iterator iterator(); +} diff --git a/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/Iterator.java b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/Iterator.java new file mode 100644 index 0000000..a90052a --- /dev/null +++ b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/Iterator.java @@ -0,0 +1,6 @@ +package it.unive.dais.po2.aa2020_21.tinyjdk; + +public interface Iterator { + boolean hasNext(); + T next(); +} diff --git a/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/List.java b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/List.java new file mode 100644 index 0000000..710f71e --- /dev/null +++ b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/List.java @@ -0,0 +1,8 @@ +package it.unive.dais.po2.aa2020_21.tinyjdk; + +public interface List extends Collection { + T get(int index); + void set(int index, T x); + void remove(int index); + void add(int index, T x); +} diff --git a/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/Main.java b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/Main.java new file mode 100644 index 0000000..c36299f --- /dev/null +++ b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/Main.java @@ -0,0 +1,23 @@ +package it.unive.dais.po2.aa2020_21.tinyjdk; + +import java.util.HashMap; +import java.util.Map; + +public class Main { + + public static void main(String[] args) { + + ArrayList u = new ArrayList<>(); + u.add("ciao"); + u.add("mi"); + u.add("chiamo"); + u.add("Alvise"); + + boolean b = u.contains("chiamo"); + + Map m = new HashMap<>(); + java.util.Set> s = m.entrySet(); + + } + +} diff --git a/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/Map.java b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/Map.java new file mode 100644 index 0000000..ea87878 --- /dev/null +++ b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/Map.java @@ -0,0 +1,24 @@ +package it.unive.dais.po2.aa2020_21.tinyjdk; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public interface Map extends Iterable> { + void put(@NotNull K key, @Nullable V value); + @Nullable V get(@NotNull K key) throws KeyNotFoundException; + int size(); + void remove(@NotNull K key); + + class KeyNotFoundException extends Exception { + public KeyNotFoundException(Object k) { + super(String.format("key = %s", k)); + } + } +} + + + + + + + diff --git a/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/Pair.java b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/Pair.java new file mode 100644 index 0000000..1e42a13 --- /dev/null +++ b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/Pair.java @@ -0,0 +1,20 @@ +package it.unive.dais.po2.aa2020_21.tinyjdk; + +public class Pair { + public final A first; + public final B second; + public Pair(A a, B b) { + first = a; + second = b; + } + + @Override + public boolean equals(Object o) { + if (o instanceof Pair) { + @SuppressWarnings("rawtypes") + Pair p = (Pair) o; + return first.equals(p.first) && second.equals(p.second); + } + return false; + } +} diff --git a/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/PairMap.java b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/PairMap.java new file mode 100644 index 0000000..db05ed5 --- /dev/null +++ b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/PairMap.java @@ -0,0 +1,61 @@ +package it.unive.dais.po2.aa2020_21.tinyjdk; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class PairMap implements Map { + @NotNull + private final ArrayList> a = new ArrayList<>(); + + @Nullable + private Pair> search(@NotNull K key) { + for (int i = 0; i < a.size(); ++i) { + @NotNull final Pair p = a.get(i); + K e = p.first; + if (e.equals(key)) { + return new Pair<>(i, p); + } + } + return null; + } + + @Override + public void put(@NotNull K key, @Nullable V value) { + Pair> r = search(key); + if (r != null) { + a.set(r.first, new Pair<>(r.second.first, value)); + } + else + a.add(new Pair<>(key, value)); + } + + @Override + public V get(@NotNull K key) throws KeyNotFoundException { + Iterator> it = iterator(); // TODO usare search() + while (it.hasNext()) { + Pair p = it.next(); + if (p.first.equals(key)) return p.second; + } + throw new KeyNotFoundException(key); + } + + @Override + public int size() { + return a.size(); + } + + @Override + public void remove(@NotNull K key) { + Pair> r = search(key); + if (r != null) { + a.remove(r.first); + } + } + + @Override + public Iterator> iterator() { + return a.iterator(); + } + + +} diff --git a/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/Set.java b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/Set.java new file mode 100644 index 0000000..9e22ec4 --- /dev/null +++ b/2020-21/Lezioni/src/it/unive/dais/po2/aa2020_21/tinyjdk/Set.java @@ -0,0 +1,4 @@ +package it.unive.dais.po2.aa2020_21.tinyjdk; + +public interface Set extends Collection { +} diff --git a/2020/Lezioni/out/production/Lezioni/META-INF/Lezioni.kotlin_module b/2020/Lezioni/out/production/Lezioni/META-INF/Lezioni.kotlin_module deleted file mode 100644 index 8fb6019..0000000 Binary files a/2020/Lezioni/out/production/Lezioni/META-INF/Lezioni.kotlin_module and /dev/null differ diff --git a/2020/Lezioni/src/it/unive/dais/po2/myjdk/MyHashSet.java b/2020/Lezioni/src/it/unive/dais/po2/myjdk/MyHashSet.java deleted file mode 100644 index 7bafb7f..0000000 --- a/2020/Lezioni/src/it/unive/dais/po2/myjdk/MyHashSet.java +++ /dev/null @@ -1,16 +0,0 @@ -package it.unive.dais.po2.myjdk; - -public class MyHashSet extends MyLinkedSet { - @Override - public void add(T x) { - MyIterator it = iterator(); - boolean found = false; - while (it.hasNext()) { - T e = it.next(); - if (x.hashCode() == e.hashCode()) - found = true; - } - if (!found) - l.add(x); - } -} diff --git a/2020/Lezioni/src/it/unive/dais/po2/myjdk/MyIterable.java b/2020/Lezioni/src/it/unive/dais/po2/myjdk/MyIterable.java deleted file mode 100644 index 5816a3c..0000000 --- a/2020/Lezioni/src/it/unive/dais/po2/myjdk/MyIterable.java +++ /dev/null @@ -1,6 +0,0 @@ -package it.unive.dais.po2.myjdk; - -public interface MyIterable { - - MyIterator iterator(); -} diff --git a/2020/Lezioni/src/it/unive/dais/po2/zoo/Animal.java b/2020/Lezioni/src/it/unive/dais/po2/zoo/Animal.java deleted file mode 100644 index 6656edf..0000000 --- a/2020/Lezioni/src/it/unive/dais/po2/zoo/Animal.java +++ /dev/null @@ -1,19 +0,0 @@ -package it.unive.dais.po2.zoo; - -public class Animal implements Creature { - protected int weight; - protected A partner; - - public Animal(int weight, A p) { - this.weight = weight; - this.partner = p; - } - - public void eat(Animal a) { - this.weight += a.weight; - } - - public A getPartner() { - return partner; - } -} diff --git a/2020/Lezioni/src/it/unive/dais/po2/zoo/ColoredAnimal.java b/2020/Lezioni/src/it/unive/dais/po2/zoo/ColoredAnimal.java deleted file mode 100644 index 103f503..0000000 --- a/2020/Lezioni/src/it/unive/dais/po2/zoo/ColoredAnimal.java +++ /dev/null @@ -1,11 +0,0 @@ -package it.unive.dais.po2.zoo; - -public abstract class ColoredAnimal extends Animal { - protected String color; - - protected ColoredAnimal(int w, String c, A p) { - super(w, p); - this.color = c; - } - -} diff --git a/2020/Lezioni/src/it/unive/dais/po2/zoo/Dog.java b/2020/Lezioni/src/it/unive/dais/po2/zoo/Dog.java deleted file mode 100644 index d7ee84e..0000000 --- a/2020/Lezioni/src/it/unive/dais/po2/zoo/Dog.java +++ /dev/null @@ -1,19 +0,0 @@ -package it.unive.dais.po2.zoo; - -public class Dog extends ColoredAnimal { - - public Dog(int w, String c, Dog p) { - super(w, c, p); - } - - - @Override - public void eat(Animal a) { - weight += a.weight / 2; - } - - - public void bark() { - System.out.println("bau!"); - } -} diff --git a/2020/Lezioni/src/it/unive/dais/po2/zoo/Main.java b/2020/Lezioni/src/it/unive/dais/po2/zoo/Main.java deleted file mode 100644 index 4e4439c..0000000 --- a/2020/Lezioni/src/it/unive/dais/po2/zoo/Main.java +++ /dev/null @@ -1,39 +0,0 @@ -package it.unive.dais.po2.zoo; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; - -public class Main { - - public static void main(String[] args) { - - // TODO: provare a mettere a posto in modo che compili -/* Dog fido = new Dog(15, "bruno"); - Dog baldo = new Dog(20, "bianco"); - Animal jackie = new Dog(2, "nero"); - Dog pluto = new Animal(50); - Animal selene = new Cat(4, "grigio"); - - // sumsumption NON valide - Dog fido2 = selene; - Cat selene2 = selene; - - Cat tigre = new Cat(20); - Animal cane = new Dog(50, tigre); - Animal p = fido.getPartner(); - - selene.eat(fido); - - Animal a = new Persian(6, fido); - a.meow(); // NON COMPILA - a.eat(fido); - - a.eat(a); // mangiare se stessi si può fare -*/ - - } - -} - - diff --git a/2021-22/LezioniCPP21-22/.gitignore b/2021-22/LezioniCPP21-22/.gitignore new file mode 100644 index 0000000..6879d2e --- /dev/null +++ b/2021-22/LezioniCPP21-22/.gitignore @@ -0,0 +1,438 @@ + +# Created by https://www.toptal.com/developers/gitignore/api/visualstudio,c++ +# Edit at https://www.toptal.com/developers/gitignore?templates=visualstudio,c++ + +### C++ ### +# Prerequisites +*.d + +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai +*.la +*.a +*.lib + +# Executables +*.exe +*.out +*.app + +### VisualStudio ### +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.iobj +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml + +### VisualStudio Patch ### +# Additional files built by Visual Studio + +# End of https://www.toptal.com/developers/gitignore/api/visualstudio,c++ diff --git a/2021-22/LezioniCPP21-22/LezioniCPP.vcxproj b/2021-22/LezioniCPP21-22/LezioniCPP.vcxproj new file mode 100644 index 0000000..4ce6405 --- /dev/null +++ b/2021-22/LezioniCPP21-22/LezioniCPP.vcxproj @@ -0,0 +1,157 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 16.0 + Win32Proj + {ce9ed7c4-e77d-4122-952d-8206cbd38868} + LezioniCPP + 10.0 + + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + + + + + + + + + + + + + + + + + + + true + + + false + + + true + + + false + + + + Level3 + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + stdcpp20 + + + Console + true + + + + + Level3 + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + Level4 + true + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + stdcpp20 + + + Console + true + + + + + Level3 + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/2021-22/LezioniCPP21-22/LezioniCPP.vcxproj.filters b/2021-22/LezioniCPP21-22/LezioniCPP.vcxproj.filters new file mode 100644 index 0000000..d0923ce --- /dev/null +++ b/2021-22/LezioniCPP21-22/LezioniCPP.vcxproj.filters @@ -0,0 +1,42 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + + + Header Files + + + \ No newline at end of file diff --git a/2021-22/LezioniCPP21-22/LezioniCPP21-22.sln b/2021-22/LezioniCPP21-22/LezioniCPP21-22.sln new file mode 100644 index 0000000..f4c9044 --- /dev/null +++ b/2021-22/LezioniCPP21-22/LezioniCPP21-22.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.31729.503 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LezioniCPP", "LezioniCPP.vcxproj", "{CE9ED7C4-E77D-4122-952D-8206CBD38868}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {CE9ED7C4-E77D-4122-952D-8206CBD38868}.Debug|x64.ActiveCfg = Debug|x64 + {CE9ED7C4-E77D-4122-952D-8206CBD38868}.Debug|x64.Build.0 = Debug|x64 + {CE9ED7C4-E77D-4122-952D-8206CBD38868}.Debug|x86.ActiveCfg = Debug|Win32 + {CE9ED7C4-E77D-4122-952D-8206CBD38868}.Debug|x86.Build.0 = Debug|Win32 + {CE9ED7C4-E77D-4122-952D-8206CBD38868}.Release|x64.ActiveCfg = Release|x64 + {CE9ED7C4-E77D-4122-952D-8206CBD38868}.Release|x64.Build.0 = Release|x64 + {CE9ED7C4-E77D-4122-952D-8206CBD38868}.Release|x86.ActiveCfg = Release|Win32 + {CE9ED7C4-E77D-4122-952D-8206CBD38868}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {F5305459-C861-4D73-8AF9-786E2D511A45} + EndGlobalSection +EndGlobal diff --git a/2021-22/LezioniCPP21-22/ident.ixx b/2021-22/LezioniCPP21-22/ident.ixx new file mode 100644 index 0000000..63672fc --- /dev/null +++ b/2021-22/LezioniCPP21-22/ident.ixx @@ -0,0 +1,31 @@ +#include + +import pairs; +import sums; + +// da C++11 ALMENO una definizione di ident() deve esistere PRIMA della funzione templatizzata che la usa (questo progetto compila in C++20) +// in C++ vanilla poteva non esisterne neanche una +int ident(int x) { return x; } + + +template +T dual_ident(const T& a) +{ + return ident(ident(a)); // da C++11 i template sono type-checkati debolmente: viene controllato solamente che esista ALMENO una definizione per le funzioni usate internamente + // ma il compilatore non può sapere con quale template argument verrà invocata questa funzione, quindi sospende la compilazione +} + +export int test_ident() +{ + + // ogni singola chiamata ad una funzione templatizzata genera una nuova istanza della funzione in cui viene sostituito il template parameter con il tipo + // concreto usato in quel caso; la funzione viene poi compilata con i tipo completo. + [[maybe_unused]] int x = dual_ident(3); // questa invocazione genera una istanza della funzione dual_ident() con int come template argument + // tale istanza compila perché esiste una definizione di ident() che prende e ritorna int + + //char* s = dual_ident("ciao"); // questa invocazione genera una istanza della funzione dual_ident() con char* come template argument + // ma questa istanza NON compila perché non esiste un overload di ident() che prenda char* + + return 0; +} + diff --git a/2021-22/LezioniCPP21-22/iterators.ixx b/2021-22/LezioniCPP21-22/iterators.ixx new file mode 100644 index 0000000..cd00c00 --- /dev/null +++ b/2021-22/LezioniCPP21-22/iterators.ixx @@ -0,0 +1,107 @@ + +export module iterators; + +import ; +import ; +import ; +import ; +import pairs; +import smart_ptr; + +using namespace std; + + +// questa funzione è templatizzata su un tipo Container QUALUNQUE +// non c'è alcun genere di specifica dei requisiti che questo tipo Container deve rispettare: il nome stesso è totalmente arbitrario +// l'implementazione fa emergere la necessità che questo tipo Container risponda a certi requisiti +template +void increment_all(Container& v) +{ + // la keyword typename indica al compilatore che l'identificatore che segue è un TIPO e non un membro statico + // senza typename il compilatore potrebbe confondere Container::iterator con un campo statico di nome iterator dentro la classe Container + for (typename Container::iterator it = v.begin(); it != v.end(); ++it) // richiede l'esistenza di un member type di nome iterator e dei metodi begin() ed end() + { // inoltre richiede l'operatore di post-incremento sul tipo dell'iteratore + typename Container::reference v = *it; // richiede l'esistenza di un member type di nome reference (di solito è equivalente a value_type&) + ++v; // richiede l'esistenza dell'operatore di pre-incremento per il tipo dell'elemento del container + } +} + +template +void print_all(const Container& v) +{ + cout << typeid(Container).name() << "["; + for (typename Container::const_iterator it = v.begin(); it != v.end(); ++it) // usiamo il const_iterator perché non dobbiamo modificare gli elementi del container + { + cout << *it << ", "; // richiede l'operatore << sul tipo dell'elemento del container + } + cout << "\b\b]" << endl; +} + +using pairs::mypair; + +// definiamo gli operatori di output stream per smart_ptr e mypair +template +ostream& operator<<(ostream& os, const mypair& p) +{ + return os << "(" << p.fst() << ", " << p.snd() << ")"; +} + + +// ridefinisce l'operatore GLOBALE di streaming per il tipo double* stampando sia l'indirizzo che il double puntato +// ATTENZIONE: la sintassi SUFFISSA con il 'const&' DOPO il tipo è una sintassi alternativa: scrivere 'const MioTipo&' e 'MioTipo const&' è esattamente EQUIVALENTE ed indica un const-reference di tipo MioTipo. +// C++ supporta dal vanilla sia la sintassi PREFISSA con il const PRIMA del tipo, sia quella SUFFISSA con il const DOPO il tipo. +// Nel nostro caso però MioTipo è un POINTER e qui emerge un problema sottile: quando il const è PREFISSO esso si riferisce al tipo PUNTATO (cioè double), ma come posso specificare che voglio il PUNTATORE per const? +// In altre parole, voglio prendere per const-reference un puntatore che punta ad un const double: per farlo devo mescolare la sintassi prefissa con quella suffissa e scrivere 'const double* const&'. +// Il motivo per cui voglio questo è perché voglio ridefinire l'operator<< GLOBALE per i double*, quindi devo riprodurre la firma ESATTA originale per assicurarmi che sia una shadowing e non un overload. +// La firma esatta dell'operator<< originale definito dalla standard library è: +// ostream& operator<<(ostream& os, double* p) +// +// Quanti e quali altri modi esistono di scrivere una firma compatibile a quella originale? Tutti i seguenti sono COMPATIBILI quindi sono considerati shadowing: +// double* const& prendo per const-reference (suffisso) un pointer ad un double non-const +// const double* const& prendo per const-reference (suffisso) un pointer ad un double const (prefisso) +// double* const prendo per copia un pointer const (suffisso) ad un double non-const +// const double* const prendo per copia un pointer const (suffisso) ad un double const (prefisso) +// double* prendo per copia un pointer non-const ad un double non-const +// const double* prendo per copia un pointer non-const ad un double const (prefisso) +// +// E quali tipi invece sono NON compatibili e sono considerati overload anziché uno shadowing dal compilatore? +// const double*& prendo per reference un pointer non-const ad un double const (prefisso) +// double*& prendo per reference un pointer non-const ad un double non-const +// +// Per essere compatibili con la firma originale (double*) non importa se il double è const oppure no, quello che importa è che il pointer sia const SE lo prendiamo per reference, poiché se non è una copia esso allora non deve essere modificabile. +// Il significato di tutto questo è: prendere un argomento per valore (cioè per copia) è compatibile, dal punto di vista dei tipi del compilatore, con il prendere per const-reference. +// Non perché siano equivalenti (perché sappiamo che sono cose diverse) ma perché dal punto di vista della const-correctness imposta dal compilatore sono compatibili. +// Il punto è che un argomento passato per copia garantisce la NON MODIFICABILITA' dell'oggetto passato dal chiamante, esattamente come lo garantisce il passarlo per const-reference. +// +// Nel nostro caso usiamo il tipo più sicuro tra quelli equivalenti a double*, cioè const double* const& +// +// ESPERIMENTO: provate a cambiare il tipo del parametro p in const double*& ad esempio, e lanciate il programma di nuovo: vedrete che il printing dei double* sarà quello originale e non quello definito da noi, perché quella qui sotto diventa un overload, non uno shadowing di quella globale. +ostream& operator<<(ostream& os, const double* const& p) +{ + os << "&" << static_cast(p); // castiamo a const void* per stampare l'indirizzo numerico invocando l'operator<< sui void* definito globalmente dalla standard library + // lo static_cast non ha il potere di rimuovere un const, quindi non si può castare a void* semplicemente + // ATTENZIONE: senza cast diventerebbe una chiamata RICORSIVA all'operator<< che noi stessi stiamo definendo + if (p != nullptr) os << "[" << *p << "]"; // se il pointer non è nullo printa anche il dereference + return os; +} + +export void test_iterators() +{ + vector v{ 1, 2, 3, 4 }; + print_all(v); // questa chiamata genera una istanza della funzione print_all() con vector sostituo al template parameter Container + increment_all(v); // questa chiamata genera una istanza della funzione print_all() con vector sostituo al template parameter Container + print_all(v); // questa NON rigenera un'altra istanza della funzione print_all() per vector: per ogni tipo diverso ne viene generata UNA SOLA + + list l1{ "ciao", "sono", "io" }; + print_all(l1); // questa chiamata genera una istanza di print_all() per list + //increment_all(l1); // NON COMPILA: questa chiamata genera una istanza di increment_all() per list, ma il pre-incremento non esiste per string + + double arr[] = { 11.23, 35.53 }; + list> l2{ {1u, arr}, {2u, arr}, {3u, arr} }; + print_all(l2); // questa genera una istanza della print_all() per list> + // essa compila perché abbiamo definito l'operator<< per mypair, altrimenti non compilerebbe + increment_all(l2); // questa compila perché mypair ha l'operatore di pre-incremento, il quale invoca a sua volta il pre-incremento sui due campi della coppia + // pertanto la chiamata compila perché sia unsigned int che double* supportano il pre-incremento + print_all(l2); +} + diff --git a/2021-22/LezioniCPP21-22/main.cpp b/2021-22/LezioniCPP21-22/main.cpp new file mode 100644 index 0000000..9904c94 --- /dev/null +++ b/2021-22/LezioniCPP21-22/main.cpp @@ -0,0 +1,24 @@ +#include +#include + +import pairs; +import sums; +import iterators; +import ; + +using namespace std; + +int main() +{ + try + { + sums::test(); // chiamare il test che si preferisce + return 0; + } + catch (exception& e) + { + cerr << "exception caught: " << e.what() << endl; + return 1; + } +} + diff --git a/2021-22/LezioniCPP21-22/pairs.ixx b/2021-22/LezioniCPP21-22/pairs.ixx new file mode 100644 index 0000000..faa23da --- /dev/null +++ b/2021-22/LezioniCPP21-22/pairs.ixx @@ -0,0 +1,213 @@ +export module pairs; + +import ; +import ; + +// questo namespace ha lo stesso nome del modulo: in C++20 i moduli NON SONO NAMESPACE, quindi i namespace possono essere definiti e posso avere lo stesso nome dei moduli +export namespace pairs +{ + + // utility generale per definire operatori aritmetici di assegnamento in-place (es: +=, -= ecc) tramite una funzione di ordine superiore + // questa funzione non è specifica per mypair ma può definire operatori aritmetici in-place dato un operatore binario qualunque + // in altre parole, essa non ha bisogno di sapere com'è fatta la classe su cui opera: gli è sufficiente conoscere l'operatore artimetico binario e necessita dell'esistenza dell'assegnamento + template + inline This& gen_op_assign(This* this_, const This& x, const Op& op) + { + return *this_ = op(*this_, x); // richiede sia definito definito operator=() + } + + + // classe templatizzata mypair + // + + export + template + class mypair + { + template friend class mypair; // necessario per il conversion copy constructor + + private: + A first; + B second; + + // metodo privato di utility per definire operatori aritmetici tramite funzioni di ordine superiore + // occorre passare i due operatori per i tipi A e B come argomento + template + inline mypair op_bin(const mypair& x, const Op1& op_first, const Op2& op_second) const + { + return mypair(op_first(first, x.first), op_second(second, x.second)); + } + + // metodo privato di utility per definire operatori aritmetici con assegnamento in-place stubbando poly_op_assign() con this come primo argomento + template + inline mypair& op_assign(const mypair& x, const Op& op) + { + return gen_op_assign(this, x, op); + } + + // macro per definire operatori aritmetici facilmente: essa chiama a sua volta l'operatore op sui campi privati della mypair + // questa macro fa una cosa simile a ciò che fa la funzione op_bin(), ma lo fa con una macro anziché con una funzione di ordine superiore + // NOTA: definire una macro dentro una classe non ha un vero motivo: le macro sono entità gestite dal pre-processore e non sono soggette a scoping + // questa macro è definita qui solamente perché a livello logico opera con mypair +# define OP_BIN(op) \ + mypair operator op (const mypair& x) const \ + { \ + return mypair(first op x.first, second op x.second); \ + } + + // macro per definire operatori aritmetici facilmente: essa chiama a sua volta l'operatore op tra this e l'argomento x + // questa macro fa una cosa simile a ciò che fa global_op_assign(), ma lo fa con una macro anziché con una funzione di ordine superiore + // è interessante notare che anche questa macro, come global_op_assign(), non menziona i campi privati +# define OP_ASSIGN(op) \ + mypair& operator op ## =(const mypair& x) \ + { \ + return *this = *this op x; \ + } + + + public: + /////////////////////////////////////////////////////////// + // costruttori + // + + // default constructor: chiama i default constructor dei campi privati, quindi deve esistere un default construtor per i tipi A e B + mypair() : first(), second() {} + + // main constructor: inizializza i campi privati first e second copiando gli argomenti a e b; ovvero invoca i copy constructor di A e B + mypair(const A& a, const B& b) : first(a), second(b) + {} + + // copy constructor: invoca i copy constructor di A e B + mypair(const mypair& p) : first(p.first), second(p.second) + {} + + // conversion copy constructor: richiede l'esistenza di un costruttore di A tramite un argomento di tipo C, e di B tramite un argomento di tipo D + template + mypair(const mypair& p) : first(p.first), second(p.second) + {} + + /////////////////////////////////////////////////////////// + // operatori principali + // + + // assegnamento: richiede che sia definito operator=() per A e B + mypair& operator=(const mypair& p) + { + first = p.first; + second = p.second; + return *this; + } + + // post-incremento: richiede che sia definito l'operatore di post-incremento per A e B + mypair operator++() // ritorna una NUOVA mypair per copia + { + mypair tmp(*this); + first++; + second++; + return tmp; + } + + // pre-incremento: richiede che sia definito l'operatore di pre-incremento per A e B + mypair& operator++(int) // ritorna un reference alla mypair appena incrementata + { + ++first; + ++second; + return *this; + } + + /////////////////////////////////////////////////////////// + // operatori aritmetici implementati in vari modi: direttamente, usando le funzioni di utility e con le macro + // + + // somma implemetata direttamente: richiede l'esistenza dell'operator+() per A e B + mypair operator+(const mypair& p) const + { + return mypair(first + p.first, second + p.second); + } + + // sottrazione usando op_bin(): è sufficiente passare le 2 operazioni di sottrazione binaria come argomenti + mypair operator-(const mypair& p) const + { + return op_bin(p, std::minus(), std::minus()); // passiamo DUE VOLTE l'operazione di sottrazione perché occorre passare quella per A e quella per B + } + + // operator*() e operator/() implementati usando la macro + OP_BIN(*) + OP_BIN(/ ) + + + /////////////////////////////////////////////////////////// + // operatori aritmetici in-place implementati in vari modi: direttamente, usando le funzioni di utility e con le macro + // + + // somma in-place usando op_assign(): è sufficiente passare l'operazione di somma binaria come argomento + mypair& operator+=(const mypair& p) + { + return op_assign(p, std::plus>()); + } + + // sottrazione in-place implementata direttamente: richiede solamente l'esistenza dell'operator=() e dell'operator-() + // questa implementazione non menziona i campi ed è praticamente uguale a quello che fa global_op_assign(), con la differenza che quest'ultima lo fa in modo generale per qualunque operatore binario + mypair& operator-=(const mypair& p) + { + return *this = *this - p; + } + + // operator*=() e operator/=() definiti usando la macro + OP_ASSIGN(*) + OP_ASSIGN(/) + + + /////////////////////////////////////////////////////////// + // metodi di accesso read/write ai campi + // + + const A& fst() const + { + return first; + } + + A& fst() + { + return first; + } + + const B& snd() const + { + return second; + } + + B& snd() + { + return second; + } + + }; + + + using std::string; + + // questa funzione viene esportata quindi gli altri moduli la vedranno; viene chiamata solamente test() e non test_pairs() perché è dentro il namespace pairs + // perciò coloro che la chiameranno da altri moduli dovranno chiamarla pairs::test() + // ATTENZIONE: i moduli non creano namespace automaticamente + export void test() + { + mypair p1(4, 5); + mypair p2(p1); + + mypair p3("ciao", true); + mypair p4(p1); + + p1 = p2; + + int n = p1.fst(); + p1.snd() = p1.snd() * 3; + p4 += p1; // converte implicitamente il RV in un pair tramite un conversion copy-constructor templatizzato + + p4 -= p1; + + } + +} + + diff --git a/2021-22/LezioniCPP21-22/smart_ptr.ixx b/2021-22/LezioniCPP21-22/smart_ptr.ixx new file mode 100644 index 0000000..c6a8323 --- /dev/null +++ b/2021-22/LezioniCPP21-22/smart_ptr.ixx @@ -0,0 +1,124 @@ +export module smart_ptr; + +import ; +import ; + +using namespace std; + +export +template +class smart_ptr +{ +private: + T* pt; + bool is_array; + + using counter_t = unsigned int; // equivalente a scrivere: typedef unsigned int counter_t; + + counter_t* cnt; + + void destroy() + { + if (--(*cnt) == 0) + { + if (is_array) delete pt; + else delete[] pt; + delete cnt; + } + } + +public: + using value_type = T; // equivalente a scrivere: typedef T value_type + + smart_ptr(T* pt_, bool is_array_ = false) : pt(pt_), cnt(new unsigned int(1)), is_array(is_array_) {} + + smart_ptr(size_t len) : smart_ptr(new T[len], len > 1) {} + + smart_ptr(const smart_ptr& p) : pt(p.pt), cnt(p.cnt), is_array(p.is_array) + { + ++(*cnt); + } + + ~smart_ptr() + { + destroy(); + } + + smart_ptr& operator=(const smart_ptr& p) + { + ++(*p.cnt); + destroy(); + pt = p.pt; + cnt = p.cnt; + return *this; + } + + T& operator*() + { + return (*this)[0]; + } + + const T& operator*() const + { + return *pt; + } + + T& operator[](size_t i) + { + return pt[i]; + } + + const T& operator[](size_t i) const + { + return pt[i]; + } + + T* operator->() + { + return pt; + } + + const T* operator->() const + { + return pt; + } + + // TODO STUDENTI: implementare operatori +, ++, +=, -, --, -= + // ATTENZIONE: spostare il pointer interno quando si incrementa/decrementa/ecc non è sufficiente, altrimenti la delete verrà invocata su un indirizzo sbagliato. + // consiglio1: l'aritmetica dei puntatori ha senso supportarla solamente quando is_array è true. + // consiglio2: tenere una copia del pointer ORIGINALE passato al costruttore che poi useremo per la delete; e spostare in avanti/indietro una copia messa in un altro campo. +}; + + +// questa funzione templatizzata swappa cose qualunque, a patto che siano de-referenziabili e che il tipo del valore puntato sia assegnabile +template +void swap_any_pointer(Pointer& p1, Pointer& p2) +{ + typename Pointer::value_type& tmp = *p1; // richiede anche l'esistenza di un member type di nome value_type che indichi il tipo del valore puntato + *p1 = *p2; + *p2 = tmp; +} + +export void test() +{ + int* a = new int[100]; + smart_ptr a2(a, true); // ora l'array puntato da a è di proprietà dello smart_ptr, quindi non servirà fare 'delete[] a' + smart_ptr b(600); // utilizza il costruttore che costruisce più di un istanza dello heap + b[2] = a[3]; // supportano l'operatore di subscript + + string* s1 = new string("ciao"); + smart_ptr s2 = s1; + s2 = s1; // questo assegnamento converte automaticamente il right value di tipo string* in un temporary object di tipo smart_ptr + s2 = s2; // supporta anche l'assegnamento di sé stesso + + smart_ptr> v1(new vector(10, 1.)); + smart_ptr> v2(new vector(20, 2.)); + swap_any_pointer(v1, v2); + + int u = 3, w = 4; + //swap_any_pointer(&u, &w); // NON COMPILA perché int* non ha un member type di nome value_type come richiesto dalla funzione templatizzata + +} + + + diff --git a/2021-22/LezioniCPP21-22/sums.ixx b/2021-22/LezioniCPP21-22/sums.ixx new file mode 100644 index 0000000..a4f4b24 --- /dev/null +++ b/2021-22/LezioniCPP21-22/sums.ixx @@ -0,0 +1,73 @@ +export module sums; + +import ; +import ; +import ; +import ; +import ; +import ; +import ; +import ; + + +export namespace sums +{ + // sum con operazione di somma binaria passata come argomento + template + std::iterator_traits::value_type sum(InputIterator first, + InputIterator last, + BinaryFunction f) + { + typename std::iterator_traits::value_type z = *first++; + while (first != last) + { + z = f(z, *first++); + } + return z; + } + + // sum che richiede l'operatore += implementata tramite template classici + template + auto sum(InputIterator first, InputIterator last) -> std::remove_reference_t + { + auto z = *first++; + static_assert(std::is_same_v, decltype(z)>); + while (first != last) + { + z += *first++; + } + return z; + } + + // sum con concept + // + + template + concept MyAddable = requires (T x, T y) { x += y; }; + + template + requires MyAddable::value_type> + auto sum_with_concepts(I first, I last) + { + return sum(first, last); + } + + + export void test() + { + std::vector v = { 1, 2, 3, 4 }; + std::for_each(std::begin(v), std::end(v), [](const auto& x) { std::cout << x << ", "; }); + std::cout << std::endl; + + double arr[5] = { 1.1, 2.2, 3.3, 4.4 }; + + std::cout << "sum con lambda = " << sum(v.begin(), v.end(), [](const auto& a, const auto& b) { return a + b; }) << std::endl; + + std::cout << "sum vector = " << sum(v.begin(), v.end()) << std::endl; + std::cout << "sum array = " << sum(arr, arr + std::size(arr)) << std::endl; + + std::cout << "sum_with_concepts vector = " << sum_with_concepts(v.begin(), v.end()) << std::endl; + std::cout << "sum_with_concepts array = " << sum_with_concepts(arr, arr + std::size(arr)) << std::endl; + } + +} \ No newline at end of file diff --git a/2021-22/LezioniJava21-22/.idea/.gitignore b/2021-22/LezioniJava21-22/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/2021-22/LezioniJava21-22/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/2021-22/LezioniJava21-22/.idea/.name b/2021-22/LezioniJava21-22/.idea/.name new file mode 100644 index 0000000..66b3bb8 --- /dev/null +++ b/2021-22/LezioniJava21-22/.idea/.name @@ -0,0 +1 @@ +Lezioni21-22.iml \ No newline at end of file diff --git a/2021-22/LezioniJava21-22/.idea/codeStyles/codeStyleConfig.xml b/2021-22/LezioniJava21-22/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 0000000..a55e7a1 --- /dev/null +++ b/2021-22/LezioniJava21-22/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/2021-22/LezioniJava21-22/.idea/misc.xml b/2021-22/LezioniJava21-22/.idea/misc.xml new file mode 100644 index 0000000..c3dfb30 --- /dev/null +++ b/2021-22/LezioniJava21-22/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/2021-22/LezioniJava21-22/.idea/modules.xml b/2021-22/LezioniJava21-22/.idea/modules.xml new file mode 100644 index 0000000..97cb713 --- /dev/null +++ b/2021-22/LezioniJava21-22/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/2021-22/LezioniJava21-22/.idea/uiDesigner.xml b/2021-22/LezioniJava21-22/.idea/uiDesigner.xml new file mode 100644 index 0000000..e96534f --- /dev/null +++ b/2021-22/LezioniJava21-22/.idea/uiDesigner.xml @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/2021-22/LezioniJava21-22/.idea/vcs.xml b/2021-22/LezioniJava21-22/.idea/vcs.xml new file mode 100644 index 0000000..b2bdec2 --- /dev/null +++ b/2021-22/LezioniJava21-22/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/2020/Lezioni/Lezioni.iml b/2021-22/LezioniJava21-22/Lezioni21-22.iml similarity index 93% rename from 2020/Lezioni/Lezioni.iml rename to 2021-22/LezioniJava21-22/Lezioni21-22.iml index 1a7f0f7..0181b11 100644 --- a/2020/Lezioni/Lezioni.iml +++ b/2021-22/LezioniJava21-22/Lezioni21-22.iml @@ -10,7 +10,7 @@ - + diff --git a/2021-22/LezioniJava21-22/src/CollectionSample.java b/2021-22/LezioniJava21-22/src/CollectionSample.java new file mode 100644 index 0000000..182dc73 --- /dev/null +++ b/2021-22/LezioniJava21-22/src/CollectionSample.java @@ -0,0 +1,106 @@ +import java.util.*; + +public class CollectionSample { + + public static class RandomSequence implements Iterable { + + private final int sz; + + public RandomSequence(int sz) { + this.sz = sz; + } + + private static class myIterator implements Iterator { + private int cnt = 0; + private Random rnd = new Random(1123); + private RandomSequence that; + + private myIterator(RandomSequence that) { + this.that = that; + } + + @Override + public boolean hasNext() { + return this.cnt < that.sz; + } + + @Override + public Integer next() { + ++cnt; + return rnd.nextInt(); + } + } + + @Override + public Iterator iterator() { + return new myIterator(this); + } + +// @Override + public Iterator iterator__() { + return new Iterator() { + private int cnt = 0; + private Random rnd = new Random(1123); + + @Override + public boolean hasNext() { + return cnt < sz; + } + + @Override + public Integer next() { + ++cnt; + return rnd.nextInt(); + } + }; + } + } + + public interface I { + void m(); + int p(int x); + } + + public static class C implements I { + @Override + public void m() { + System.out.println("ciao"); + } + + @Override + public int p(int x) { + return x * 2; + } + } + + public static void main(String[] args) { + + I y = new C(); + + I x = new I() { + + @Override + public void m() { + System.out.println("ciao"); + } + + @Override + public int p(int x) { + return x * 2; + } + }; + + for (int n : new RandomSequence(80)) { + System.out.println(n); + } + + RandomSequence o = new RandomSequence(80); + Iterator it = o.iterator(); + while (it.hasNext()) { + int n = it.next(); + System.out.println(n); + } + + } + +} diff --git a/2021-22/LezioniJava21-22/src/ConsumerProducer.java b/2021-22/LezioniJava21-22/src/ConsumerProducer.java new file mode 100644 index 0000000..2dc2cbc --- /dev/null +++ b/2021-22/LezioniJava21-22/src/ConsumerProducer.java @@ -0,0 +1,64 @@ +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +public class ConsumerProducer { + + public static Random rand = new Random(); + + public static List q = new ArrayList<>(); + + public static class Producer extends Thread { + + @Override + public void run() { + while (true) { + try { + Thread.sleep(rand.nextLong(100L)); + + synchronized (q) { // LOCK + q.add(rand.nextInt(100)); + q.notify(); + } // UNLOCK + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } + + public static class Consumer extends Thread { + @Override + public void run() { + while (true) { + synchronized (q) { // LOCK + if (q.isEmpty()) { + try { + q.wait(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + int n = q.remove(0); + System.out.printf("consumed: %d (size = %d)\n", n, q.size()); + } // UNLOCK + } + } + } + + public static void main(String[] args) { + Producer p1 = new Producer(); + Producer p2 = new Producer(); + Consumer c1 = new Consumer(); + Consumer c2 = new Consumer(); + p1.start(); + p2.start(); + c1.start(); + c2.start(); + + try { + p1.join(); + } catch (InterruptedException e) {} + } + +} diff --git a/2021-22/LezioniJava21-22/src/Functional.java b/2021-22/LezioniJava21-22/src/Functional.java new file mode 100644 index 0000000..25226fb --- /dev/null +++ b/2021-22/LezioniJava21-22/src/Functional.java @@ -0,0 +1,108 @@ +import java.util.*; +import java.util.function.BiFunction; + +public class Functional { + + public interface Function { + B apply(A x); + } + + public interface Consumer { + void accept(T x); + } + + public interface Supplier { + T get(); + } + + public interface Runnable { + void run(); + } + + public static T sum(Iterator it, BiFunction f) { + T z = it.next(); + while (it.hasNext()) { + z = f.apply(z, it.next()); + } + return z; + } + + + + public static Collection map(Collection c, Function f) { + Collection r = new ArrayList<>(); + for (A x : c) + r.add(f.apply(x)); + return r; + } + + public static void foreach(Collection c, Consumer f) { + for (T x : c) + f.accept(x); + } + + public static Collection generate(int len, Supplier f) { + Collection r = new ArrayList<>(); + for (; len > 0; --len) + r.add(f.get()); + return r; + } + + public static void main(String[] args) { + List l = List.of("ciao", "come", "ti", "chiami?"); + + // test map + Collection r = map(l, (String s) -> s.length()); + Collection r2 = map(l, new Function() { + @Override + public Integer apply(String x) { + return x.length(); + } + }); + System.out.println(r); + System.out.println(r2); + + // test foreach + foreach(l, (String s) -> System.out.println(s)); + + // test generate + Collection g1 = generate(10, () -> 7); + System.out.println(g1); + Random rand = new Random(); + Collection g2 = generate(10, () -> rand.nextInt(100)); + Collection g3 = generate(10, new Supplier() { + @Override + public Integer get() { + return rand.nextInt(100); + } + }); + Collection g4 = generate(10, new MySupplier(rand)); + System.out.println(g2); + System.out.println(g3); + System.out.println(g4); + + // runnable + Runnable run1 = () -> System.out.println("ciao"); + Runnable run2 = new Runnable() { + @Override + public void run() { + System.out.println("ciao"); + } + }; + } + + static class MySupplier implements Supplier { + + private final Random rand; + + public MySupplier(Random rand) { + this.rand = rand; + } + + @Override + public Integer get() { + return rand.nextInt(100); + } + } + +} diff --git a/2021-22/LezioniJava21-22/src/Generics.java b/2021-22/LezioniJava21-22/src/Generics.java new file mode 100644 index 0000000..116b06c --- /dev/null +++ b/2021-22/LezioniJava21-22/src/Generics.java @@ -0,0 +1,61 @@ +public class Generics { + + + public static class FloatPair { + private float a, b; + + public FloatPair(float a, float b) { + this.a = a; + this.b = b; + } + + public float getFirst() { return a; } + public float getSecond() { return b; } + + public void setFirst(float a) { + this.a = a; + } + public void setSecond(float b) { + this.b = b; + } + + } + + public static class Pair { + private A a; + private B b; + + public Pair(A a, B b) { + this.a = a; + this.b = b; + } + + public A getFirst() { return a; } + public B getSecond() { return b; } + + public void setFirst(A a) { + this.a = a; + } + public void setSecond(B b) { + this.b = b; + } + + } + + public static int f(int x) { + return x + 1; + } + + + public static void main(String[] args) { + FloatPair p1 = new FloatPair(23.11f, 67.69f); + Pair p2 = new Pair<>(23.11f, 67.69f); + Pair p3 = new Pair<>("ciao", new Zoo.Dog(10)); + Pair, Pair> p4 = new Pair<>(new Pair<>(1, 2), new Pair<>(5, 6)); + Pair p5 = new Pair<>("ciao", new Zoo.Labrador(10)); + + } + + + +} diff --git a/2021-22/LezioniJava21-22/src/Iterators.java b/2021-22/LezioniJava21-22/src/Iterators.java new file mode 100644 index 0000000..b9f8fc3 --- /dev/null +++ b/2021-22/LezioniJava21-22/src/Iterators.java @@ -0,0 +1,51 @@ +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; + +public class Iterators { + + public static class BackwardsArrayList extends ArrayList { + + public Iterator originalIterator() { + return super.iterator(); + } + + @Override + public Iterator iterator() { + return new Iterator() { + private int index = BackwardsArrayList.this.size() - 1; + @Override + public boolean hasNext() { + return index >= 0; + } + + @Override + public T next() { + return BackwardsArrayList.this.get(index--); + } + }; + } + + public static Iterator reverseIterator(Iterator it) { + List buff = new ArrayList<>(); + while (it.hasNext()) buff.add(0, it.next()); + return buff.iterator(); + } + + } + + public static void main(String[] args) { + Collection l = new BackwardsArrayList<>(); + for (int i = 0; i < 20; l.add(i++)); + + Iterator it = l.iterator(); + while (it.hasNext()) + System.out.println(it.next()); + + /*Iterator it2 = l.originalIterator(); + while (it2.hasNext()) + System.out.println(it2.next()); + */ + } +} diff --git a/2021-22/LezioniJava21-22/src/Sorting.java b/2021-22/LezioniJava21-22/src/Sorting.java new file mode 100644 index 0000000..b241e78 --- /dev/null +++ b/2021-22/LezioniJava21-22/src/Sorting.java @@ -0,0 +1,136 @@ +import java.util.*; +import java.util.function.Function; + +public class Sorting { + + public static class Humanoid implements Comparable { + protected int health; + + public Humanoid(int h) { + health = h; + } + + @Override + public int compareTo(Humanoid o) { + return health - o.health; + } + + @Override + public String toString() { + return String.format("Humanoid[health=%d]", health); + } + } + + public static class Elf extends Humanoid { + private int mana; + + public Elf(int health, int mana) { + super(health); + this.mana = mana; + } + + @Override + public int compareTo(Humanoid o) { + if (o instanceof Elf) { + Elf e = (Elf) o; + return mana - e.mana; + } + return super.compareTo(o); + } + + @Override + public String toString() { + return String.format("Elf[health=%d;mana=%d]", health, mana); + } + + } + + public static class Creature { + } + + public static class Animal extends Creature { + protected int weight; + + public Animal(int w) { + weight = w; + } + + public void eat(Animal a) { + } + + public Animal spawn() { + return new Animal(weight / 3); + } + } + + public static class Dog extends Animal { + private int tail; + + public Dog(int w, int tail) { + super(w); + this.tail = tail; + } + + public void bark() { + } + + @Override + public void eat(Animal a) { + } + + @Override + public Dog spawn() { + return new Dog(weight / 2, 1); + } + } + + static class MyComparator implements Comparator { + @Override + public int compare(Animal o1, Animal o2) { + return o1.weight - o2.weight; + } + } + + public static void main(String[] args) { + Random rand = new Random(); + { + List a = new ArrayList<>(); + for (int i = 0; i < 10; ++i) + a.add(new Dog(i * 10, i)); + + // non-anonymous class + sort(a, new MyComparator()); + // anonymous class + sort(a, new Comparator() { + @Override + public int compare(Animal o1, Animal o2) { + return o1.weight - o2.weight; + } + }); + // lambda che si converte in una anonymous class + sort(a, (o1, o2) -> o1.weight - o2.weight); + } + + { + List l = new ArrayList<>(); + for (int i = 0; i < 10; ++i) { +// if (rand.nextBoolean()) + l.add(new Elf(rand.nextInt(100), rand.nextInt(50))); + // else + // l.add(new Humanoid(rand.nextInt(100))); + } + + System.out.println(l); + sort(l); + System.out.println(l); + } + } + + public static > void sort(List l) { + Collections.sort(l); + } + + public static void sort(List l, Comparator c) { + Collections.sort(l, c); + } +} diff --git a/2021-22/LezioniJava21-22/src/Threading.java b/2021-22/LezioniJava21-22/src/Threading.java new file mode 100644 index 0000000..ff44159 --- /dev/null +++ b/2021-22/LezioniJava21-22/src/Threading.java @@ -0,0 +1,39 @@ +import java.util.Random; + +public class Threading { + + private static Random rand = new Random(); + + private static void doSomething() { + long ms = rand.nextLong(500L); + Thread self = Thread.currentThread(); + for (int i = 0; i < 20; ++i) { + System.out.printf("%s[%d] #%d\n", self.getName(), self.getId(), i); + try { + Thread.sleep(ms); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + + public static void main(String[] args) { + + Thread t1 = new Thread(() -> { + doSomething(); + }); + t1.start(); + + doSomething(); + + try { + t1.join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + } + + +} diff --git a/2021-22/LezioniJava21-22/src/Zoo.java b/2021-22/LezioniJava21-22/src/Zoo.java new file mode 100644 index 0000000..383ffcb --- /dev/null +++ b/2021-22/LezioniJava21-22/src/Zoo.java @@ -0,0 +1,60 @@ +public class Zoo { + + private int x; + private static float y = Zoo.z; + public static float z; + + protected void m() { + this.x = 8; + } + public static void n() { + Zoo.y = 8; + } + + private class Boo {} + + public static class Animal { + protected int peso; + public Animal(int peso) { + this.peso = peso; + } + public void eat(Animal a) { + this.peso += a.peso; + } + } + + public static class Dog extends Animal { + + public Dog(int peso) { + super(peso); + } + + @Override + public void eat(Animal a) { + this.peso += a.peso / 2; + } + } + + public static class Labrador extends Dog { + + public Labrador(int peso) { + super(peso); + } + + @Override + public void eat(Animal a) { + this.peso += a.peso * 2; + } + + public void drool() {} + + } + + public static void main(String[] args) { + Animal a = new Labrador(15); + a.eat(new Dog(10)); + + } + + +} diff --git a/2021-22/LezioniJava21-22/src/tinyjdk/ArrayList.java b/2021-22/LezioniJava21-22/src/tinyjdk/ArrayList.java new file mode 100644 index 0000000..7715b06 --- /dev/null +++ b/2021-22/LezioniJava21-22/src/tinyjdk/ArrayList.java @@ -0,0 +1,89 @@ +package tinyjdk; + +import java.util.Arrays; + +public class ArrayList implements List { + private Object[] a; + private int actualLen; + private static final int DEFAULT_CAPACITY = 10; + + public ArrayList() { + this(DEFAULT_CAPACITY); + } + + public ArrayList(int capacity) { + assert capacity > 0; + a = new Object[capacity]; + actualLen = 0; + } + + @Override + public void add(T e) { + if (actualLen >= a.length) + a = Arrays.copyOf(a, a.length * 2); + a[actualLen++] = e; + } + + @Override + public int indexOf(T e) throws NotFoundException { + for (int i = 0; i < actualLen; ++i) + if (a[i].equals(e)) + return i; + throw new NotFoundException(); + } + + @Override + public void remove(T e) throws NotFoundException { + int i = indexOf(e); + for (int j = i; j < size() - 1; ++j) + a[j] = a[j + 1]; + --actualLen; + } + +/* @Override + public boolean contains(T e) { + try { + indexOf(e); + return true; + } catch (NotFoundException ex) { + return false; + } + }*/ + + @Override + public void clear() { + a = new Object[actualLen + 1]; + } + + @Override + public int size() { + return actualLen; + } + + @Override + public Iterator iterator() { + return new Iterator() { + private int pos = 0; + + @Override + public boolean hasNext() { + return pos < actualLen; + } + + @Override + public T next() { + return (T) a[pos++]; + } + }; + } + + @Override + public T get(int i) { + return (T) a[i]; + } + + @Override + public void set(int i, T e) { + a[i] = e; + } +} diff --git a/2021-22/LezioniJava21-22/src/tinyjdk/Collection.java b/2021-22/LezioniJava21-22/src/tinyjdk/Collection.java new file mode 100644 index 0000000..8dd55b0 --- /dev/null +++ b/2021-22/LezioniJava21-22/src/tinyjdk/Collection.java @@ -0,0 +1,9 @@ +package tinyjdk; + +public interface Collection extends Iterable { + void add(X e); + void remove(X e) throws NotFoundException; + boolean contains(X e); + void clear(); + int size(); +} diff --git a/2021-22/LezioniJava21-22/src/tinyjdk/IntPair.java b/2021-22/LezioniJava21-22/src/tinyjdk/IntPair.java new file mode 100644 index 0000000..47e007c --- /dev/null +++ b/2021-22/LezioniJava21-22/src/tinyjdk/IntPair.java @@ -0,0 +1,15 @@ +package tinyjdk; + +public class IntPair implements Comparable { + public final int first, second; + + public IntPair(int a, int b) { + first = a; + second = b; + } + + @Override + public int compareTo(IntPair o) { + return first * o.first - second * o.second; + } +} diff --git a/2021-22/LezioniJava21-22/src/tinyjdk/Iterable.java b/2021-22/LezioniJava21-22/src/tinyjdk/Iterable.java new file mode 100644 index 0000000..c06c058 --- /dev/null +++ b/2021-22/LezioniJava21-22/src/tinyjdk/Iterable.java @@ -0,0 +1,5 @@ +package tinyjdk; + +public interface Iterable { + Iterator iterator(); +} \ No newline at end of file diff --git a/2021-22/LezioniJava21-22/src/tinyjdk/Iterator.java b/2021-22/LezioniJava21-22/src/tinyjdk/Iterator.java new file mode 100644 index 0000000..3f1efd3 --- /dev/null +++ b/2021-22/LezioniJava21-22/src/tinyjdk/Iterator.java @@ -0,0 +1,6 @@ +package tinyjdk; + +public interface Iterator { + boolean hasNext(); + T next(); +} diff --git a/2021-22/LezioniJava21-22/src/tinyjdk/LinkedList.java b/2021-22/LezioniJava21-22/src/tinyjdk/LinkedList.java new file mode 100644 index 0000000..c77933d --- /dev/null +++ b/2021-22/LezioniJava21-22/src/tinyjdk/LinkedList.java @@ -0,0 +1,109 @@ +package tinyjdk; + +public class LinkedList implements List { + + protected Node head = null, tail = null; + protected int len = 0; + + protected static class Node { + public X data; + public Node next; + + protected Node(X data, Node next) { + this.data = data; + this.next = next; + } + } + + @Override + public void add(T e) { + Node n = new Node<>(e, null); + if (tail != null) { + tail.next = n; + tail = n; + } + else + head = tail = n; + ++len; + } + + // TODO: da testare + @Override + public void remove(T e) throws NotFoundException { + Node prev = null, n = head; + while (n != null) { + if (n.data.equals(e)) { + if (prev != null) + prev.next = n.next; + else + head = n.next; + if (n.next == null) + tail = prev; + return; + } + prev = n; + n = n.next; + } + throw new NotFoundException(); + } + + @Override + public void clear() { + head = tail = null; + len = 0; + } + + @Override + public int size() { + return len; + } + + @Override + public Iterator iterator() { + return new Iterator() { + private Node n = head; + + @Override + public boolean hasNext() { + return n.next != null; + } + + @Override + public T next() { + T r = n.data; + n = n.next; + return r; + } + }; + } + + protected Node nodeAt(int pos) { + assert (pos < size()); + Node n = head; + for (; pos > 0; --pos) + n = n.next; + return n; + } + + @Override + public T get(int pos) { + return nodeAt(pos).data; + } + + @Override + public void set(int pos, T e) { + nodeAt(pos).data = e; + } + + @Override + public int indexOf(T e) throws NotFoundException { + Node n = head; + for (int pos = 0; n != null; ++pos) { + if (n.data.equals(e)) { + return pos; + } + n = n.next; + } + throw new NotFoundException(); + } +} diff --git a/2021-22/LezioniJava21-22/src/tinyjdk/List.java b/2021-22/LezioniJava21-22/src/tinyjdk/List.java new file mode 100644 index 0000000..0f03707 --- /dev/null +++ b/2021-22/LezioniJava21-22/src/tinyjdk/List.java @@ -0,0 +1,17 @@ +package tinyjdk; + +public interface List extends Collection { + X get(int pos); + void set(int pos, X e); + int indexOf(X e) throws NotFoundException; + + default boolean contains(X e) { + try { + indexOf(e); + return true; + } catch (NotFoundException ex) { + return false; + } + } +} + diff --git a/2021-22/LezioniJava21-22/src/tinyjdk/Map.java b/2021-22/LezioniJava21-22/src/tinyjdk/Map.java new file mode 100644 index 0000000..8fb0da4 --- /dev/null +++ b/2021-22/LezioniJava21-22/src/tinyjdk/Map.java @@ -0,0 +1,10 @@ +package tinyjdk; + +public interface Map extends Iterable> { + V get(K key); + V put(K key, V value); + void clear(); + boolean containsKey(K key); + boolean containsValue(V value); + void remove(K key) throws NotFoundException; +} diff --git a/2021-22/LezioniJava21-22/src/tinyjdk/Mapping.java b/2021-22/LezioniJava21-22/src/tinyjdk/Mapping.java new file mode 100644 index 0000000..7dd5207 --- /dev/null +++ b/2021-22/LezioniJava21-22/src/tinyjdk/Mapping.java @@ -0,0 +1,73 @@ +package tinyjdk; + +import java.util.function.Function; +import java.util.List; +import java.util.Iterator; +import java.util.function.Supplier; + +public class Mapping { + + + public static Iterator mapIterator(Iterator it, Function f) { + return new Iterator() { + @Override + public boolean hasNext() { + return it.hasNext(); + } + + @Override + public B next() { + return f.apply(it.next()); + } + }; + } + + public static Iterator> mapIterator__mt(Iterator it, Function f) { + return new Iterator<>() { + @Override + public boolean hasNext() { + return it.hasNext(); + } + + @Override + public Supplier next() { + A a = it.next(); + final B[] b = (B[]) new Object[1]; + Thread t = new Thread(() -> { + b[0] = f.apply(a); + }); + t.start(); + return () -> { + try { + t.join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return b[0]; + }; + } + }; + } + + + public static void main(String[] args) { + List l = List.of(1, 2, 3, 4, 5); + Iterator it1 = mapIterator(l.iterator(), (n) -> String.format("%d", n)); + + Iterator> it2 = mapIterator__mt(l.iterator(), (n) -> { + try { + Thread.sleep(1000L); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return String.format("%d", n); + }); + + while(it2.hasNext()) { + Supplier sup = it2.next(); + System.out.println(sup.get()); + } + } + + +} diff --git a/2021-22/LezioniJava21-22/src/tinyjdk/NotFoundException.java b/2021-22/LezioniJava21-22/src/tinyjdk/NotFoundException.java new file mode 100644 index 0000000..9146323 --- /dev/null +++ b/2021-22/LezioniJava21-22/src/tinyjdk/NotFoundException.java @@ -0,0 +1,5 @@ +package tinyjdk; + +public class NotFoundException extends Exception { + +} diff --git a/2021-22/LezioniJava21-22/src/tinyjdk/Pair.java b/2021-22/LezioniJava21-22/src/tinyjdk/Pair.java new file mode 100644 index 0000000..3340009 --- /dev/null +++ b/2021-22/LezioniJava21-22/src/tinyjdk/Pair.java @@ -0,0 +1,24 @@ +package tinyjdk; + +public class Pair { + private A a; + private B b; + + public Pair(A a, B b) { + this.a = a; + this.b = b; + } + + public A getFirst() { return a; } + public B getSecond() { return b; } + + public void setFirst(A a) { + this.a = a; + } + public void setSecond(B b) { + this.b = b; + } + +} + + diff --git a/2021-22/LezioniJava21-22/src/tinyjdk/PairMap.java b/2021-22/LezioniJava21-22/src/tinyjdk/PairMap.java new file mode 100644 index 0000000..d8321d3 --- /dev/null +++ b/2021-22/LezioniJava21-22/src/tinyjdk/PairMap.java @@ -0,0 +1,69 @@ +package tinyjdk; + +public class PairMap implements Map { + private List> l; + + public PairMap() { + l = new ArrayList<>(); + } + + @Override + public Iterator> iterator() { + return l.iterator(); + } + + @Override + public V get(K key) { + Pair p = find(key); + if (p != null) return p.getSecond(); + return null; + } + + private Pair find(K key) { + Iterator> it = this.iterator(); + while (it.hasNext()) { + Pair p = it.next(); + if (p.getFirst().equals(key)) + return p; + } + return null; + } + + @Override + public V put(K key, V value) { + Pair p = find(key); + if (p != null) { + V r = p.getSecond(); + p.setSecond(value); + return r; + } + l.add(new Pair<>(key, value)); + return null; + } + + @Override + public void clear() { + l.clear(); + } + + @Override + public boolean containsKey(K key) { + return find(key) != null; + } + + @Override + public boolean containsValue(V value) { + Iterator> it = this.iterator(); + while (it.hasNext()) { + Pair p = it.next(); + if (p.getSecond().equals(value)) + return true; + } + return false; + } + + @Override + public void remove(K key) throws NotFoundException { + l.remove(find(key)); + } +} diff --git a/2021-22/LezioniJava21-22/src/tinyjdk/SimpleSortedSet.java b/2021-22/LezioniJava21-22/src/tinyjdk/SimpleSortedSet.java new file mode 100644 index 0000000..231b784 --- /dev/null +++ b/2021-22/LezioniJava21-22/src/tinyjdk/SimpleSortedSet.java @@ -0,0 +1,45 @@ +package tinyjdk; + +import java.util.List; +import java.util.ArrayList; +import java.util.Collections; + + +public class SimpleSortedSet> implements SortedSet { + private List l = new ArrayList<>(); + + @Override + public void add(T e) { + if (!contains(e)) { + l.add(e); + Collections.sort(l); + } + } + + // TODO: implementare questi metodi + + @Override + public void remove(T e) throws NotFoundException { + + } + + @Override + public boolean contains(T e) { + return false; + } + + @Override + public void clear() { + + } + + @Override + public int size() { + return l.size(); + } + + @Override + public Iterator iterator() { + throw new RuntimeException("not implemented"); + } +} diff --git a/2021-22/LezioniJava21-22/src/tinyjdk/SortedSet.java b/2021-22/LezioniJava21-22/src/tinyjdk/SortedSet.java new file mode 100644 index 0000000..5c922bd --- /dev/null +++ b/2021-22/LezioniJava21-22/src/tinyjdk/SortedSet.java @@ -0,0 +1,5 @@ +package tinyjdk; + +public interface SortedSet> extends Collection { + +} diff --git a/2021-22/LezioniJava21-22/src/tinyjdk/ThreadPool.java b/2021-22/LezioniJava21-22/src/tinyjdk/ThreadPool.java new file mode 100644 index 0000000..092b257 --- /dev/null +++ b/2021-22/LezioniJava21-22/src/tinyjdk/ThreadPool.java @@ -0,0 +1,70 @@ +package tinyjdk; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Queue; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; + +public class ThreadPool { + + private BlockingQueue q = new LinkedBlockingQueue<>(); + + public class PooledThread extends Thread { + + @Nullable + private Runnable myRunnable; + + @Override + public void run() { + while (true) { + try { + wait(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + if (myRunnable != null) { + myRunnable.run(); + q.add(this); + } + } + } + + private void setRunnable(@NotNull Runnable r) { + myRunnable = r; + notify(); + } + } + + public ThreadPool(int capacity) { + for (int i = 0; i < capacity; ++i) { + PooledThread t = new PooledThread(); + t.start(); + q.add(t); + } + } + + public PooledThread acquire(Runnable r) throws InterruptedException { + PooledThread t = q.take(); + // TODO: spawnare thread nuovi se la coda è vuota + t.setRunnable(r); + return t; + // TODO: scorrere la pool e buttare via thread in eccesso se non usati + } + + + + + public static void main(String[] args) { + try { + ThreadPool pool = new ThreadPool(20); + PooledThread t1 = pool.acquire(() -> { for (int i = 0; i < 10; ++i) System.out.println(i); }); + + PooledThread t2 = pool.acquire(() -> { for (int i = 0; i < 100; ++i) System.out.println(i); }); + + } catch (InterruptedException e) { + e.printStackTrace(); + } + } +} diff --git a/2022-23/LezioniCPP22-23/.gitignore b/2022-23/LezioniCPP22-23/.gitignore new file mode 100644 index 0000000..6879d2e --- /dev/null +++ b/2022-23/LezioniCPP22-23/.gitignore @@ -0,0 +1,438 @@ + +# Created by https://www.toptal.com/developers/gitignore/api/visualstudio,c++ +# Edit at https://www.toptal.com/developers/gitignore?templates=visualstudio,c++ + +### C++ ### +# Prerequisites +*.d + +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai +*.la +*.a +*.lib + +# Executables +*.exe +*.out +*.app + +### VisualStudio ### +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.iobj +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml + +### VisualStudio Patch ### +# Additional files built by Visual Studio + +# End of https://www.toptal.com/developers/gitignore/api/visualstudio,c++ diff --git a/2022-23/LezioniCPP22-23/LezioniCPP.vcxproj b/2022-23/LezioniCPP22-23/LezioniCPP.vcxproj new file mode 100644 index 0000000..093826c --- /dev/null +++ b/2022-23/LezioniCPP22-23/LezioniCPP.vcxproj @@ -0,0 +1,157 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 16.0 + Win32Proj + {ce9ed7c4-e77d-4122-952d-8206cbd38868} + LezioniCPP + 10.0 + + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + + + + + + + + + + + + + + + + + + + true + + + false + + + true + + + false + + + + Level3 + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + stdcpp20 + + + Console + true + + + + + Level3 + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + Level4 + true + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + stdcpp20 + + + Console + true + + + + + Level3 + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/2022-23/LezioniCPP22-23/LezioniCPP.vcxproj.filters b/2022-23/LezioniCPP22-23/LezioniCPP.vcxproj.filters new file mode 100644 index 0000000..6a2b4a8 --- /dev/null +++ b/2022-23/LezioniCPP22-23/LezioniCPP.vcxproj.filters @@ -0,0 +1,42 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + + + Header Files + + + \ No newline at end of file diff --git a/2022-23/LezioniCPP22-23/LezioniCPP22-23.sln b/2022-23/LezioniCPP22-23/LezioniCPP22-23.sln new file mode 100644 index 0000000..f4c9044 --- /dev/null +++ b/2022-23/LezioniCPP22-23/LezioniCPP22-23.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.31729.503 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LezioniCPP", "LezioniCPP.vcxproj", "{CE9ED7C4-E77D-4122-952D-8206CBD38868}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {CE9ED7C4-E77D-4122-952D-8206CBD38868}.Debug|x64.ActiveCfg = Debug|x64 + {CE9ED7C4-E77D-4122-952D-8206CBD38868}.Debug|x64.Build.0 = Debug|x64 + {CE9ED7C4-E77D-4122-952D-8206CBD38868}.Debug|x86.ActiveCfg = Debug|Win32 + {CE9ED7C4-E77D-4122-952D-8206CBD38868}.Debug|x86.Build.0 = Debug|Win32 + {CE9ED7C4-E77D-4122-952D-8206CBD38868}.Release|x64.ActiveCfg = Release|x64 + {CE9ED7C4-E77D-4122-952D-8206CBD38868}.Release|x64.Build.0 = Release|x64 + {CE9ED7C4-E77D-4122-952D-8206CBD38868}.Release|x86.ActiveCfg = Release|Win32 + {CE9ED7C4-E77D-4122-952D-8206CBD38868}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {F5305459-C861-4D73-8AF9-786E2D511A45} + EndGlobalSection +EndGlobal diff --git a/2022-23/LezioniCPP22-23/macros.ixx b/2022-23/LezioniCPP22-23/macros.ixx new file mode 100644 index 0000000..1dbac09 --- /dev/null +++ b/2022-23/LezioniCPP22-23/macros.ixx @@ -0,0 +1,49 @@ +export module macros; + +namespace macros { + // in linguaggio C non ci sono forme di polimorfismo: è pertanto necessario replicare il codice per tipi diversi + // questo è molto scomodo e prono agli errori + void myswap_int(int* a, int* b) { + int tmp = *a; + *a = *b; + *b = tmp; + } + + void myswap_double(double* a, double* b) { + double tmp = *a; + *a = *b; + *b = tmp; + } + + // usando le macro del preprocessore è possibile generare versioni diverse dello stesso codice sostituendo letteralmente l'argomento della macro + // questa macro si chiama SWAP ed ha un parametro di nome T + // l'operatore ## permette di appendere l'argomento della macro senza introdurre spazi + // si badi che quando si definisce una macro che deve essere indentata dentro un blocco, la convenzione è mettere il # ad inizio riga e tabbare la define + // il backslash immediatamente seguito dalla fine della riga, permette di definire macro su più righe +# define SWAP(T) \ + void swap_##T(T* a, T* b) { \ + T tmp = *a; \ + *a = *b; \ + *b = tmp; \ + } + + // qui usiamo la macro più volte: essa definirà varie versioni della swap con nomi diversi: swap_int, swap_double + SWAP(int) + SWAP(double) + SWAP(char) + SWAP(long) + + + export void test() + { + { + int x = 3, y = 6; + swap_int(&x, &y); + } + { + long x = 3, y = 6; + swap_long(&x, &y); + } + } + +} diff --git a/2022-23/LezioniCPP22-23/main.cpp b/2022-23/LezioniCPP22-23/main.cpp new file mode 100644 index 0000000..2820898 --- /dev/null +++ b/2022-23/LezioniCPP22-23/main.cpp @@ -0,0 +1,29 @@ +#include +#include + +import sums; +import zoo; +import macros; +import some_lambdas; +import smart_ptr; + +using namespace std; + +int main() +{ + try + { + smart_ptr::test(); + sums::test(); + zoo::test(); + macros::test(); + some_lambdas::test(); + return 0; + } + catch (exception& e) + { + cerr << "exception caught: " << e.what() << endl; + return 1; + } +} + diff --git a/2022-23/LezioniCPP22-23/smart_ptr.ixx b/2022-23/LezioniCPP22-23/smart_ptr.ixx new file mode 100644 index 0000000..71f2cff --- /dev/null +++ b/2022-23/LezioniCPP22-23/smart_ptr.ixx @@ -0,0 +1,228 @@ +export module smart_ptr; + +import ; +import ; +import ; +import ; + + +namespace smart_ptr +{ + + // definiamo un piccolo type trait che ci dice se possiamo usare la delete[] per un certo tipo + template + struct can_delete + { + static constexpr bool value = false; + }; + + // questa � una specializzazione parziale di can_delete che il compilatore sceglie solamente se compila il decltype nel secondo template argument + template + struct can_delete())>> + { + static constexpr bool value = true; + }; + + // uno smart points ha un tipo a cui punta ed una dimensiona statica templatizzata, il cui valore di default 1 se un non-array altrimenti la lunghezza del suo extent + // NOTA: si chiama extent la lunghezza statica degli array, ad esempio la parte tra parentesi quadre in: int[10] + export + template ? std::extent_v : 1)> + class smart_ptr + { + private: + using T = std::remove_extent_t; + using self = smart_ptr; + + protected: + T* pt; + ptrdiff_t offset; + size_t* cnt; + + void dec() + { + --(*cnt); + if (*cnt == 0) + { + if constexpr (can_delete::value) delete[] pt; + else delete pt; + delete cnt; + } + } + + void inc() + { + ++(*cnt); + } + + + public: + smart_ptr(T* pt_, ptrdiff_t offset_, size_t* cnt_) + : pt(pt_), offset(offset_), cnt(cnt_) + { + assert(offset >= 0 && offset < L); + inc(); + } + + explicit smart_ptr(T* p) : smart_ptr(p, 0, new size_t(1)) {} + + smart_ptr(const self& p) + : pt(p.pt), cnt(p.cnt), offset(p.offset) + { + inc(); + } + + ~smart_ptr() + { + dec(); + } + + self& operator=(const self& p) + { + if (pt != p.pt) + { + dec(); + pt = p.pt; + cnt = p.cnt; + offset = p.offset; + inc(); + } + return *this; + } + + T& operator*() + { + return const_cast(*std::as_const(*this)); + } + + const T& operator*() const + { + return pt[offset]; + } + + bool operator==(const self& p) const + { + return pt == p.pt && offset == p.offset; + } + + bool operator!=(const self& p) const + { + return !(*this == p); + } + + operator T* () + { + return const_cast(std::as_const(*this).operator const T * ()); + } + + operator const T* () const + { + return pt + offset; + } + + self operator+(ptrdiff_t d) const + { + return self(pt, offset + d, cnt); + } + + self operator-(ptrdiff_t d) const + { + return *this + (-d); + } + + self& operator+=(ptrdiff_t d) + { + assert(offset + d >= 0 && offset + d < L); + offset += d; + return *this; + } + + self& operator-=(ptrdiff_t d) + { + return *this += -d; + } + + self& operator++() + { + return *this += 1; + } + + self operator++(int) + { + self r(*this); + ++(*this); + return r; + } + + self& operator--() + { + return *this -= 1; + } + + self operator--(int) + { + self r(*this); + --(*this); + return r; + } + + T* operator->() + { + return const_cast(std::as_const(*this).operator->()); + } + + const T* operator->() const + { + return pt + offset; + } + + T& operator[](ptrdiff_t i) + { + return const_cast(std::as_const(*this)[i]); + } + + const T& operator[](ptrdiff_t i) const + { + assert(offset + i >= 0 && offset + i < L); + return pt[offset + i]; + } + }; + + + + // usa tutti gli operatori utilizzabili per i pointer classici + // � templatizzata cos� � possibile utilizzarla con tipi qualunque, basta che implementino gli operatori richiesti + // la usiamo per testare gli smart pointer + template + void demo(Pointer p) + { + Pointer p2(p); + p = p2; + *p; // in C, C++ ed altri linguaggi imperativi non � necessario utilizzare il risultato di una chiamata a funzione o operatore + const Pointer p3(p + 2); + p2 = p + 2; + ++p2; + p++; + --p2; + p += 1; + p -= 2; + p3[0]; + } + + + export void test() + { + int* a = new int[10]; + demo(a); + + smart_ptr a2(new int[5]); + demo(a2); + + smart_ptr b(a); + demo(b); + + smart_ptr d(new double[10]); + demo(d); + + } + +} diff --git a/2022-23/LezioniCPP22-23/some_lambdas.ixx b/2022-23/LezioniCPP22-23/some_lambdas.ixx new file mode 100644 index 0000000..0821277 --- /dev/null +++ b/2022-23/LezioniCPP22-23/some_lambdas.ixx @@ -0,0 +1,42 @@ +export module some_lambdas; + +import ; +import ; + +using namespace std; + +export namespace some_lambdas +{ + + export void test() + { + // proviamo un po' di lambda + { + auto f1 = [](int x) { return x + 1; }; // da int a int + auto f2 = [](auto x) { return x + 1; }; // con auto sul lambda parametro + auto f3 = [](auto x) -> int { return x + 1; }; // con annotazione esplicita del tipo di ritorno ed auto nel lambda parametro + auto f4 = [](int x) -> int { return x + 1; }; // con annotazione esplicita sia del tipo del lambda parametro che del tipo di ritorno + } + + // altri esempi con reference + { + auto f1 = [](const int& x) { return x + 1; }; // con un const int& come lambda parametro + auto f2 = [](const auto& x) { return x + 1; }; // auto può essere usato insieme a const e reference: il compilatore non inferisce mai & e const con auto, inferisce solo il tipo principale + auto f3 = [](auto& x) { x++; }; // come reference non-const + } + + // esempi di capture: si chiamano capture le variabili catturate dalla chiusura della lambda + // c++ permette di customizzare il comportamento delle capture in maniera molto fine + { + int k = 5; + vector v{ 1, 2, 3, 4, 5 }; + auto f1 = [=](int x) { return x + v[0] + k; }; // v e k sono catturate per COPIA nella chiusura della lambda + auto f2 = [&](int x) { return x + v[0] + k; }; // v e k sono catturate per REFERENCE nella chiusura della lambda + auto f3 = [=, &v](int x) { return x + v[0] + k; }; // tutto per copia (cioè solo k, nel nostro caso) eccetto v per reference + auto f4 = [&, k](int x) { return x + v[0] + k; }; // tutto per reference (cioè solo v, nel nostro caso) eccetto k per copia + auto f5 = [a = v, b = k](int x) { return x + a[0] + b; }; // tutto per copia con rebinding dei nomi: v si chiama a e k si chiama b + auto f6 = [&a = v, b = k](int x) { return x + a[0] + b; }; // v si chiama a ed è per reference; k si chiama b ed è per copia + } + } + +} \ No newline at end of file diff --git a/2022-23/LezioniCPP22-23/sums.ixx b/2022-23/LezioniCPP22-23/sums.ixx new file mode 100644 index 0000000..0161e37 --- /dev/null +++ b/2022-23/LezioniCPP22-23/sums.ixx @@ -0,0 +1,127 @@ +export module sums; + +import ; +import ; +import ; +import ; + +export namespace sums { + + // questa versione della sum templatizza l'intero container + template + typename C::value_type sum(const C& v) + { + if (v.size() > 0) + { + typename C::value_type r(v[0]); + for (size_t i = 0; i < v.size(); ++i) + { + typename C::const_reference x(v[i]); + r += x; + } + return r; + } + return C::value_type(); + } + + // questa versione della sum funziona sugli iteratori, naturalmente templatizzati + // tuttavia assume l'esistanza del member type value_type, quindi non dovrebbe funzionare con i pointer a meno di usare i traits + template + typename std::iterator_traits::value_type sum(InputIterator first, InputIterator last) + { + // iterator_traits funziona come una type function: crea un tipo con tutti i member type che lo rendono compatibile con un iteratore + // se gli si passa un tipo che è già un iteratore, non fa niente; se gli si passa un pointer crea tutti i member type opportuni + typename std::iterator_traits::value_type r(*first); + while (first != last) + { + r += *first++; + } + return r; + } + + // in C++11 è possibile usare auto + template + auto sum_cxx11(InputIterator first, InputIterator last) + { + auto r(*first); + while (first != last) + { + r += *first++; + } + return r; + } + + // questa versione della sum ha 3 parametri: il terzo parametro è una funzione, il cui tipo è templatizzato, e + template + auto sum(InputIterator first, InputIterator last, BinFun f) + { + auto r(*first); + while (first != last) + { + r = f(r, *first++); // f deve supportare la sintassi di CHIAMATA A FUNZIONE con 2 argomenti + } + return r; + } + + // questa classe definisce un overload di operator(), quindi permette alle sue istanze di supportare la sintassi della chiamata a funzione + class my_binary_function_object + { + private: + double k; + + public: + explicit my_binary_function_object(double k_) : k(k_) {} + + // questo è l'operatore che permette alle istanze di questa classe di essere usate COME SE FOSSERO UNA FUNZIONE che prende 2 argomenti di tipo e ritorna un int + double operator()(double a, double b) const + { + return a + b + k; // somma i 2 argomenti e il campo + } + + // questo metodo statico non serve a niente, se non a mostrare un piccolo test di questa classe per capire come funziona + static void test() + { + my_binary_function_object f(7.1); // costruisci un oggetto invocando l'unico costruttore che c'è + double x = f(11.23, 35.0); // la variabile f può essere usata COME SE FOSSE UNA FUNZIONE, cioè applicando 2 argomenti alla sua destra tra parentesi tonde + } + }; + + int my_global_binary_function(char a, char b) { return a + b; } + + export void test() + { + std::vector v1 { 1, 2, 3, -4, 5 }; + std::vector v2 { 56.67, 0.0, 4.5, 98.2134 }; + char a[4] { 11, 24, 123, -23 }; + + // alcuni test delle funzioni sum + { + int x = sum(v1); + double y = sum(v2); + } + + // con gli iteratori + { + int x = sum(v1.begin(), v1.end()); + double y = sum(v2.begin(), v2.end()); + } + + // con i pointer + { + char x = sum(a, a + 10); + double b[5]; + double y = sum(b, b + 5); + } + + // testiamo ora la versione della sum che prende 3 argomenti, di cui il terzo deve supportare la sintassi di chiamata a funzione + // ci sono varie espressioni possibili che supportano la sintassi di chiamata funzione e che sono quindi compatibili con la sum in questione + { + int x = sum(v1.begin(), v1.end(), [](int a, int b) { return a + b; }); // una lambda binaria che la fa somma degli argomenti di tipo int + int y = sum(v2.begin(), v2.end(), my_binary_function_object(8.67)); // una istanza di un oggetto che supporta la sintassi di chiamata con 2 argomenti + int z = sum(a, a + 10, my_global_binary_function); // un puntatore ad una funzione globale + } + + + } + +} \ No newline at end of file diff --git a/2022-23/LezioniCPP22-23/zoo.ixx b/2022-23/LezioniCPP22-23/zoo.ixx new file mode 100644 index 0000000..887e20f --- /dev/null +++ b/2022-23/LezioniCPP22-23/zoo.ixx @@ -0,0 +1,93 @@ + +export module zoo; + +import ; + +export namespace zoo +{ + + export class animal + { + protected: + int weight_; + + public: + explicit animal(int w) : weight_(w) {} + virtual ~animal() {} + + animal(const animal& a) : weight_(a.weight_) {} + + animal& operator=(const animal& a) + { + weight_ = a.weight_; + return *this; + } + + virtual void eat(const animal* a) + { + weight_ += a->weight_; + } + + const int& weight() const { return weight_; } + int& weight() { return weight_; } + }; + + class dog : public animal + { + private: + int* a; // supponiamo che un dog abbia un array al suo interno (non lo usiamo davvero, è solo un esempio per mostrare una new ed una delete) + + public: + explicit dog(int w) : animal(w), a(new int[10]) {} // l'array lo inizializziamo con una new[] + + ~dog() override + { + delete[] a; // è necessario distruggere l'array con una delete[] + } + + void eat(const animal* a) override + { + weight() = a->weight() * 2; + } + }; + + class cat : public animal + { + public: + explicit cat(int w) : animal(w) {} + + void eat(const animal* a) override + { + weight() = a->weight() / 3; + } + }; + + class labrador : public dog + { + public: + explicit labrador(int w) : dog(w) {} + + void eat(const animal* a) override + { + weight() = a->weight() * 5; + } + }; + + + export void test() + { + animal fido(50); // questo oggetto è nello stack + animal* pluto = new dog(40); // questo invece è nello heap, inoltre c'è subsumption qui + + fido.eat(pluto); // invoca la eat() di animal + pluto->eat(&fido); // invoca la eat() di dog perché c'è il dynamic dispatching in azione, grazie al fatto che eat() è virtual + + animal pluto2 = labrador(40); // questa non è una subsumption, è una invocazione del copy-constructor + pluto2.eat(pluto); // invoca la eat() di animal semplicemente perché l'oggetto è davvero un animal copiato da un labrador: nessun dynamic dispatching ha luogo + + delete pluto; // distruggi pluto chiamando il distruttore di dog: anche il distruttore è virtual, quindi è in virtual table, quindi è soggetto a dynamic dispatching pure lui + } + +} + + diff --git a/2022-23/LezioniJava22-23/.idea/misc.xml b/2022-23/LezioniJava22-23/.idea/misc.xml new file mode 100644 index 0000000..639900d --- /dev/null +++ b/2022-23/LezioniJava22-23/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/2022-23/LezioniJava22-23/.idea/modules.xml b/2022-23/LezioniJava22-23/.idea/modules.xml new file mode 100644 index 0000000..ef8c266 --- /dev/null +++ b/2022-23/LezioniJava22-23/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/2022-23/LezioniJava22-23/.idea/uiDesigner.xml b/2022-23/LezioniJava22-23/.idea/uiDesigner.xml new file mode 100644 index 0000000..2b63946 --- /dev/null +++ b/2022-23/LezioniJava22-23/.idea/uiDesigner.xml @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/2022-23/LezioniJava22-23/.idea/vcs.xml b/2022-23/LezioniJava22-23/.idea/vcs.xml new file mode 100644 index 0000000..b2bdec2 --- /dev/null +++ b/2022-23/LezioniJava22-23/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/2022-23/LezioniJava22-23/.idea/workspace.xml b/2022-23/LezioniJava22-23/.idea/workspace.xml new file mode 100644 index 0000000..45bee3d --- /dev/null +++ b/2022-23/LezioniJava22-23/.idea/workspace.xml @@ -0,0 +1,136 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1676643953687 + + + + + + + + + + + + + file://$PROJECT_DIR$/it/unive/dais/po2/misc/Zoo.java + 31 + + + + + \ No newline at end of file diff --git a/2022-23/LezioniJava22-23/LezioniJava22-23.iml b/2022-23/LezioniJava22-23/LezioniJava22-23.iml new file mode 100644 index 0000000..6abc57f --- /dev/null +++ b/2022-23/LezioniJava22-23/LezioniJava22-23.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/2022-23/LezioniJava22-23/it/unive/dais/po2/misc/HigherOrderFunctions.java b/2022-23/LezioniJava22-23/it/unive/dais/po2/misc/HigherOrderFunctions.java new file mode 100644 index 0000000..172d027 --- /dev/null +++ b/2022-23/LezioniJava22-23/it/unive/dais/po2/misc/HigherOrderFunctions.java @@ -0,0 +1,139 @@ +package it.unive.dais.po2.misc; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.function.*; + +public class HigherOrderFunctions { + + // non serve riscrivere queste interfacce funzionali, ma le riportiamo per facilitare la consultazione + + /*interface Function { + B apply(A x); + }*/ + + /*interface Consumer { + void accept(T x); + }*/ + + /*interface Supplier { + T get(); + }*/ + + /*interface Runnable { + void run(); + }*/ + + public static void main(String[] args) { + + Runnable r = () -> { System.out.println("ciao"); }; + Runnable r2 = new Runnable() { + @Override + public void run() { + System.out.println("ciao"); + } + }; + + Supplier h = () -> 1; + Supplier h2 = new Supplier() { + @Override + public Integer get() { + return 1; + } + }; + + Consumer g = x -> { System.out.println(x); }; + Consumer g2 = new Consumer() { + @Override + public void accept(Integer x) { + System.out.println(x); + } + }; + + Function f = x -> x + 1; + Function f2 = new Function() { + @Override + public Integer apply(Integer x) { + return x + 1; + } + }; + + } + + public static Collection map(Collection c, + Function f) { + Collection r = new ArrayList<>(); + for (A x : c) { + r.add(f.apply(x)); + } + return r; + } + + public static Iterator mapIterator(Iterator it, + Function f) { + return new Iterator() { + @Override + public boolean hasNext() { + return it.hasNext(); + } + + @Override + public B next() { + return f.apply(it.next()); + } + }; + } + + public static Collection filter__pure(Collection c, + Predicate p) { + Collection r = new ArrayList<>(); + for (T x : c) { + if (p.test(x)) + r.add(x); + } + return r; + } + + public static void filter__impure(Collection c, + Predicate p) { + Iterator it = c.iterator(); + while (it.hasNext()) { + if (!p.test(it.next())) + it.remove(); + } + } + + public static void iter(Collection c, Consumer f) { + for (T x : c) { + f.accept(x); + } + } + + public static T sum(Collection c, T zero, BiFunction f) { + return foldLeft(c, zero, f); + } + + public static B foldLeft(Collection c, + B zero, + BiFunction f) { + B z = zero; + for (A x : c) { + z = f.apply(x, z); + } + return z; + } + + // TODO scrivere la foldLeft ricorsivamente + + public static void main2(String[] args) { + List l = new ArrayList<>(); + l.add("ciao"); + l.add("mi"); + l.add("chiamo"); + l.add("pippo"); + String s = sum(l, "", (x, y) -> x + y); + + } +} diff --git a/2022-23/LezioniJava22-23/it/unive/dais/po2/misc/Sorting.java b/2022-23/LezioniJava22-23/it/unive/dais/po2/misc/Sorting.java new file mode 100644 index 0000000..8093ebf --- /dev/null +++ b/2022-23/LezioniJava22-23/it/unive/dais/po2/misc/Sorting.java @@ -0,0 +1,89 @@ +package it.unive.dais.po2.misc; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class Sorting { + + public interface Shape extends Comparable { + double area(); + double perimeter(); + + default int compareTo(Shape o) { + return (int) (this.area() - o.area()); + } + } + + public static class Circle implements Shape { + private double ray; + + public Circle(double r) { + this.ray = r; + } + + @Override + public int compareTo(Shape s) { + if (s instanceof Circle) { + Circle c = (Circle) s; + return (int) (ray - c.ray); + } + else { + return (int) (area() - s.area()); + } + } + + @Override + public double area() { + return Math.PI * ray * ray; + } + + @Override + public double perimeter() { + return Math.PI * 2. * ray; + } + } + + public static class Rectangle implements Shape { + private double base, height; + + public Rectangle(double b, double h) { + this.base = b; + this.height = h; + } + + @Override + public double area() { + return base * height; + } + + @Override + public double perimeter() { + return 2. * base + 2. * height; + } + } + + public static void main(String[] args) { + List l = List.of(4, 1, 38, -4, -567); + Collections.sort(l); // questa sort() sfrutta il fatto che gli Integer implementano Comparable + + List l2 = new ArrayList<>(); + l2.add(new Circle(4.)); + l2.add(new Circle(40.)); + l2.add(new Circle(56.)); + Collections.sort(l2); // questa sort() funziona perché Circle implementa Shape che implementa Comparable + + // queste due sort() ignora il fatto che Cirlce implementi Comparable e usa il Comparator passato + // come secondo argomento: si badi che il Comparator vince sul Comparable + Collections.sort(l2, (o1, o2) -> (int) (o1.ray - o2.ray)); + Collections.sort(l2, (Shape o1, Shape o2) -> (int) (o1.perimeter() - o2.perimeter())); + } + + // le due Collections.sort hanno le seguenti firme (vedi doc del JDK) + //static > void sort(List l) + //static void sort(List l, Comparator cmp) + + + + +} diff --git a/2022-23/LezioniJava22-23/it/unive/dais/po2/misc/Wildcards.java b/2022-23/LezioniJava22-23/it/unive/dais/po2/misc/Wildcards.java new file mode 100644 index 0000000..e63e768 --- /dev/null +++ b/2022-23/LezioniJava22-23/it/unive/dais/po2/misc/Wildcards.java @@ -0,0 +1,61 @@ +package it.unive.dais.po2.misc; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.function.Function; + +public class Wildcards { + + // esempi di funzione identica + public static T identity(T x) { + return x; + } // polimorfa tramite generics + public static Object identity2(Object x) { + return x; + } // polimorfa tramite subtyping + + // esempi di wildcard + public static Collection w1(Collection x) { + return x; // ? extends Number è sottotipo di ? + } + + public static Collection w2(Collection x) { + return x; // X è un Number, quindi è sottotipo di ? + } + + public static Collection w3(Collection x) { + return x; // + } + + // riscriviamo ora la funzione di ordine superiore map() che avevamo scritto nel file HigherOrderFunctions.java + // usiamo i wildcard per ampliare le potenzialità della funzione passata come secondo parametro + // permettendo la controvarianza del dominio e la co-varianza del co-dominio + public static Collection map(Collection c, + Function f) { + Collection r = new ArrayList<>(); + for (A x : c) { + r.add(f.apply(x)); + } + return r; + } + + + public static void main(String[] args) { + // esempio di chiamata della nuova versione della map() + List l = List.of(1, 2, 3); + Collection u = map(l, (Number x) -> 1); // passiamo una lambda che ha tipo Function nonostante i generic A = Integer e B = Number + + // altri esempi con i wildcard: cosa è possibile fare e non fare + List l1 = new ArrayList<>(); + Zoo.Dog fido = new Zoo.Dog(30, "red"); + //l.add(fido); // non si può chiamare add() perché Dog non è sottotipo di ? extends Animal + Zoo.Animal pluto = l1.get(0); + + List l2 = new ArrayList<>(); + l2.add(fido); + //Zoo.Dog rex = l2.get(0); // non si può gettare perché Dog non è supertipo di ? super Dog + } + + +} diff --git a/2022-23/LezioniJava22-23/it/unive/dais/po2/misc/Zoo.java b/2022-23/LezioniJava22-23/it/unive/dais/po2/misc/Zoo.java new file mode 100644 index 0000000..275d7e5 --- /dev/null +++ b/2022-23/LezioniJava22-23/it/unive/dais/po2/misc/Zoo.java @@ -0,0 +1,42 @@ +package it.unive.dais.po2.misc; + +public class Zoo { + public static class Animal { + protected int weight; + + public Animal(int w) { + this.weight = w; + } + + public void eat(Animal a) { + this.weight += a.weight; + } + } + + public static class Dog extends Animal { + private String hairColor; + + public Dog(int w, String hairColor) { + super(w); + this.hairColor = hairColor; + } + + @Override + public void eat(Animal a) { + this.weight = a.weight * 2; + } + } + + public static void main(String[] args) { + + Animal fido = new Dog(50, "Red"); + Dog pluto = new Dog(20, "Dotted"); + Animal ciccio = pluto; + Dog bobby = pluto; + ciccio = bobby; + + ciccio.eat(new Dog(10, "White")); + + } + +} diff --git a/2022-23/LezioniJava22-23/it/unive/dais/po2/threading/ConsumerProducer.java b/2022-23/LezioniJava22-23/it/unive/dais/po2/threading/ConsumerProducer.java new file mode 100644 index 0000000..5e1547d --- /dev/null +++ b/2022-23/LezioniJava22-23/it/unive/dais/po2/threading/ConsumerProducer.java @@ -0,0 +1,82 @@ +package it.unive.dais.po2.threading; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.function.Supplier; + +public class ConsumerProducer { + + private static final List l = new ArrayList<>(); + + public static class Producer extends Thread { + @Override + public void run() { + Random rnd = new Random(); + while (true) { + try { + Thread.sleep(10); + } catch (InterruptedException e) { + e.printStackTrace(); + } + int n = rnd.nextInt(100); + synchronized (l) { + l.add(n); + l.notify(); + System.out.printf("#%d: produced %d\n", Thread.currentThread().getId(), n); + } + } + } + } + + public static class Consumer extends Thread { + @Override + public void run() { + while (true) { + synchronized (l) { + if (l.isEmpty()) { + try { + l.wait(); + } catch (InterruptedException e) { + } + } + int n = l.remove(0); + System.out.printf("#%d: consumed %d\n", Thread.currentThread().getId(), n); + } + } + } + } + + private static + void populate(int n, List p, Supplier f) { + for (int i = 0; i < n; ++i) { + Thread t = f.get(); + p.add(t); + t.start(); + } + + } + + public static void main(String[] args) { + List p = new ArrayList<>(); + Supplier u = Producer::new; + populate(10, p, u); + populate(20, p, new Supplier<>() { + @Override + public Thread get() { + return new Consumer(); + } + }); + + for (Thread t : p) { + try { + t.join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + } + + +} diff --git a/2022-23/LezioniJava22-23/it/unive/dais/po2/threading/Threads.java b/2022-23/LezioniJava22-23/it/unive/dais/po2/threading/Threads.java new file mode 100644 index 0000000..dabc622 --- /dev/null +++ b/2022-23/LezioniJava22-23/it/unive/dais/po2/threading/Threads.java @@ -0,0 +1,54 @@ +package it.unive.dais.po2.threading; + +import java.util.Random; + +public class Threads { + + private static final Random rnd = new Random(); + + private static int rand(int a, int b) { + synchronized (rnd) { + return rnd.nextInt(b - a) + a; + } + } + + private static void loop() { + while (true) { + synchronized (rnd) { + try { + Thread.sleep(rand(200, 1000)); + } catch (InterruptedException e) {} + + System.out.println("ciao sono "); + System.out.println("il thread #" + Thread.currentThread().getId()); + } + } + } + + public static class MyThread extends Thread { + @Override + public void run() { + loop(); + } + } + + public static void main(String[] args) { + Thread t1 = new MyThread(); + t1.start(); + + new Thread(Threads::loop).start(); + new MyThread().start(); + new MyThread().start(); + new MyThread().start(); + loop(); + + try { + t1.join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + } + + +} diff --git a/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/ArrayList.java b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/ArrayList.java new file mode 100644 index 0000000..f50967a --- /dev/null +++ b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/ArrayList.java @@ -0,0 +1,177 @@ +package it.unive.dais.po2.tinyjdk; + +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Predicate; + +public class ArrayList implements List { + + private Object[] a; + private int sz; + + public ArrayList(int capacity) { + a = new Object[capacity]; + sz = 0; + } + + public ArrayList() { + this(10); + } + + @Override + public int size() { + return sz; + } + + @Override + public void add(T x) { + if (sz >= a.length) { + Object[] old = a; + a = new Object[old.length * 2]; + for (int i = 0; i < old.length; ++i) + a[i] = old[i]; + } + a[sz++] = x; + } + + @Override + public void remove(T x) { + // TODO per chi vuole implementarla + } + + // versione in C della removeIf() + /*void C_removeIf(int* a, size_t len, bool(*p)(int)) + { + for (int i = 0; i < len; ++i) { + int x = a[i]; + if (p(x)) { + removeAt(i); + } + } + }*/ + + private static class MyPredicate implements Predicate { + @Override + public boolean test(Integer x) { + return x % 3 == 0; + } + } + + public static void main(String[] args) { + List c = new ArrayList<>(); + c.add(78); + c.add(-456); + c.add(7); + c.add(4); + c.add(7834); + + c.removeIf(new Predicate() { + @Override + public boolean test(Integer x) { + return x < 0; + } + }); + + Function y = x -> x > 80; + + c.removeIf(new MyPredicate()); + c.removeIf(x -> x > 80); + } + + // esempi di method reference + public int f(int x) { return x; } + public static boolean g(int x, float y) { return true; } + + public static void main2(String[] args) { + BiFunction, Integer, Integer> f1 = ArrayList::f; + Function f2 = new ArrayList<>()::f; + BiFunction g1 = ArrayList::g; + BiFunction g2 = (x, y) -> g(x, y); + } + + + @Override + public boolean contains(T x) { + //return contains(x::equals); // method reference equivalente alla lambda qua sotto + return contains((T y) -> x.equals(y)); + } + + @Override + public boolean contains(Predicate p) { + Iterator it = iterator(); + while (it.hasNext()) { + if (p.test(it.next())) + return true; + } + return false; + } + + + private class MyIterator implements Iterator { + private int pos = 0; + + @Override + public boolean hasNext() { + return pos < size(); + } + + @Override + public T next() { + return get(pos++); + } + } + + private static class ListIterator implements Iterator { + private int pos = 0; + private List l; + + public ListIterator(List l) { + this.l = l; + } + + @Override + public boolean hasNext() { + return pos < l.size(); + } + + @Override + public E next() { + return l.get(pos++); + } + } + + @Override + public Iterator iterator() { + //return new MyIterator(); + //return new ListIterator(this); + return new Iterator() { + private int pos = 0; + + @Override + public boolean hasNext() { + return pos < size(); + } + + @Override + public T next() { + return get(pos++); + } + }; + } + + + @Override + public T get(int index) { + return (T) a[index]; + } + + @Override + public void set(int index, T x) { + a[index] = x; + } + + @Override + public void removeAt(int index) { + // TODO per casa + } +} diff --git a/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/BasicQueue.java b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/BasicQueue.java new file mode 100644 index 0000000..b7a501c --- /dev/null +++ b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/BasicQueue.java @@ -0,0 +1,54 @@ +package it.unive.dais.po2.tinyjdk; + +import java.util.function.Predicate; + +public class BasicQueue implements Queue { + private List l = new ArrayList<>(); + + @Override + public int size() { + return l.size(); + } + + @Override + public void add(T x) { + l.add(x); + } + + @Override + public void remove(T x) { + throw new NotImplementedException(); + } + + + @Override + public boolean contains(T x) { + return false; + } + + @Override + public boolean contains(Predicate p) { + // TODO per casa + return false; + } + + @Override + public Iterator iterator() { + return null; + } + + @Override + public void push(T x) { + + } + + @Override + public T pop() { + return null; + } + + @Override + public T peek() { + return null; + } +} diff --git a/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/BinaryTree.java b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/BinaryTree.java new file mode 100644 index 0000000..17a69cc --- /dev/null +++ b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/BinaryTree.java @@ -0,0 +1,10 @@ +package it.unive.dais.po2.tinyjdk; + +public interface BinaryTree extends Iterable { + BinaryTree left(); + BinaryTree right(); + T get(); + int height(); + BinaryTree parent(); + BinaryTree root(); +} diff --git a/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/Collection.java b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/Collection.java new file mode 100644 index 0000000..78215a2 --- /dev/null +++ b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/Collection.java @@ -0,0 +1,16 @@ +package it.unive.dais.po2.tinyjdk; + +import java.util.function.Predicate; + +public interface Collection extends Iterable { + int size(); + + default boolean isEmpty() { return size() == 0; } + + void add(T x); + + void remove(T x); + + boolean contains(T x); + boolean contains(Predicate p); +} diff --git a/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/HashMap.java b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/HashMap.java new file mode 100644 index 0000000..bb52b8e --- /dev/null +++ b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/HashMap.java @@ -0,0 +1,82 @@ +package it.unive.dais.po2.tinyjdk; + +public class HashMap implements Map { + private static int CAPACITY = 1000; + + private List>> l = new ArrayList<>(CAPACITY); + + @Override + public Iterator> iterator() { + // TODO fixare o riscrivere per casa + return new Iterator>() { + private int i = 0, j = -1; + private boolean _hasNext = true; + + @Override + public boolean hasNext() { + return _hasNext; + } + + @Override + public Pair next() { + Pair r = null; + if (j >= 0) { + List> inl = l.get(i); + r = inl.get(j++); + if (j > inl.size()) + j = -1; + } + else { + for (; i < l.size(); ++i) { + List> inl = l.get(i); + if (inl == null) + continue; + r = inl.get(0); + j = 1; + } + } + if (r == null) + _hasNext = false; + return r; + } + }; + } + + @Override + public void put(K key, V value) { + int h = key.hashCode() % CAPACITY; + List> inl = l.get(h); + if (inl == null) { + inl = new ArrayList<>(); + l.set(h, inl); + } + inl.add(new Pair<>(key, value)); + } + + @Override + public V get(K key) throws KeyNotFoundException { + int h = key.hashCode() % CAPACITY; + List> inl = l.get(h); + if (inl != null) { + for (int i = 0; i < inl.size(); ++i) { + Pair p = inl.get(i); + if (p.fst.equals(key)) + return p.snd; + } + } + throw new KeyNotFoundException(String.format("key %s is missing", key)); +// throw new RuntimeException(String.format("unexpected error: key %s is not found at index %d", key, h)); + } + + @Override + public boolean containsKey(K key) { + // TODO per casa + return false; + } + + @Override + public V removeKey(K key) throws KeyNotFoundException { + // TODO per casa + return null; + } +} diff --git a/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/HashSet.java b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/HashSet.java new file mode 100644 index 0000000..42bc410 --- /dev/null +++ b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/HashSet.java @@ -0,0 +1,48 @@ +package it.unive.dais.po2.tinyjdk; + +import java.util.function.Predicate; + +public class HashSet implements Set { + private List l = new ArrayList<>(); + + @Override + public int size() { + return l.size(); + } + + @Override + public void add(T x) { + if (!contains(x)) + l.add(x); + } + + @Override + public void remove(T x) { + for (int i = 0; i < l.size(); ++i) { + T o = l.get(i); + if (o.hashCode() == x.hashCode()) + l.removeAt(i); + } + } + + @Override + public boolean contains(T x) { + for (int i = 0; i < l.size(); ++i) { + T o = l.get(i); + if (o.hashCode() == x.hashCode()) + return true; + } + return false; + } + + @Override + public boolean contains(Predicate p) { + // TODO per casa + return false; + } + + @Override + public Iterator iterator() { + return l.iterator(); + } +} diff --git a/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/Iterable.java b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/Iterable.java new file mode 100644 index 0000000..8a384cc --- /dev/null +++ b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/Iterable.java @@ -0,0 +1,5 @@ +package it.unive.dais.po2.tinyjdk; + +public interface Iterable { + Iterator iterator(); +} diff --git a/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/Iterator.java b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/Iterator.java new file mode 100644 index 0000000..565282a --- /dev/null +++ b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/Iterator.java @@ -0,0 +1,6 @@ +package it.unive.dais.po2.tinyjdk; + +public interface Iterator { + boolean hasNext(); + T next(); +} diff --git a/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/List.java b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/List.java new file mode 100644 index 0000000..5c1d9bc --- /dev/null +++ b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/List.java @@ -0,0 +1,22 @@ +package it.unive.dais.po2.tinyjdk; +import java.util.function.Predicate; + +public interface List extends Collection { + T get(int index); + + void set(int index, T x); + + void removeAt(int index); + + default T removeIf(Predicate p) { + for (int i = 0; i < size(); ++i) { + T x = get(i); + if (p.test(x)) { + removeAt(i); + return x; + } + } + return null; + } + +} diff --git a/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/Map.java b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/Map.java new file mode 100644 index 0000000..15100eb --- /dev/null +++ b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/Map.java @@ -0,0 +1,15 @@ +package it.unive.dais.po2.tinyjdk; + +public interface Map extends Iterable> { + class KeyNotFoundException extends Exception { + public KeyNotFoundException(String msg) { + super(msg); + } + } + + void put(K key, V value); + V get(K key) throws KeyNotFoundException; + + boolean containsKey(K key); + V removeKey(K key) throws KeyNotFoundException; +} diff --git a/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/NodeBinaryTree.java b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/NodeBinaryTree.java new file mode 100644 index 0000000..026c2e6 --- /dev/null +++ b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/NodeBinaryTree.java @@ -0,0 +1,73 @@ +package it.unive.dais.po2.tinyjdk; + +public class NodeBinaryTree implements BinaryTree { + + private final T data; + private final BinaryTree l, r; + + public NodeBinaryTree(T data, BinaryTree l, BinaryTree r) { + this.data = data; + this.l = l; + this.r = r; + } + + public NodeBinaryTree(T data) { + this(data, null, null); + } + + public static BinaryTree L(T data, BinaryTree l) { + return new NodeBinaryTree<>(data, l, null); + } + + public static BinaryTree R(T data, BinaryTree r) { + return new NodeBinaryTree<>(data, null, r); + } + + public static void main(String[] args) { + // TODO provare a riscrivere questo albero usando L() e R() + NodeBinaryTree root = new NodeBinaryTree<>(1, + new NodeBinaryTree<>(8, + new NodeBinaryTree<>(9), + new NodeBinaryTree<>(11, + new NodeBinaryTree<>(12), + null)), + new NodeBinaryTree<>(13) + ); + } + + + @Override + public BinaryTree left() { + return null; + } + + @Override + public BinaryTree right() { + return null; + } + + @Override + public T get() { + return null; + } + + @Override + public int height() { + return 0; + } + + @Override + public BinaryTree parent() { + return null; + } + + @Override + public BinaryTree root() { + return null; + } + + @Override + public Iterator iterator() { + return null; + } +} diff --git a/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/NotImplementedException.java b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/NotImplementedException.java new file mode 100644 index 0000000..a08f094 --- /dev/null +++ b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/NotImplementedException.java @@ -0,0 +1,4 @@ +package it.unive.dais.po2.tinyjdk; + +public class NotImplementedException extends RuntimeException { +} diff --git a/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/Pair.java b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/Pair.java new file mode 100644 index 0000000..99cdbb0 --- /dev/null +++ b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/Pair.java @@ -0,0 +1,11 @@ +package it.unive.dais.po2.tinyjdk; + +public class Pair { + public final A fst; + public final B snd; + + public Pair(A a, B b) { + this.fst = a; + this.snd = b; + } +} diff --git a/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/PairMap.java b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/PairMap.java new file mode 100644 index 0000000..41d0dde --- /dev/null +++ b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/PairMap.java @@ -0,0 +1,43 @@ +package it.unive.dais.po2.tinyjdk; + +public class PairMap implements Map { + private List> l = new ArrayList<>(); + + @Override + public Iterator> iterator() { + return l.iterator(); + } + + @Override + public void put(K key, V value) { + l.add(new Pair(key, value)); + } + + @Override + public V get(K key) throws KeyNotFoundException { + Iterator> it = l.iterator(); + while (it.hasNext()) { + Pair p = it.next(); + if (p.fst.equals(key)) + return p.snd; + } + throw new KeyNotFoundException(String.format("key %s not found", key)); + } + + @Override + public boolean containsKey(K key) { + try { + get(key); + return true; + } + catch (KeyNotFoundException e) { + return false; + } + } + + @Override + public V removeKey(K key) throws KeyNotFoundException { + // TODO per voi + throw new NotImplementedException(); + } +} diff --git a/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/Queue.java b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/Queue.java new file mode 100644 index 0000000..43d2747 --- /dev/null +++ b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/Queue.java @@ -0,0 +1,7 @@ +package it.unive.dais.po2.tinyjdk; + +public interface Queue extends Collection { + void push(T x); + T pop(); + T peek(); +} diff --git a/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/Set.java b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/Set.java new file mode 100644 index 0000000..a3749b2 --- /dev/null +++ b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/Set.java @@ -0,0 +1,4 @@ +package it.unive.dais.po2.tinyjdk; + +public interface Set extends Collection { +} diff --git a/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/nogenerics/NoGenerics.java b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/nogenerics/NoGenerics.java new file mode 100644 index 0000000..50aef27 --- /dev/null +++ b/2022-23/LezioniJava22-23/it/unive/dais/po2/tinyjdk/nogenerics/NoGenerics.java @@ -0,0 +1,103 @@ +package it.unive.dais.po2.tinyjdk.nogenerics; + +import it.unive.dais.po2.misc.Zoo; + +// in questo file mostriamo come si faceva una volta, prima che Java 5 introducesse i generics + +public class NoGenerics { + + // JDK 1.0 (1994) + + public interface Iterator { + boolean hasNext(); + Object next(); + } + + public interface Iterable { + Iterator iterator(); + } + + public interface Collection extends Iterable { + int size(); + void add(Object x); + void remove(Object x); + boolean contains(Object x); + } + + public interface List extends Collection { + Object get(int index); + void set(int index, Object x); + } + + public static class ArrayList implements List { + + private Object[] a; + private int sz; + + public ArrayList(int capacity) { + a = new Object[capacity]; + sz = 0; + } + + public ArrayList() { + this(10); + } + + @Override + public int size() { + return sz; + } + + @Override + public void add(Object x) { + if (sz >= a.length) { + Object[] old = a; + a = new Object[old.length * 2]; + for (int i = 0; i < old.length; ++i) + a[i] = old[i]; + } + a[sz++] = x; + } + + @Override + public void remove(Object x) { + + } + + @Override + public boolean contains(Object x) { + return false; + } + + @Override + public Iterator iterator() { + return null; + } + + + @Override + public Object get(int index) { + return a[index]; + } + + @Override + public void set(int index, Object x) { + a[index] = x; + } + } + + + public static void main(String[] args) { + List c = new ArrayList(); + c.add("ciao"); + c.add(8); + c.add(new Zoo.Dog(20, "Red")); + + for (int i = 0; i < c.size(); ++i) { + String s = (String) c.get(i); + + } + + } + +} diff --git a/2022-23/LezioniJava22-23/out/production/LezioniJava22-23/.idea/misc.xml b/2022-23/LezioniJava22-23/out/production/LezioniJava22-23/.idea/misc.xml new file mode 100644 index 0000000..639900d --- /dev/null +++ b/2022-23/LezioniJava22-23/out/production/LezioniJava22-23/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/2022-23/LezioniJava22-23/out/production/LezioniJava22-23/.idea/modules.xml b/2022-23/LezioniJava22-23/out/production/LezioniJava22-23/.idea/modules.xml new file mode 100644 index 0000000..ef8c266 --- /dev/null +++ b/2022-23/LezioniJava22-23/out/production/LezioniJava22-23/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/2022-23/LezioniJava22-23/out/production/LezioniJava22-23/.idea/uiDesigner.xml b/2022-23/LezioniJava22-23/out/production/LezioniJava22-23/.idea/uiDesigner.xml new file mode 100644 index 0000000..2b63946 --- /dev/null +++ b/2022-23/LezioniJava22-23/out/production/LezioniJava22-23/.idea/uiDesigner.xml @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/2022-23/LezioniJava22-23/out/production/LezioniJava22-23/.idea/vcs.xml b/2022-23/LezioniJava22-23/out/production/LezioniJava22-23/.idea/vcs.xml new file mode 100644 index 0000000..b2bdec2 --- /dev/null +++ b/2022-23/LezioniJava22-23/out/production/LezioniJava22-23/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/2022-23/LezioniJava22-23/out/production/LezioniJava22-23/.idea/workspace.xml b/2022-23/LezioniJava22-23/out/production/LezioniJava22-23/.idea/workspace.xml new file mode 100644 index 0000000..e4a0c0b --- /dev/null +++ b/2022-23/LezioniJava22-23/out/production/LezioniJava22-23/.idea/workspace.xml @@ -0,0 +1,131 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1676643953687 + + + + + + + + + + + + + file://$PROJECT_DIR$/it/unive/dais/po2/Zoo.java + 33 + + + + + \ No newline at end of file diff --git a/2022-23/LezioniJava22-23/out/production/LezioniJava22-23/LezioniJava22-23.iml b/2022-23/LezioniJava22-23/out/production/LezioniJava22-23/LezioniJava22-23.iml new file mode 100644 index 0000000..6abc57f --- /dev/null +++ b/2022-23/LezioniJava22-23/out/production/LezioniJava22-23/LezioniJava22-23.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/2023-24/.idea/.gitignore b/2023-24/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/2023-24/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/2023-24/.idea/misc.xml b/2023-24/.idea/misc.xml new file mode 100644 index 0000000..862d09b --- /dev/null +++ b/2023-24/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/2023-24/.idea/modules.xml b/2023-24/.idea/modules.xml new file mode 100644 index 0000000..1467495 --- /dev/null +++ b/2023-24/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/2023-24/.idea/vcs.xml b/2023-24/.idea/vcs.xml new file mode 100644 index 0000000..6c0b863 --- /dev/null +++ b/2023-24/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/2023-24/2023-24.iml b/2023-24/2023-24.iml new file mode 100644 index 0000000..81bae42 --- /dev/null +++ b/2023-24/2023-24.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/2023-24/LezioniCPP23-24/LezioniCPP/LezioniCPP.sln b/2023-24/LezioniCPP23-24/LezioniCPP/LezioniCPP.sln new file mode 100644 index 0000000..fcc8ac4 --- /dev/null +++ b/2023-24/LezioniCPP23-24/LezioniCPP/LezioniCPP.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.5.33627.172 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LezioniCPP", "LezioniCPP\LezioniCPP.vcxproj", "{F22B848D-8942-41FD-A3A2-BD7C5CF98C4C}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {F22B848D-8942-41FD-A3A2-BD7C5CF98C4C}.Debug|x64.ActiveCfg = Debug|x64 + {F22B848D-8942-41FD-A3A2-BD7C5CF98C4C}.Debug|x64.Build.0 = Debug|x64 + {F22B848D-8942-41FD-A3A2-BD7C5CF98C4C}.Debug|x86.ActiveCfg = Debug|Win32 + {F22B848D-8942-41FD-A3A2-BD7C5CF98C4C}.Debug|x86.Build.0 = Debug|Win32 + {F22B848D-8942-41FD-A3A2-BD7C5CF98C4C}.Release|x64.ActiveCfg = Release|x64 + {F22B848D-8942-41FD-A3A2-BD7C5CF98C4C}.Release|x64.Build.0 = Release|x64 + {F22B848D-8942-41FD-A3A2-BD7C5CF98C4C}.Release|x86.ActiveCfg = Release|Win32 + {F22B848D-8942-41FD-A3A2-BD7C5CF98C4C}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {EC04A7C9-2ADD-4E4E-8C9D-8FAD4CDBE013} + EndGlobalSection +EndGlobal diff --git a/2023-24/LezioniCPP23-24/LezioniCPP/LezioniCPP/LezioniCPP.cpp b/2023-24/LezioniCPP23-24/LezioniCPP/LezioniCPP/LezioniCPP.cpp new file mode 100644 index 0000000..26dd24a --- /dev/null +++ b/2023-24/LezioniCPP23-24/LezioniCPP/LezioniCPP/LezioniCPP.cpp @@ -0,0 +1,71 @@ + +#include + + + +class animal +{ +protected: + int weight; + double speed; + +public: + animal() : weight(), speed() {} + animal(int w, double sp) : weight(w), speed(sp) {} + animal(const animal& a) : weight(a.weight), speed(a.speed) {} + + const int& weight() const { return weight; } + + int& weight() { return weight; } + + virtual void eat(const animal& a) + { + weight += a.weight; + } +}; + +class dog : public animal +{ +private: + bool has_pedigree; + +public: + dog(int w, double sp, bool ped) : animal(w, sp), has_pedigree(ped) {} + + void eat(const animal& a) { + weight() += a.weight() / 2; + } +}; + + +void main() { + animal* a1 = new animal(7, 2.34); + animal a2(7, 2.34); + + animal a3(a2); + animal* a4 = new animal(a2); + + a2.eat(a2); + + dog fido(60, 45.34, false); + animal& a5 = fido; + a5.eat(a2); + + dog* fufi = new dog(3, 100., true); + animal* a6 = fufi; + a6->eat(a2); + + animal pippo(fido); + pippo.eat(a2); + +} + + + + + + +int main() +{ +} + diff --git a/2023-24/LezioniCPP23-24/LezioniCPP/LezioniCPP/LezioniCPP.vcxproj b/2023-24/LezioniCPP23-24/LezioniCPP/LezioniCPP/LezioniCPP.vcxproj new file mode 100644 index 0000000..5b07be8 --- /dev/null +++ b/2023-24/LezioniCPP23-24/LezioniCPP/LezioniCPP/LezioniCPP.vcxproj @@ -0,0 +1,137 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 16.0 + Win32Proj + {f22b848d-8942-41fd-a3a2-bd7c5cf98c4c} + LezioniCPP + 10.0 + + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + + + + + + + + + + + + + + + + + + + + Level3 + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + Level3 + true + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + + + + + + + \ No newline at end of file diff --git a/2023-24/LezioniCPP23-24/LezioniCPP/LezioniCPP/LezioniCPP.vcxproj.filters b/2023-24/LezioniCPP23-24/LezioniCPP/LezioniCPP/LezioniCPP.vcxproj.filters new file mode 100644 index 0000000..f14b371 --- /dev/null +++ b/2023-24/LezioniCPP23-24/LezioniCPP/LezioniCPP/LezioniCPP.vcxproj.filters @@ -0,0 +1,28 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + + Source Files + + + Source Files + + + \ No newline at end of file diff --git a/2023-24/LezioniCPP23-24/LezioniCPP/LezioniCPP/LezioniCPP.vcxproj.user b/2023-24/LezioniCPP23-24/LezioniCPP/LezioniCPP/LezioniCPP.vcxproj.user new file mode 100644 index 0000000..88a5509 --- /dev/null +++ b/2023-24/LezioniCPP23-24/LezioniCPP/LezioniCPP/LezioniCPP.vcxproj.user @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/2023-24/LezioniCPP23-24/LezioniCPP/LezioniCPP/matrix.cpp b/2023-24/LezioniCPP23-24/LezioniCPP/LezioniCPP/matrix.cpp new file mode 100644 index 0000000..827407c --- /dev/null +++ b/2023-24/LezioniCPP23-24/LezioniCPP/LezioniCPP/matrix.cpp @@ -0,0 +1,105 @@ +#include +#include + +using namespace std; + +template +class matrix +{ +private: + size_t cols; + vector v; + +public: + matrix() : v() {} + matrix(const matrix& m) : cols(m.cols), v(m.v) {} + + template + matrix(const matrix& m) : cols(m.cols), v(m.get_rows() * m.get_cols()) + { + for (int i = 0; i < v.size(); ++i) + v[i] = m.v[i]; + } + + matrix(size_t rows, size_t _cols, const T& x = T()) + : cols(_cols), v(rows* cols, x) {} + + + explicit matrix(size_t dim) : matrix(dim, dim) {} + + typedef T value_type; + typedef vector::iterator iterator; + typedef vector::const_iterator const_iterator; + + iterator begin() + { + return v.begin(); + } + + iterator end() + { + return v.end(); + } + + const_iterator begin() const + { + return v.begin(); + } + + const_iterator end() const; + { + return v.end(); + } + + operator const vector&() const + { + return v; + } + + matrix& operator=(const matrix& m) + { + cols = m.cols; + v = m.v; + return *this; + } + + const T& operator()(size_t i, size_t j) const + { + return v[i * cols + j]; + } + T& operator()(size_t i, size_t j) + { + return v[i * cols + j]; + } + + size_t get_cols() const { return cols; } + size_t get_rows() const { return v.size() / cols; } +}; + +template +ostream& operator<<(ostream& os, const C& m) +{ + for (typename C::iterator it = m.v.begin(); it != m.v.end(); ++it) + { + typename C::value_type x = *it; + os << x << " "; + } + return os; +} + + + +void main() +{ + matrix m1(20, 30); + + for (matrix::iterator it = m1.begin(); it != m1.end(); ++it) + { + matrix::value_type x = *it; + cout << x; + } + + +} + + diff --git a/2023-24/LezioniCPP23-24/LezioniCPP/LezioniCPP/smart_ptr.cpp b/2023-24/LezioniCPP23-24/LezioniCPP/LezioniCPP/smart_ptr.cpp new file mode 100644 index 0000000..7d79cc4 --- /dev/null +++ b/2023-24/LezioniCPP23-24/LezioniCPP/LezioniCPP/smart_ptr.cpp @@ -0,0 +1,59 @@ + + +template +class smart_ptr +{ +private: + T* pt; + const T* orig; + unsigned int* cnt; + +public: + explicit smart_ptr(T* _pt) : pt(_pt), orig(_pt), cnt(new unsigned int(1u)) {} + + smart_ptr(const smart_ptr& sp) : pt(sp.pt), orig(sp.orig), cnt(sp.cnt) + { + ++ *cnt; + } + + ~smart_ptr() + { + if (-- *cnt == 0) + { + delete orig; + delete cnt; + } + } + + T& operator*() + { + return *pt; + } + + const T& operator*() const + { + return *pt; + } + + smart_ptr& operator++() + { + ++pt; + return *this; + } + + smart_ptr operator++(int) + { + smart_ptr r(*this); + ++pt; + return r; + } +}; + + + +void main() +{ + int n = 7; + int m = n++ + 1; + +} \ No newline at end of file diff --git a/2023-24/LezioniJava23-24/.gitignore b/2023-24/LezioniJava23-24/.gitignore new file mode 100644 index 0000000..f68d109 --- /dev/null +++ b/2023-24/LezioniJava23-24/.gitignore @@ -0,0 +1,29 @@ +### 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 diff --git a/2023-24/LezioniJava23-24/.idea/.gitignore b/2023-24/LezioniJava23-24/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/2023-24/LezioniJava23-24/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/2023-24/LezioniJava23-24/.idea/misc.xml b/2023-24/LezioniJava23-24/.idea/misc.xml new file mode 100644 index 0000000..d15472f --- /dev/null +++ b/2023-24/LezioniJava23-24/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/2023-24/LezioniJava23-24/.idea/modules.xml b/2023-24/LezioniJava23-24/.idea/modules.xml new file mode 100644 index 0000000..aea0ebf --- /dev/null +++ b/2023-24/LezioniJava23-24/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/2023-24/LezioniJava23-24/.idea/uiDesigner.xml b/2023-24/LezioniJava23-24/.idea/uiDesigner.xml new file mode 100644 index 0000000..2b63946 --- /dev/null +++ b/2023-24/LezioniJava23-24/.idea/uiDesigner.xml @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/2023-24/LezioniJava23-24/.idea/vcs.xml b/2023-24/LezioniJava23-24/.idea/vcs.xml new file mode 100644 index 0000000..b2bdec2 --- /dev/null +++ b/2023-24/LezioniJava23-24/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/2023-24/LezioniJava23-24/LezioniJava23-24.iml b/2023-24/LezioniJava23-24/LezioniJava23-24.iml new file mode 100644 index 0000000..c90834f --- /dev/null +++ b/2023-24/LezioniJava23-24/LezioniJava23-24.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/2023-24/LezioniJava23-24/src/concurrent/ConsumerProducer.java b/2023-24/LezioniJava23-24/src/concurrent/ConsumerProducer.java new file mode 100644 index 0000000..eb64c1b --- /dev/null +++ b/2023-24/LezioniJava23-24/src/concurrent/ConsumerProducer.java @@ -0,0 +1,65 @@ +package concurrent; + + +import java.util.*; + +public class ConsumerProducer { + + public static List buff = new ArrayList<>(); + + public static class Producer extends Thread { + public Producer() { + super("Producer"); + } + @Override + public void run() { + Random rnd = new Random(); + while (true) { + int n = rnd.nextInt(); + synchronized (buff) { // lock + buff.add(n); + buff.notify(); + System.out.printf("%s: added %d\n", getName(), n); + } // unlock + } + } + } + public static class Consumer extends Thread { + public Consumer() { + super("Consumer"); + } + @Override + public void run() { + while (true) { + synchronized (buff) { // lock + if (buff.isEmpty()) { + try { + buff.wait(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } + int n = buff.remove(0); + System.out.printf("%s: removed %d\n", getName(), n); + } // unlock + } + } + } + + public static void main(String[] args) { + List threads = new ArrayList<>(); + for (int i = 0; i < 20; ++i) { + Thread t = new Producer(); + t.start(); + threads.add(t); + t = new Consumer(); + t.start(); + threads.add(t); + } + try { + threads.get(0).join(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } +} diff --git a/2023-24/LezioniJava23-24/src/concurrent/Threads.java b/2023-24/LezioniJava23-24/src/concurrent/Threads.java new file mode 100644 index 0000000..fb26592 --- /dev/null +++ b/2023-24/LezioniJava23-24/src/concurrent/Threads.java @@ -0,0 +1,27 @@ +package concurrent; + +public class Threads { + public static String suffix = "baudo"; + public static void loop(String msg) { + while (true) { + System.out.println(msg + " " + suffix); + } + } + public static class MyThread extends Thread { + @Override + public void run() { + loop("ciao"); + } + } + + public static void main(String[] args) { + Thread t = new MyThread(); + t.start(); + loop("pippo"); + + // modo alternativo + Thread t2 = new Thread(() -> loop("ciccio")); + t2.start(); + } + +} diff --git a/2023-24/LezioniJava23-24/src/misc/HigherOrderFunctions.java b/2023-24/LezioniJava23-24/src/misc/HigherOrderFunctions.java new file mode 100644 index 0000000..b266819 --- /dev/null +++ b/2023-24/LezioniJava23-24/src/misc/HigherOrderFunctions.java @@ -0,0 +1,108 @@ +package misc; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.function.*; + + +/* +void for_each(int* a, size_t len, void(*f)(int)) { + for (int i = 0; i < len; ++i) + f(a[i]); +} + +void print_int(int n) { + printf("%d\n", n); +} + +void main(){ + int A[10] = ...; + for_each(A, 10, print_int); +} +*/ + +public class HigherOrderFunctions { + + interface PippoFunction { + B ciccio(A x); + } + + public static List map(Iterable c, PippoFunction f) { + List r = new ArrayList<>(); + for (A x : c) { + B b = f.ciccio(x); + r.add(b); + } + return r; + } + + public static void forEach(Iterable c, Consumer f) { + for (T x : c) + f.accept(x); + } + public static List filter(Iterable c, Predicate f) { + List r = new ArrayList<>(); + for (T x : c) { + if (f.test(x)) + r.add(x); + } + return r; + } + public static void filter__impure(Iterable c, Function f) { + Iterator it = c.iterator(); + while (it.hasNext()) { + if (!f.apply(it.next())) + it.remove(); + } + } + + public static void main(String[] args) { + List l = List.of(1, 2, -3, 4); + + // map + Collection r1 = map(l, x -> x + 1); + Collection r2 = map(l, new PippoFunction() { + @Override + public Integer ciccio(Integer x) { + return x + 1; + } + }); + + // forEach + forEach(l, x -> System.out.println(x)); + forEach(l, new Consumer() { + @Override + public void accept(Integer x) { + System.out.print(x); + } + }); + forEach(l, x -> System.out.println(x)); + forEach(l, new Consumer() { + @Override + public void accept(Integer x) { + System.out.print(x); + } + }); + + // filter + Collection c1 = filter(l, x -> x > 2); + + // filter__impure + filter(l, x -> x > 2); + + // +/* List dogs = new ArrayList<>(); + + Function f = (d) -> new misc.Zoo.Cat(d.getWeight()); + PippoFunction g = (d) -> new misc.Zoo.Cat(d.getWeight()); + + // questa non compila giustamente + //List cats = map(dogs, f); + + List cats2 = map(dogs, g);*/ + + } + +} diff --git a/2023-24/LezioniJava23-24/src/misc/InterfacesVsAbstractClasses.java b/2023-24/LezioniJava23-24/src/misc/InterfacesVsAbstractClasses.java new file mode 100644 index 0000000..8cee49f --- /dev/null +++ b/2023-24/LezioniJava23-24/src/misc/InterfacesVsAbstractClasses.java @@ -0,0 +1,42 @@ +package misc; + +public class InterfacesVsAbstractClasses { + + public interface I { + void a(); + void b(); + default void c() { + a(); + b(); + } + } + + public static abstract class J { + public abstract void a(); + public abstract void b(); + public void c() { + a(); + b(); + } + } + + + + + public static class C implements I { + + @Override + public void a() { + + } + + @Override + public void b() { + + } + } + + public static void main(String[] args) { + I o = new C(); + } +} diff --git a/2023-24/LezioniJava23-24/src/misc/IteratorTest.java b/2023-24/LezioniJava23-24/src/misc/IteratorTest.java new file mode 100644 index 0000000..587219b --- /dev/null +++ b/2023-24/LezioniJava23-24/src/misc/IteratorTest.java @@ -0,0 +1,27 @@ +package misc; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class IteratorTest { + + public static void main(String[] args) { + + List l = new ArrayList(); + l.add(21); + l.add(2); + l.add(456); + + Iterator it = l.iterator(); + while (it.hasNext()) { + int n = it.next(); + System.out.println(n); + } + + for (int i = 0; i < l.size(); ++i) { + int n = l.get(i); + System.out.println(n); + } + } +} diff --git a/2023-24/LezioniJava23-24/src/misc/Overloading.java b/2023-24/LezioniJava23-24/src/misc/Overloading.java new file mode 100644 index 0000000..7d7f408 --- /dev/null +++ b/2023-24/LezioniJava23-24/src/misc/Overloading.java @@ -0,0 +1,22 @@ +package misc; + +import java.util.List; + +public class Overloading { + + public static class A { + public Number m() { return 1.3; } + } + + public static class B extends A { + @Override + public Integer m() { return 2; } + } + + + public static void main(String[] args) { + A a = new B(); + Number u = a.m(); + } + +} diff --git a/2023-24/LezioniJava23-24/src/misc/Sorting.java b/2023-24/LezioniJava23-24/src/misc/Sorting.java new file mode 100644 index 0000000..88d0ff0 --- /dev/null +++ b/2023-24/LezioniJava23-24/src/misc/Sorting.java @@ -0,0 +1,34 @@ +package misc; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +public class Sorting { + + public static void sort(List list, Comparator c) { ... } + + public static class Animal { + public int weight; + public Animal(int w) { this.weight = w; } + } + public static class Dog extends Animal { + public boolean pedigree; + public Dog(int w, boolean p) { super(w); this.pedigree = p; } + } + + public static void main(String[] args) { + List l = new ArrayList<>(); + l.add(new Dog(50, false)); + l.add(new Dog(20, true)); + l.add(new Dog(30, true)); + + sort(l, new Comparator() { + @Override + public int compare(Animal o1, Animal o2) { + return o1.weight - o2.weight; + } + }); + } + +} diff --git a/2023-24/LezioniJava23-24/src/misc/Wildcards.java b/2023-24/LezioniJava23-24/src/misc/Wildcards.java new file mode 100644 index 0000000..cd09a88 --- /dev/null +++ b/2023-24/LezioniJava23-24/src/misc/Wildcards.java @@ -0,0 +1,24 @@ +package misc; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Function; + +public class Wildcards { + + public static List map(Iterable c, + Function f) { + List r = new ArrayList<>(); + for (A x : c) { + B b = f.apply(x); + r.add(b); + } + return r; + } + + public static void main(String[] args) { + List l1 = List.of("pippo", "franco", "ciccio", "gigi"); + List l2 = map(l1, (CharSequence s) -> s.length()); + } + +} diff --git a/2023-24/LezioniJava23-24/src/misc/Zoo.java b/2023-24/LezioniJava23-24/src/misc/Zoo.java new file mode 100644 index 0000000..963b967 --- /dev/null +++ b/2023-24/LezioniJava23-24/src/misc/Zoo.java @@ -0,0 +1,55 @@ +package misc; + +public class Zoo { + + public static class Animal { + protected int weight; + + public int getWeight() { return weight; } + + public Animal(int w) { + this.weight = w; + } + + public void eat(Animal a) { + this.weight += a.weight; + } + } + + public static class Dog extends Animal { + private boolean pedgree; + + public Dog(int w, boolean ped) { + super(w); + this.pedgree = ped; + } + + public void bark() { + System.out.println("bau!"); + } + + public void eat(Animal a) { + this.weight += a.weight * 2; + } + } + + public static class Cat extends Animal { + + public Cat(int w) { + super(w); + } + + @Override + public void eat(Animal a) { + this.weight += a.weight / 2; + } + } + + public static void main(String[] args) + { + Dog fido = new Dog(50, false); + Animal pluto = new Dog(40, true); + pluto.eat(fido); + } + +} \ No newline at end of file diff --git a/2023-24/LezioniJava23-24/src/tinyjdk/AbstractResizableArray.java b/2023-24/LezioniJava23-24/src/tinyjdk/AbstractResizableArray.java new file mode 100644 index 0000000..4f0dacb --- /dev/null +++ b/2023-24/LezioniJava23-24/src/tinyjdk/AbstractResizableArray.java @@ -0,0 +1,41 @@ +package tinyjdk; + +public abstract class AbstractResizableArray implements Collection { + protected Object[] a; + protected int sz; + + public AbstractResizableArray() { + this.a = new Object[10]; + this.sz = 0; + } + + @Override + public void add(T x) { + if (sz >= a.length) { + Object[] old = a; + a = new Object[a.length * 2]; + for (int i = 0; i < old.length; ++i) + a[i] = old[i]; + } + a[sz++] = x; + } + + @Override + public void clear() { + sz = 0; + } + + @Override + public boolean isEmpty() { + return sz == 0; + } + + public abstract void remove(T x); + + @Override + public int size() { + return sz; + } + + public abstract Iterator iterator(); +} diff --git a/2023-24/LezioniJava23-24/src/tinyjdk/ArrayList.java b/2023-24/LezioniJava23-24/src/tinyjdk/ArrayList.java new file mode 100644 index 0000000..f37bfb8 --- /dev/null +++ b/2023-24/LezioniJava23-24/src/tinyjdk/ArrayList.java @@ -0,0 +1,125 @@ +package tinyjdk; + +public class ArrayList implements List { + private Object[] a; + private int sz; + + public ArrayList() { + this.a = new Object[10]; + this.sz = 0; + } + + @Override + public void add(T x) { + if (sz >= a.length) { + Object[] old = a; + a = new Object[a.length * 2]; + for (int i = 0; i < old.length; ++i) + a[i] = old[i]; + } + a[sz++] = x; + } + + @Override + public void clear() { + sz = 0; + } + + @Override + public boolean isEmpty() { + return sz == 0; + } + + @Override + public void remove(T x) { + for (int i = 0; i < size(); ++i) { + T o = get(i); + if (o.equals(x)) { + for (int j = i ; j < size() - 1; ++j) + set(j, get(j + 1)); + --sz; + } + } + } + + @Override + public int size() { + return sz; + } + // static nested iterator + private static class StaticMyIterator implements Iterator { + private int pos = 0; + private ArrayList enclosing; + + public StaticMyIterator(ArrayList a) { + this.enclosing = a; + } + @Override + public boolean hasNext() { + return this.pos < enclosing.size(); + } + @Override + public T next() { + return enclosing.get(pos++); + } + } + + // non-static nested iterator + private class MyIterator implements Iterator { + private int pos = 0; + + @Override + public boolean hasNext() { + return pos < size(); + } + @Override + public T next() { + return get(pos++); + } + } + + @Override + public Iterator iterator() { + // anonymous class interator + return new Iterator() { + private int pos = 0; + @Override + public boolean hasNext() { + return pos < size(); + } + + @Override + public T next() { + return get(pos++); + } + }; + } + + @Override + public T get(int i) { + if (i < sz) + return (T) a[i]; + throw new RuntimeException(String.format("ArrayList.get(): index %d out of bounds %d", i, sz)); + } + + @Override + public T set(int i, T x) { + if (i < sz) { + T old = get(i); + a[i] = x; + return old; + } + throw new RuntimeException(String.format("ArrayList.set(): index %d out of bounds %d", i, sz)); + } + + @Override + public void add(int i, T x) { + // TODO per casa + } + + @Override + public T remove(int i) { + // TODO per casa + return null; + } +} diff --git a/2023-24/LezioniJava23-24/src/tinyjdk/ArrayList2.java b/2023-24/LezioniJava23-24/src/tinyjdk/ArrayList2.java new file mode 100644 index 0000000..7145f61 --- /dev/null +++ b/2023-24/LezioniJava23-24/src/tinyjdk/ArrayList2.java @@ -0,0 +1,59 @@ +package tinyjdk; + +public class ArrayList2 extends AbstractResizableArray implements List { + @Override + public void remove(T x) { + for (int i = 0; i < size(); ++i) { + T o = get(i); + if (o.equals(x)) { + for (int j = i ; j < size() - 1; ++j) + set(j, get(j + 1)); + --sz; + } + } + } + + @Override + public Iterator iterator() { + return new Iterator() { + private int pos = 0; + @Override + public boolean hasNext() { + return pos < size(); + } + + @Override + public T next() { + return get(pos++); + } + }; + } + + @Override + public T get(int i) { + if (i < sz) + return (T) a[i]; + throw new RuntimeException(String.format("ArrayList.get(): index %d out of bounds %d", i, sz)); + } + + @Override + public T set(int i, T x) { + if (i < sz) { + T old = get(i); + a[i] = x; + return old; + } + throw new RuntimeException(String.format("ArrayList.set(): index %d out of bounds %d", i, sz)); + } + + @Override + public void add(int i, T x) { + // TODO + } + + @Override + public T remove(int i) { + // TODO + return null; + } +} diff --git a/2023-24/LezioniJava23-24/src/tinyjdk/ArrayListIterator.java b/2023-24/LezioniJava23-24/src/tinyjdk/ArrayListIterator.java new file mode 100644 index 0000000..07ee883 --- /dev/null +++ b/2023-24/LezioniJava23-24/src/tinyjdk/ArrayListIterator.java @@ -0,0 +1,19 @@ +package tinyjdk; + +public class ArrayListIterator implements Iterator { + private int pos = 0; + private ArrayList enclosing; + + public ArrayListIterator(ArrayList a) { + this.enclosing = a; + } + @Override + public boolean hasNext() { + return this.pos < enclosing.size(); + } + @Override + public T next() { + return enclosing.get(pos++); + } + +} diff --git a/2023-24/LezioniJava23-24/src/tinyjdk/Collection.java b/2023-24/LezioniJava23-24/src/tinyjdk/Collection.java new file mode 100644 index 0000000..2842897 --- /dev/null +++ b/2023-24/LezioniJava23-24/src/tinyjdk/Collection.java @@ -0,0 +1,25 @@ +package tinyjdk; + +public interface Collection extends Iterable { + void add(T x); + + default void addAll(Collection c) { + Iterator it = c.iterator(); + while (it.hasNext()) { + add(it.next()); + } + } + void clear(); + default boolean contains(T x) { + Iterator it = iterator(); + while (it.hasNext()) { + T e = it.next(); + if (e.equals(x)) + return true; + } + return false; + } + boolean isEmpty(); + void remove(T x); + int size(); +} diff --git a/2023-24/LezioniJava23-24/src/tinyjdk/Comparable.java b/2023-24/LezioniJava23-24/src/tinyjdk/Comparable.java new file mode 100644 index 0000000..ebf9220 --- /dev/null +++ b/2023-24/LezioniJava23-24/src/tinyjdk/Comparable.java @@ -0,0 +1,5 @@ +package tinyjdk; + +public interface Comparable { + int compareTo(T x); +} diff --git a/2023-24/LezioniJava23-24/src/tinyjdk/HashSet.java b/2023-24/LezioniJava23-24/src/tinyjdk/HashSet.java new file mode 100644 index 0000000..f153342 --- /dev/null +++ b/2023-24/LezioniJava23-24/src/tinyjdk/HashSet.java @@ -0,0 +1,31 @@ +package tinyjdk; + +public class HashSet extends AbstractResizableArray implements Set{ + + @Override + public void add(T x) { + if (!contains(x)) + super.add(x); + } + @Override + public boolean contains(T x) { + Iterator it = iterator(); + int h = x.hashCode(); + while (it.hasNext()) { + T e = it.next(); + if (e.hashCode() == h) + return true; + } + return false; + } + @Override + public void remove(T x) { + // TODO + } + + @Override + public Iterator iterator() { + // TODO + return null; + } +} diff --git a/2023-24/LezioniJava23-24/src/tinyjdk/IndexOutOfBoundsException.java b/2023-24/LezioniJava23-24/src/tinyjdk/IndexOutOfBoundsException.java new file mode 100644 index 0000000..b198f18 --- /dev/null +++ b/2023-24/LezioniJava23-24/src/tinyjdk/IndexOutOfBoundsException.java @@ -0,0 +1,8 @@ +package tinyjdk; + +public class IndexOutOfBoundsException extends Exception { + public IndexOutOfBoundsException(String msg) { + super(msg); + } +} + diff --git a/2023-24/LezioniJava23-24/src/tinyjdk/Iterable.java b/2023-24/LezioniJava23-24/src/tinyjdk/Iterable.java new file mode 100644 index 0000000..140cd2c --- /dev/null +++ b/2023-24/LezioniJava23-24/src/tinyjdk/Iterable.java @@ -0,0 +1,6 @@ +package tinyjdk; + +public interface Iterable { + Iterator iterator(); +} + diff --git a/2023-24/LezioniJava23-24/src/tinyjdk/Iterator.java b/2023-24/LezioniJava23-24/src/tinyjdk/Iterator.java new file mode 100644 index 0000000..b80a1b9 --- /dev/null +++ b/2023-24/LezioniJava23-24/src/tinyjdk/Iterator.java @@ -0,0 +1,6 @@ +package tinyjdk; + +public interface Iterator { + boolean hasNext(); + E next(); +} diff --git a/2023-24/LezioniJava23-24/src/tinyjdk/LinkedList.java b/2023-24/LezioniJava23-24/src/tinyjdk/LinkedList.java new file mode 100644 index 0000000..a3a2486 --- /dev/null +++ b/2023-24/LezioniJava23-24/src/tinyjdk/LinkedList.java @@ -0,0 +1,113 @@ +package tinyjdk; + +public class LinkedList implements List { + + protected class Node { + public T data; + public Node next; + public Node(T data, Node next) { + this.data = data; + this.next = next; + } + } + protected Node head; + protected int sz; + public LinkedList() { + this.head = null; + sz = 0; + } + @Override + public void add(T x) { + if (head == null) { + head = new Node(x, null); + } + else { + // TODO da testare + Node n = head; + while (n.next != null) { + n = n.next; + } + n.next = new Node(x, null); + } + ++sz; + } + + @Override + public void clear() { + head = null; + sz = 0; + } + + @Override + public boolean isEmpty() { + return head == null; + } + + @Override + public void remove(T x) { + for (Node prev = null, n = head; n != null; prev = n, n = n.next) { + if (n.data.equals(x)) { + if (prev != null) + prev.next = n.next; + else + head = n.next; + return; + } + } + } + + @Override + public int size() { + return sz; + } + + @Override + public Iterator iterator() { + return new Iterator<>() { + private Node n = head; + @Override + public boolean hasNext() { + return n != null; + } + @Override + public T next() { + T r = n.data; + n = n.next; + return r; + } + }; + } + + protected Node getNode(int i) { + if (i < 0 || i >= size()) + throw new RuntimeException(String.format("index %d is out of bound (size = %d)", i, size())); + Node n = head; + for (; i > 0; --i) + n = n.next; + return n; + } + + @Override + public T get(int i) { + return getNode(i).data; + } + + @Override + public T set(int i, T x) { + Node n = getNode(i); + T old = n.data; + n.data = x; + return old; + } + + @Override + public void add(int i, T x) { + // TODO per casa + } + + @Override + public T remove(int i) { + // TODO per casa + return null; + } +} diff --git a/2023-24/LezioniJava23-24/src/tinyjdk/List.java b/2023-24/LezioniJava23-24/src/tinyjdk/List.java new file mode 100644 index 0000000..5271ddb --- /dev/null +++ b/2023-24/LezioniJava23-24/src/tinyjdk/List.java @@ -0,0 +1,8 @@ +package tinyjdk; + +public interface List extends Collection { + T get(int i); + T set(int i, T x); + void add(int i, T x); + T remove(int i); +} diff --git a/2023-24/LezioniJava23-24/src/tinyjdk/Main.java b/2023-24/LezioniJava23-24/src/tinyjdk/Main.java new file mode 100644 index 0000000..05c3836 --- /dev/null +++ b/2023-24/LezioniJava23-24/src/tinyjdk/Main.java @@ -0,0 +1,7 @@ +package tinyjdk; + +public class Main { + + public static void main(String[] args) { + } +} diff --git a/2023-24/LezioniJava23-24/src/tinyjdk/Map.java b/2023-24/LezioniJava23-24/src/tinyjdk/Map.java new file mode 100644 index 0000000..3656177 --- /dev/null +++ b/2023-24/LezioniJava23-24/src/tinyjdk/Map.java @@ -0,0 +1,15 @@ +package tinyjdk; +import java.lang.Exception; + +public interface Map extends Iterable> { + void put(K k, V v); + + V get(K k) throws KeyNotFoundException; + + class KeyNotFoundException extends Exception { + public KeyNotFoundException(Object k) { + super(String.format("key %s not found in map", k)); + } + } +} + diff --git a/2023-24/LezioniJava23-24/src/tinyjdk/Pair.java b/2023-24/LezioniJava23-24/src/tinyjdk/Pair.java new file mode 100644 index 0000000..896484e --- /dev/null +++ b/2023-24/LezioniJava23-24/src/tinyjdk/Pair.java @@ -0,0 +1,11 @@ +package tinyjdk; + +public class Pair { + public final A first; + public final B second; + + public Pair(A a, B b) { + first = a; + second = b; + } +} diff --git a/2023-24/LezioniJava23-24/src/tinyjdk/PairMap.java b/2023-24/LezioniJava23-24/src/tinyjdk/PairMap.java new file mode 100644 index 0000000..2bdb6eb --- /dev/null +++ b/2023-24/LezioniJava23-24/src/tinyjdk/PairMap.java @@ -0,0 +1,35 @@ +package tinyjdk; + +public class PairMap implements Map { + private final List> l = new ArrayList<>(); + + @Override + public void put(K k, V v) { + assert (k != null); + l.add(new Pair<>(k, v)); + } + + @Override + public V get(K k) throws KeyNotFoundException { + for (int i = l.size() - 1; i >= 0 ; --i) { + final Pair p = l.get(i); + if (p.first.equals(k)) + return p.second; + } + throw new KeyNotFoundException(k); + } + + @Override + public Iterator> iterator() { + Set history = new HashSet<>(); + List> r = new ArrayList<>(); + for (int i = l.size() - 1; i >= 0; --i) { + Pair p = l.get(i); + if (!history.contains(p.first)) { + history.add(p.first); + r.add(p); + } + } + return r.iterator(); + } +} diff --git a/2023-24/LezioniJava23-24/src/tinyjdk/Set.java b/2023-24/LezioniJava23-24/src/tinyjdk/Set.java new file mode 100644 index 0000000..739cb95 --- /dev/null +++ b/2023-24/LezioniJava23-24/src/tinyjdk/Set.java @@ -0,0 +1,4 @@ +package tinyjdk; + +public interface Set extends Collection { +} diff --git a/2023-24/LezioniJava23-24/src/tinyjdk/SortedSet.java b/2023-24/LezioniJava23-24/src/tinyjdk/SortedSet.java new file mode 100644 index 0000000..5e3246a --- /dev/null +++ b/2023-24/LezioniJava23-24/src/tinyjdk/SortedSet.java @@ -0,0 +1,6 @@ +package tinyjdk; + +public interface SortedSet> extends Set { + T first(); + T last(); +} diff --git a/2023-24/LezioniJava23-24/src/tinyjdk/StructuralSet.java b/2023-24/LezioniJava23-24/src/tinyjdk/StructuralSet.java new file mode 100644 index 0000000..ca1b461 --- /dev/null +++ b/2023-24/LezioniJava23-24/src/tinyjdk/StructuralSet.java @@ -0,0 +1,21 @@ +package tinyjdk; +public class StructuralSet + extends AbstractResizableArray + implements Set { + @Override + public void add(T x) { + if (!contains(x)) + super.add(x); + } + + @Override + public void remove(T x) { + // TODO + } + + @Override + public Iterator iterator() { + // TODO + return null; + } +} diff --git a/2023-24/LezioniJava23-24/src/tinyjdk/StructuralSortedSet.java b/2023-24/LezioniJava23-24/src/tinyjdk/StructuralSortedSet.java new file mode 100644 index 0000000..da4785e --- /dev/null +++ b/2023-24/LezioniJava23-24/src/tinyjdk/StructuralSortedSet.java @@ -0,0 +1,51 @@ +package tinyjdk; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.NoSuchElementException; + +public class StructuralSortedSet> + extends StructuralSet + implements SortedSet { + + @Override + public void add(T x) { + super.add(x); + sort(); + } + +/* private void sort() { + T[] a = (T[]) this.a; + while (...) { + int i = 0; + if (a[i].compareTo(a[i + 1]) > 0) { + T tmp = a[i]; + a[i] = a[i + 1]; + a[i + 1] = tmp; + } + } + }*/ + + private void sort() { + T[] src = (T[]) a; + Arrays.sort(src, 0, size(), new Comparator() { + @Override + public int compare(T o1, T o2) { + return o1.compareTo(o2); + } + }); + } + + @Override + public T first() { + if (isEmpty()) throw new NoSuchElementException(); + return (T) a[0]; + } + + @Override + public T last() { + if (isEmpty()) throw new NoSuchElementException(); + return (T) a[size() - 1]; + } +} diff --git a/2024-25/LezioniJava24-25/.gitignore b/2024-25/LezioniJava24-25/.gitignore new file mode 100644 index 0000000..f68d109 --- /dev/null +++ b/2024-25/LezioniJava24-25/.gitignore @@ -0,0 +1,29 @@ +### 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 diff --git a/2024-25/LezioniJava24-25/.idea/.gitignore b/2024-25/LezioniJava24-25/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/2024-25/LezioniJava24-25/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/2024-25/LezioniJava24-25/.idea/misc.xml b/2024-25/LezioniJava24-25/.idea/misc.xml new file mode 100644 index 0000000..c3aa11c --- /dev/null +++ b/2024-25/LezioniJava24-25/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/2024-25/LezioniJava24-25/.idea/modules.xml b/2024-25/LezioniJava24-25/.idea/modules.xml new file mode 100644 index 0000000..7b904e8 --- /dev/null +++ b/2024-25/LezioniJava24-25/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/2024-25/LezioniJava24-25/.idea/vcs.xml b/2024-25/LezioniJava24-25/.idea/vcs.xml new file mode 100644 index 0000000..b2bdec2 --- /dev/null +++ b/2024-25/LezioniJava24-25/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/2024-25/LezioniJava24-25/LezioniJava24-25.iml b/2024-25/LezioniJava24-25/LezioniJava24-25.iml new file mode 100644 index 0000000..c90834f --- /dev/null +++ b/2024-25/LezioniJava24-25/LezioniJava24-25.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/2024-25/LezioniJava24-25/src/misc/Functional.java b/2024-25/LezioniJava24-25/src/misc/Functional.java new file mode 100644 index 0000000..5b9db97 --- /dev/null +++ b/2024-25/LezioniJava24-25/src/misc/Functional.java @@ -0,0 +1,138 @@ +package misc; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.function.BiFunction; + +public class Functional { + + + + public interface Function { + B apply(A x); + } + + public interface Consumer { + void apply(T x); + } + + public static Collection map(Collection c, Function f) { + Collection r = new ArrayList(); + for (A a : c) { + B b = f.apply(a); + r.add(b); + } + return r; + } + + public static void iter(Collection c, Consumer f) { + for (T x : c) { + f.apply(x); + } + } + + public static Collection filter(Collection c, Function f) { + Collection r = new ArrayList<>(); + for (T x : c) { + if (f.apply(x)) { + r.add(x); + } + } + return r; + } + + public interface BiFunction { + C apply(A a, B b); + } + + public static R fold(Collection c, R zero, BiFunction f) { + R r = zero; + for (T x : c) { + r = f.apply(x, r); + } + return r; + } + + + public static void main(String[] args) { + { + List l = List.of(1, 2, 3, 4, 5); + String r = fold(l, "", new BiFunction<>() { + public String apply(Integer x, String acc) { + return acc.concat(x.toString()); + } + }); + } + + { + List l = List.of(-56, 345, 11, 0, -456, 23); + int r = fold(l, 1, new BiFunction() { + public Integer apply(Integer x, Integer acc) { + return x * acc; + } + }); + } + + { + List l = List.of(-56.567, 345.356, 11.3254, 0.0, -456.345, 23.345); + double r = fold(l, 0.0, new BiFunction<>() { + public Double apply(Double x, Double acc) { + return x + acc; + } + }); + } + + { + List l = List.of("ciao", "sono", "franco", "!"); + String r = fold(l, "", new BiFunction<>() { + public String apply(String x, String acc) { + return x.concat(acc); + } + }); + } + + + { + List l = List.of("ciao", "sono", "franco", "!"); + Collection r = map(l, new Function<>() { + public Integer apply(String x) { + return x.length(); + } + }); + } + + { + List l = List.of(-56, 345, 11, 0, -456, 23); + final int k = 0; + Collection r = map(l, new Function() { + public Boolean apply(Integer x) { + return x > k; + } + }); + Collection r2 = map(l, (x) -> x > k); + } + + { + List l = List.of(-56, 345, 11, 0, -456, 23); + iter(l, new Consumer() { + public void apply(Integer x) { + System.out.println(x); + } + }); + } + + { + List l = List.of(-56, 345, 11, 0, -456, 23); + Collection r = filter(l, new Function() { + public Boolean apply(Integer x) { + return x < 0; + } + }); + } + + } + + + +} diff --git a/2024-25/LezioniJava24-25/src/misc/Sorting.java b/2024-25/LezioniJava24-25/src/misc/Sorting.java new file mode 100644 index 0000000..d2bc824 --- /dev/null +++ b/2024-25/LezioniJava24-25/src/misc/Sorting.java @@ -0,0 +1,47 @@ +package misc; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +public class Sorting { + + + public static > void sort(List list) { ... } + + + /*public interface Comparator { + int compare(T o1, T o2); + }*/ + + public static void main(String[] args) { + { + List l = new ArrayList<>(); + l.add(new Zoo.Dog(20, "mio")); + l.add(new Zoo.Dog(29, "mio")); + l.add(new Zoo.Dog(28, "mio")); + sort(l); + + + + + Collections.sort(l, new Comparator<>() { + @Override + public int compare(Zoo.Animal a, Zoo.Animal b) { + return a.weight - b.weight; + } + }); + } + { + List l = List.of("ciao", "pippo", "gigio", "byebye"); + Collections.sort(l, new Comparator<>() { + public int compare(String a, String b) { + return b.length() - a.length(); + } + }); + } + } + + +} diff --git a/2024-25/LezioniJava24-25/src/misc/Zoo.java b/2024-25/LezioniJava24-25/src/misc/Zoo.java new file mode 100644 index 0000000..ca244cf --- /dev/null +++ b/2024-25/LezioniJava24-25/src/misc/Zoo.java @@ -0,0 +1,75 @@ +package misc; + +public class Zoo { + + public static class Animal implements Comparable { + + protected int weight; + + public Animal(int weight) { + this.weight = weight; + } + + public void eat(Animal a) { + this.weight += a.weight; + } + + @Override + public int compareTo(Animal o) { + return this.weight - o.weight; + } + } + + public static class Dog extends Animal { + private String owner; + + public Dog(int weight, String owner) { + super(weight); + this.owner = owner; + } + + @Override + public int compareTo(Animal o) { + if (o instanceof Dog) { + Dog d = (Dog) o; + ... + } + else return super.compareTo(o); + } + + public void bark() { + System.out.println("BAUUU!"); + } + + @Override + public void eat(Animal a) { + this.weight += a.weight * 2; + } + } + + public static class Cat extends Animal { + public Cat(int weight) { + super(weight); + } + + public void meow() { + System.out.println("Meow!"); + } + + @Override + public void eat(Animal a) { + this.weight += a.weight / 2; + } + } + + // POLIMORFISMO SUBTYPING + public static void main(String[] args) { + Animal tilde = new Animal(10); + Dog fido = new Dog(20, "Gigi"); // SUBSUMPTION + fido.eat(tilde); + Animal pippo = new Cat(30); + //pippo.meow(); + pippo.eat(fido); + } + +} diff --git a/2024-25/LezioniJava24-25/src/tinyjdk/ArrayList.java b/2024-25/LezioniJava24-25/src/tinyjdk/ArrayList.java new file mode 100644 index 0000000..552424a --- /dev/null +++ b/2024-25/LezioniJava24-25/src/tinyjdk/ArrayList.java @@ -0,0 +1,148 @@ +package tinyjdk; + +public class ArrayList implements List { + + T[] a; + int sz; + + public ArrayList() { + this.a = (T[]) new Object[10]; + this.sz = 0; + } + + @Override + public int size() { + return sz; + } + + @Override + public void add(T e) { + if (sz >= a.length) { + T[] newa = (T[]) new Object[a.length * 2]; + for (int i = 0; i < a.length; ++i) { + newa[i] = a[i]; + } + a = newa; + } + a[sz++] = e; + } + + @Override + public T get(int i) { + if (i < 0 || i >= sz) throw new IndexOutOfBoundsException(); + return a[i]; + } + + @Override + public void set(int i, T e) { + if (i < 0 || i >= sz) throw new IndexOutOfBoundsException(); + a[i] = e; + } + + @Override + public void clear() { + sz = 0; + } + + + @Override + public boolean contains(T e) { + for (int i = 0; i < sz; ++i) { + if (a[i].equals(e)) + return true; + } + return false; + } + + + @Override + public void remove(T e) { + for (int i = 0; i < sz; ++i) { + if (a[i].equals(e)) { + for (int j = i + 1; j < sz; ++j) { + a[j - 1] = a[j]; + } + --sz; + break; + } + } + } + + + private class MyIteratorNestedNonstatic implements Iterator { + private int pos = 0; + + @Override + public boolean hasNext() { + return pos < sz; + } + + @Override + public T next() { + return a[pos++]; + } + } + + private static class MyIteratorNestedStatic implements Iterator { + private int pos = 0; + private ArrayList that; + + public MyIteratorNestedStatic(ArrayList that) { + this.that = that; + } + + @Override + public boolean hasNext() { + return pos < that.sz; + } + + @Override + public E next() { + return that.a[pos++]; + } + } + + @Override + public Iterator iterator() { + // con classe globale + //return new ArrayListIterator<>(this); + // con nested static + //return new MyIteratorNestedStatic<>(this); + // con nested non-static + //return new MyIteratorNestedNonstatic(); + // con anonymous class + return new Iterator() { + private int pos = 0; + + @Override + public boolean hasNext() { + return pos < sz; + } + + @Override + public T next() { + return a[pos++]; + } + }; + } + + + public static void printAll(Iterable c) { + Iterator it = c.iterator(); + while(it.hasNext()) { + T n = it.next(); + System.out.println(n); + } + } + + public static void main(String[] args) { + Iterable l = new ArrayList(); + + Iterator it = l.iterator(); + while(it.hasNext()) { + Integer n = it.next(); + System.out.println(n); + } + } + +} diff --git a/2024-25/LezioniJava24-25/src/tinyjdk/ArrayListIterator.java b/2024-25/LezioniJava24-25/src/tinyjdk/ArrayListIterator.java new file mode 100644 index 0000000..686b3c5 --- /dev/null +++ b/2024-25/LezioniJava24-25/src/tinyjdk/ArrayListIterator.java @@ -0,0 +1,21 @@ +package tinyjdk; + +public class ArrayListIterator implements Iterator { + private int pos = 0; + private ArrayList that; + + public ArrayListIterator(ArrayList that) { + this.that = that; + } + + @Override + public boolean hasNext() { + return pos < that.sz; + } + + @Override + public E next() { + return that.a[pos++]; + } +} + diff --git a/2024-25/LezioniJava24-25/src/tinyjdk/Collection.java b/2024-25/LezioniJava24-25/src/tinyjdk/Collection.java new file mode 100644 index 0000000..3e3ca3b --- /dev/null +++ b/2024-25/LezioniJava24-25/src/tinyjdk/Collection.java @@ -0,0 +1,9 @@ +package tinyjdk; + +public interface Collection extends Iterable { + void add(T e); + boolean contains(T e); + int size(); + void remove(T e); + void clear(); +} diff --git a/2024-25/LezioniJava24-25/src/tinyjdk/IndexOutOfBoundsException.java b/2024-25/LezioniJava24-25/src/tinyjdk/IndexOutOfBoundsException.java new file mode 100644 index 0000000..8f43a8d --- /dev/null +++ b/2024-25/LezioniJava24-25/src/tinyjdk/IndexOutOfBoundsException.java @@ -0,0 +1,5 @@ +package tinyjdk; + +public class IndexOutOfBoundsException extends RuntimeException { + +} diff --git a/2024-25/LezioniJava24-25/src/tinyjdk/Iterable.java b/2024-25/LezioniJava24-25/src/tinyjdk/Iterable.java new file mode 100644 index 0000000..1772ae7 --- /dev/null +++ b/2024-25/LezioniJava24-25/src/tinyjdk/Iterable.java @@ -0,0 +1,9 @@ +package tinyjdk; + +public interface Iterable { + Iterator iterator(); +} + + + + diff --git a/2024-25/LezioniJava24-25/src/tinyjdk/Iterator.java b/2024-25/LezioniJava24-25/src/tinyjdk/Iterator.java new file mode 100644 index 0000000..3f1efd3 --- /dev/null +++ b/2024-25/LezioniJava24-25/src/tinyjdk/Iterator.java @@ -0,0 +1,6 @@ +package tinyjdk; + +public interface Iterator { + boolean hasNext(); + T next(); +} diff --git a/2024-25/LezioniJava24-25/src/tinyjdk/LinkedList.java b/2024-25/LezioniJava24-25/src/tinyjdk/LinkedList.java new file mode 100644 index 0000000..731da57 --- /dev/null +++ b/2024-25/LezioniJava24-25/src/tinyjdk/LinkedList.java @@ -0,0 +1,95 @@ +package tinyjdk; + +public class LinkedList implements List { + + protected class Node { + T data; + Node next; + + Node(T data) { + this.data = data; + this.next = null; + } + } + + protected Node head; + + public LinkedList() { + head = null; + } + + @Override + public void add(T e) { + if (head == null) { + head = new Node(e); + } + else { + Node n = head; + while (n.next != null) + n = n.next; + n.next = new Node(e); + } + } + + protected Node reach(int i) { + Node n = head; + for (; n != null && i > 0; --i) + n = n.next; + if (i == 0) + return n; + throw new RuntimeException("index out of bounds"); + } + + @Override + public T get(int i) { + return reach(i).data; + } + + @Override + public void set(int i, T e) { + reach(i).data = e; + } + + @Override + public boolean contains(T e) { + // TODO da fare per casa + return false; + } + + @Override + public int size() { + // TODO + return 0; + } + + @Override + public void remove(T e) { + // TODO + } + + @Override + public void clear() { + head = null; + } + + + @Override + public Iterator iterator() { + return new Iterator() { + private Node current = head; + + @Override + public boolean hasNext() { + return current != null; + } + + @Override + public T next() { + T data = current.data; + current = current.next; + return data; + } + }; + } + +} diff --git a/2024-25/LezioniJava24-25/src/tinyjdk/List.java b/2024-25/LezioniJava24-25/src/tinyjdk/List.java new file mode 100644 index 0000000..5af03bf --- /dev/null +++ b/2024-25/LezioniJava24-25/src/tinyjdk/List.java @@ -0,0 +1,6 @@ +package tinyjdk; + +public interface List extends Collection { + T get(int i); + void set(int i, T e); +} diff --git a/2024-25/LezioniJava24-25/src/tinyjdk/Pair.java b/2024-25/LezioniJava24-25/src/tinyjdk/Pair.java new file mode 100644 index 0000000..62cbaff --- /dev/null +++ b/2024-25/LezioniJava24-25/src/tinyjdk/Pair.java @@ -0,0 +1,12 @@ +package tinyjdk; + + +public class Pair { + public final A fst; + public final B snd; + + public Pair(A a, B b) { + this.fst = a; + this.snd = b; + } +} diff --git a/2024-25/LezioniJava24-25/src/tinyjdk/Tests.java b/2024-25/LezioniJava24-25/src/tinyjdk/Tests.java new file mode 100644 index 0000000..1a2a8a2 --- /dev/null +++ b/2024-25/LezioniJava24-25/src/tinyjdk/Tests.java @@ -0,0 +1,10 @@ +package tinyjdk; + +public class Tests { + + public static void main(String[] args) { + + } + + +} diff --git a/2025-26/.gitignore b/2025-26/.gitignore new file mode 100644 index 0000000..f68d109 --- /dev/null +++ b/2025-26/.gitignore @@ -0,0 +1,29 @@ +### 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 diff --git a/2025-26/.idea/.gitignore b/2025-26/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/2025-26/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/2025-26/.idea/misc.xml b/2025-26/.idea/misc.xml new file mode 100644 index 0000000..a9182a4 --- /dev/null +++ b/2025-26/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/2025-26/.idea/modules.xml b/2025-26/.idea/modules.xml new file mode 100644 index 0000000..b6d4d12 --- /dev/null +++ b/2025-26/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/2025-26/.idea/vcs.xml b/2025-26/.idea/vcs.xml new file mode 100644 index 0000000..6c0b863 --- /dev/null +++ b/2025-26/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/2025-26/PO2_2025_26.iml b/2025-26/PO2_2025_26.iml new file mode 100644 index 0000000..c90834f --- /dev/null +++ b/2025-26/PO2_2025_26.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/2025-26/src/IterTest.java b/2025-26/src/IterTest.java new file mode 100644 index 0000000..ed057dd --- /dev/null +++ b/2025-26/src/IterTest.java @@ -0,0 +1,18 @@ +import java.util.*; + +public class IterTest { + + public static void main(String[] args) { + Collection a = new ArrayList(); + a.add(10); + a.add(245); + a.add(387); + + Iterator it = a.iterator(); + while (it.hasNext()) { + Integer n = it.next(); + System.out.println(n); + } + + } +} diff --git a/2025-26/src/Lambda.java b/2025-26/src/Lambda.java new file mode 100644 index 0000000..0ba839e --- /dev/null +++ b/2025-26/src/Lambda.java @@ -0,0 +1,174 @@ +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Random; +import java.util.function.Function; + +public class Lambda { + + @FunctionalInterface + interface Function { + R apply(T x); + } + + interface Consumer { + void accept(T x); + } + + interface Supplier { + T get(); + } + + interface Runnable { + void run(); + } + + public static void delay(int ms, Runnable r) { + try { + Thread.sleep(ms); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + r.run(); + } + + public static void iter(Collection c, Consumer p) { + for (T e : c) { + p.accept(e); + } + } + + public static List map(Collection a, Function f) { + List l = new ArrayList<>(); + for (A e : a) { + B b = f.apply(e); + l.add(b); + } + return l; + } + + public static Collection filter(Collection c, Function f) { + List l = new ArrayList<>(); + for (T e : c) { + if (f.apply(e)) + l.add(e); + } + return l; + } + + public static List generate(int n, Supplier f) { + List l = new ArrayList<>(); + for (; n > 0; n--) { + T x = f.get(); + l.add(x); + } + return l; + } + + static void f(int x) { + generate(x, () -> x); + } + + public static void main(String[] args) { + { + Runnable pippo = () -> System.out.println("ciao"); + + pippo.run(); + + + int x = 8 * 34 / 67; + + boolean y = x < 0; + + if (y) { + x = 8; + } + else { + System.out.println(x); + } + + } + + + + { + delay(1000, new Runnable() { + @Override + public void run() { + System.out.println("ciao!"); + } + }); + } + { + List u = generate(20, () -> "ciao"); + + Random rnd = new Random(); + List u2 = generate(20, () -> rnd.nextInt(100)); + + int k = rnd.nextInt(100); + List u3 = generate(20, () -> k); + } + { + List a = new ArrayList<>(); + a.add(10); + a.add(-345); + a.add(33); + Collection u = filter(a, x -> x > 0); + } + + { + List a = new ArrayList<>(); + a.add(1); + a.add(2); + a.add(3); + iter(a, new Consumer<>() { + @Override + public void accept(Integer e) { + a.add(e); + } + }); + } + { + List a = new ArrayList<>(); + a.add("pi"); + a.add("po"); + a.add("pa"); + List u = map(a, new Function<>() { + @Override + public Integer apply(String e) { + return e.length(); + } + }); + } + { + List a = new ArrayList<>(); + a.add(1); + a.add(12); + a.add(23); + List u = map(a, new Function<>() { + @Override + public Boolean apply(Integer e) { + return e % 2 == 0; + } + }); + } + { + List a = new ArrayList<>(); + a.add(1); + a.add(12); + a.add(23); + List u = map(a, new Function<>() { + @Override + public Integer apply(Integer e) { + return (int) Math.sqrt(e); + } + }); + List u2 = map(a, x -> x + 1); + + + } + + } + + +} diff --git a/2025-26/src/Sorting.java b/2025-26/src/Sorting.java new file mode 100644 index 0000000..e75b6ac --- /dev/null +++ b/2025-26/src/Sorting.java @@ -0,0 +1,72 @@ +import tinyjdk.dais.unive.it.ArrayList; + +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +public class Sorting { + + public static class Piatto implements Comparable { + private List ingredienti; + + public Piatto(List ingredienti) { + this.ingredienti = ingredienti; + } + + @Override + public int compareTo(Piatto o) { + return ingredienti.size() - o.ingredienti.size(); + } + + public int numero_ingredienti() { return ingredienti.size(); } + } + + public static class PiattoVegano extends Piatto { + private int costo; + + public PiattoVegano(List ingredienti, int costo) { + super(ingredienti); + for (String s : ingredienti) { + assert(isVegan(s)); + } + this.costo = costo; + } + + public static boolean isVegan(String s) { return true; } + + @Override + public int compareTo(Piatto o) { + if (o instanceof PiattoVegano) + return costo - ((PiattoVegano) o).costo; + else return -1; + } + + } + + public static void main(String[] args) { + { + Piatto carbonara = new Piatto(List.of("uova", "guanciale", "pecorino romano", "pasta")); + Piatto polloArrosto = new Piatto(List.of("pollo", "olio", "rosmarino", "patate")); + Piatto frittura = new Piatto(List.of("calamari", "gamberetti", "totani", "schie", "seppioline")); + List l = List.of(carbonara, polloArrosto, frittura); + Collections.sort(l); + } + + { + List l = List.of(45, 78, 234, -456, 2); + + Collections.sort(l, (a, b) -> a - b); + } + { + Zoo.Animal fido = new Zoo.Animal(40); + Zoo.Animal gigio = new Zoo.Animal(5); + Zoo.Animal pippo = new Zoo.Animal(140); + Zoo.Animal pluto = new Zoo.Animal(12); + List l = List.of(fido, gigio, pippo, pluto); + + Collections.sort(l, (a1, a2) -> a2.weight - a1.weight); + + } + } + +} diff --git a/2025-26/src/Zoo.java b/2025-26/src/Zoo.java new file mode 100644 index 0000000..69c3e7b --- /dev/null +++ b/2025-26/src/Zoo.java @@ -0,0 +1,85 @@ + + +/*struct S { + int n; + float x; +} + +struct U { + S parent; + char* s; +} + +void f(S this) { + if (this.n > 5) +} + +int m(U this) { return this.parent.n + strlen(this.s) } + + +public class S { + public int n; + public float x; + + public void f() { + if (this.n > 5) { ... } + } +} + +public class U extends S { + public String s; + public int m() { return n + s.length(); } + +} +*/ + + +public class Zoo { + public static class Animal { + protected int weight; + + public Animal(int weight) { + this.weight = weight; + } + + public void eat(Animal a) { + this.weight += a.weight; + } + } + + public static class Dog extends Animal { + private String hair; + + public Dog(int weight, String hair) { + super(weight); + this.hair = hair; + } + + @Override + public void eat(Animal a) { + this.weight += a.weight / 3; + } + + public String getHair() { return hair;} + } + + public static class Cat extends Animal { + public Cat(int weight) { + super(weight); + } + + public void eat(Animal a) { + this.weight += a.weight * 3; + } + } + + public static void main(String[] args) { + Animal pippo = new Dog(5, "liscio"); + Dog gigio = new Dog(7, "riccio"); + pippo.eat(gigio); + + Animal romeo = new Cat(40); + romeo.eat(gigio); + + } +} \ No newline at end of file diff --git a/2025-26/src/tinyjdk/dais/unive/it/ArrayList.java b/2025-26/src/tinyjdk/dais/unive/it/ArrayList.java new file mode 100644 index 0000000..d5e246c --- /dev/null +++ b/2025-26/src/tinyjdk/dais/unive/it/ArrayList.java @@ -0,0 +1,76 @@ +package tinyjdk.dais.unive.it; + +public class ArrayList implements List { + private T[] a; + private int sz; + + public ArrayList() { + clear(); + } + + @Override + public void add(T o) { + if (sz >= a.length) { + T[] newa = (T[]) new Object[a.length * 2]; + for (int i = 0; i < a.length; i++) + newa[i] = a[i]; + a = newa; + } + a[sz++] = o; + } + + @Override + public boolean contains(T o) { + for (int i = 0; i < sz; i++) { + T e = a[i]; + if (e.equals(o)) return true; + } + return false; + } + + @Override + public int size() { + return sz; + } + + @Override + public void remove(T o) { + // TODO + } + + @Override + public void clear() { + a = (T[]) new Object[100]; + sz = 0; + } + + @Override + public T get(int i) { + if (i >= 0 && i < sz) + return a[i]; + throw new RuntimeException(); + } + + @Override + public void set(int i, T e) { + if (i >= 0 && i < sz) + a[i] = e; + throw new RuntimeException(); + } + + + /*private class MyIterator implements Iterator { + private int pos = 0; + + @Override + public boolean hasNext() { + return pos < sz; + } + + @Override + public T next() { + return a[pos++]; + } + }*/ + +} diff --git a/2025-26/src/tinyjdk/dais/unive/it/Collection.java b/2025-26/src/tinyjdk/dais/unive/it/Collection.java new file mode 100644 index 0000000..821b3d9 --- /dev/null +++ b/2025-26/src/tinyjdk/dais/unive/it/Collection.java @@ -0,0 +1,13 @@ +package tinyjdk.dais.unive.it; + +public interface Collection extends Iterable { + void add(T o); + boolean contains(T o); + int size(); + void remove(T o); + void clear(); + + default boolean isEmpty() { + return size() == 0; + } +} diff --git a/2025-26/src/tinyjdk/dais/unive/it/Iterable.java b/2025-26/src/tinyjdk/dais/unive/it/Iterable.java new file mode 100644 index 0000000..247b2e5 --- /dev/null +++ b/2025-26/src/tinyjdk/dais/unive/it/Iterable.java @@ -0,0 +1,5 @@ +package tinyjdk.dais.unive.it; + +public interface Iterable { + Iterator iterator(); +} diff --git a/2025-26/src/tinyjdk/dais/unive/it/Iterator.java b/2025-26/src/tinyjdk/dais/unive/it/Iterator.java new file mode 100644 index 0000000..fb64eb4 --- /dev/null +++ b/2025-26/src/tinyjdk/dais/unive/it/Iterator.java @@ -0,0 +1,6 @@ +package tinyjdk.dais.unive.it; + +public interface Iterator { + boolean hasNext(); + T next(); +} diff --git a/2025-26/src/tinyjdk/dais/unive/it/LinkedList.java b/2025-26/src/tinyjdk/dais/unive/it/LinkedList.java new file mode 100644 index 0000000..be99534 --- /dev/null +++ b/2025-26/src/tinyjdk/dais/unive/it/LinkedList.java @@ -0,0 +1,106 @@ +package tinyjdk.dais.unive.it; + +public class LinkedList implements List { + + /* + struct node { + int data; + struct node* next; + } + */ + + private class Node { + T data; + Node next; + + public Node(T data) { + this.data = data; + this.next = null; + } + } + + private Node head = null; + + public LinkedList() { + } + + @Override + public void add(T e) { + if (head == null) + head = new Node(e); + else { + Node n = head; + while (n != null) { + n = n.next; + } + n = new Node(e); + } + } + + @Override + public int size() { + int cnt = 0; + for (Node n = head; n != null; ++cnt, n = n.next); + return cnt; + } + + + private Node seek(int i) { + assert (i >= 0); + Node n = head; + for (; i-- > 0; n = n.next) { + if (n.next == null) + throw new RuntimeException(); + } + return n; + } + + @Override + public T get(int i) { + return seek(i).data; + } + + @Override + public void set(int i, T e) { + seek(i).data = e; + } + + @Override + public boolean contains(T o) { + Node n = head; + while (n != null) { + if (n.data.equals(o)) return true; + n = n.next; + } + return false; + } + + @Override + public void remove(T o) { + // TODO + } + + @Override + public void clear() { + head = null; + } + + @Override + public Iterator iterator() { + return new Iterator() { + private Node current = head; + + @Override + public boolean hasNext() { + return current != null; + } + + @Override + public T next() { + T r = current.data; + current = current.next; + return r; + } + }; + } +} diff --git a/2025-26/src/tinyjdk/dais/unive/it/List.java b/2025-26/src/tinyjdk/dais/unive/it/List.java new file mode 100644 index 0000000..9e6eef5 --- /dev/null +++ b/2025-26/src/tinyjdk/dais/unive/it/List.java @@ -0,0 +1,22 @@ +package tinyjdk.dais.unive.it; + +public interface List extends Collection { + T get(int index); + void set(int index, T element); + + default Iterator iterator() { + return new Iterator() { + private int pos = 0; + + @Override + public boolean hasNext() { + return pos < size(); + } + + @Override + public T next() { + return get(pos++); + } + }; + } +} diff --git a/2025-26/src/tinyjdk/dais/unive/it/ListMap.java b/2025-26/src/tinyjdk/dais/unive/it/ListMap.java new file mode 100644 index 0000000..7b5bf3b --- /dev/null +++ b/2025-26/src/tinyjdk/dais/unive/it/ListMap.java @@ -0,0 +1,49 @@ +package tinyjdk.dais.unive.it; + +public class ListMap implements Map { + private List> l; + + public ListMap() { + l = new ArrayList<>(); + } + + @Override + public void put(K key, V value) { + l.add(new Map.Pair<>(key, value)); + } + + @Override + public V get(K key) { + Iterator> it = l.iterator(); + while (it.hasNext()) { + Map.Pair p = it.next(); + if (p.key.equals(key)) { + return p.value; + } + } + throw new RuntimeException("key not found"); + } + + @Override + public int size() { + return l.size(); + } + + @Override + public boolean containsKey(K key) { + Iterator> it = l.iterator(); + while (it.hasNext()) { + Map.Pair p = it.next(); + if (p.key.equals(key)) { + return true; + } + } + return false; + } + + @Override + public Iterator> iterator() { + return l.iterator(); + } + +} diff --git a/2025-26/src/tinyjdk/dais/unive/it/Map.java b/2025-26/src/tinyjdk/dais/unive/it/Map.java new file mode 100644 index 0000000..0fd1720 --- /dev/null +++ b/2025-26/src/tinyjdk/dais/unive/it/Map.java @@ -0,0 +1,21 @@ +package tinyjdk.dais.unive.it; + +public interface Map extends Iterable> { + + class Pair { + public final K key; + public final V value; + public Pair(K key, V value) { + this.key = key; + this.value = value; + } + } + + void put(K key, V value); + V get(K key); + int size(); + + default boolean isEmpty() { return size() == 0; } + + boolean containsKey(K key); +} diff --git a/2025-26/src/tinyjdk/dais/unive/it/Test.java b/2025-26/src/tinyjdk/dais/unive/it/Test.java new file mode 100644 index 0000000..0beb209 --- /dev/null +++ b/2025-26/src/tinyjdk/dais/unive/it/Test.java @@ -0,0 +1,21 @@ +package tinyjdk.dais.unive.it; + + + +public class Test { + public static void main(String[] args) { + } + + public static void foo(Collection c) { + c.add(1); + c.add(62); + c.add(234); + + Iterator it = c.iterator(); + while (it.hasNext()) { + Integer e = it.next(); + System.out.println(e); + } + + } +} diff --git a/soluzione appelli/Scritto PO2 1 6 23/Scritto PO2 13 1 2023.iml b/soluzione appelli/Scritto PO2 1 6 23/Scritto PO2 13 1 2023.iml new file mode 100644 index 0000000..908ad4f --- /dev/null +++ b/soluzione appelli/Scritto PO2 1 6 23/Scritto PO2 13 1 2023.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 1 6 23/cpp/Appello_1_6_23.sln b/soluzione appelli/Scritto PO2 1 6 23/cpp/Appello_1_6_23.sln new file mode 100644 index 0000000..8420566 --- /dev/null +++ b/soluzione appelli/Scritto PO2 1 6 23/cpp/Appello_1_6_23.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.3.32901.215 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Appello_1_6_2023", "Appello_1_6_23.vcxproj", "{6A49BB9B-DE9D-46D5-BB18-BD13737F5026}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {6A49BB9B-DE9D-46D5-BB18-BD13737F5026}.Debug|x64.ActiveCfg = Debug|x64 + {6A49BB9B-DE9D-46D5-BB18-BD13737F5026}.Debug|x64.Build.0 = Debug|x64 + {6A49BB9B-DE9D-46D5-BB18-BD13737F5026}.Debug|x86.ActiveCfg = Debug|Win32 + {6A49BB9B-DE9D-46D5-BB18-BD13737F5026}.Debug|x86.Build.0 = Debug|Win32 + {6A49BB9B-DE9D-46D5-BB18-BD13737F5026}.Release|x64.ActiveCfg = Release|x64 + {6A49BB9B-DE9D-46D5-BB18-BD13737F5026}.Release|x64.Build.0 = Release|x64 + {6A49BB9B-DE9D-46D5-BB18-BD13737F5026}.Release|x86.ActiveCfg = Release|Win32 + {6A49BB9B-DE9D-46D5-BB18-BD13737F5026}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {66CDDA76-E424-4DD8-87CF-E87E03399139} + EndGlobalSection +EndGlobal diff --git a/soluzione appelli/Scritto PO2 1 6 23/cpp/Appello_1_6_23.vcxproj b/soluzione appelli/Scritto PO2 1 6 23/cpp/Appello_1_6_23.vcxproj new file mode 100644 index 0000000..eb5e9c9 --- /dev/null +++ b/soluzione appelli/Scritto PO2 1 6 23/cpp/Appello_1_6_23.vcxproj @@ -0,0 +1,137 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 16.0 + Win32Proj + {6A49BB9B-DE9D-46D5-BB18-BD13737F5026} + Appello13 + 10.0 + Appello_1_6_23 + + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + + + + + + + + + + + + + + + + + + + + Level3 + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + Level3 + true + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + stdcpp20 + + + Console + true + + + + + Level3 + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 1 6 23/cpp/Appello_1_6_23.vcxproj.user b/soluzione appelli/Scritto PO2 1 6 23/cpp/Appello_1_6_23.vcxproj.user new file mode 100644 index 0000000..88a5509 --- /dev/null +++ b/soluzione appelli/Scritto PO2 1 6 23/cpp/Appello_1_6_23.vcxproj.user @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 1 6 23/cpp/pair.ixx b/soluzione appelli/Scritto PO2 1 6 23/cpp/pair.ixx new file mode 100644 index 0000000..73a6d3b --- /dev/null +++ b/soluzione appelli/Scritto PO2 1 6 23/cpp/pair.ixx @@ -0,0 +1,116 @@ +export module pairs; + +import ; +import ; + + +export +template +class pair +{ + template friend class pair; // necessario per il copy constructor templatizzato + +private: + A first; + B second; + +public: + // 2.a + pair() : first(), second() {} + pair(const A& a, const B& b) : first(a), second(b) {} + pair(const pair& p) : first(p.first), second(p.second) {} + + pair& operator=(const pair& p) + { + first = p.first; + second = p.second; + return *this; + } + + // 2.c + template + pair(const pair& p) : first(p.first), second(p.second) {} + + + // 2.b + pair operator++(int) + { + pair tmp(*this); + first++; + second++; + return tmp; + } + + pair& operator++() + { + ++first; + ++second; + return *this; + } + + bool operator==(const pair& p) const + { + return first == p.first && second == p.second; + } + + bool operator!=(const pair& p) const + { + return !(*this == p); + } + + // altri operatori aritmentici ed in-place sono analoghi + pair operator+(const pair& p) const + { + return pair(first + p.first, second + p.second); + } + + pair& operator+=(const pair& p) + { + first += p.first; + second += p.second; + return *this; + } + + const A& fst() const + { + return first; + } + + A& fst() + { + return first; + } + + const B& snd() const + { + return second; + } + + B& snd() + { + return second; + } + +}; + + +export int main() +{ + pair p1(4, 5); + pair p2(p1); + + pair p3("ciao", true); + pair p4(p1); + + p1 = p2; + + int n = p1.fst(); + p1.snd() = p1.snd() * 3; + p4 += p1; // converte implicitamente il RV in un pair tramite un conversion copy-constructor templatizzato + + return 0; +} + + + + diff --git a/soluzione appelli/Scritto PO2 1 6 23/java/.gitignore b/soluzione appelli/Scritto PO2 1 6 23/java/.gitignore new file mode 100644 index 0000000..f68d109 --- /dev/null +++ b/soluzione appelli/Scritto PO2 1 6 23/java/.gitignore @@ -0,0 +1,29 @@ +### 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 diff --git a/soluzione appelli/Scritto PO2 1 6 23/java/.idea/.gitignore b/soluzione appelli/Scritto PO2 1 6 23/java/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/soluzione appelli/Scritto PO2 1 6 23/java/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/soluzione appelli/Scritto PO2 1 6 23/java/.idea/misc.xml b/soluzione appelli/Scritto PO2 1 6 23/java/.idea/misc.xml new file mode 100644 index 0000000..d15472f --- /dev/null +++ b/soluzione appelli/Scritto PO2 1 6 23/java/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 1 6 23/java/.idea/modules.xml b/soluzione appelli/Scritto PO2 1 6 23/java/.idea/modules.xml new file mode 100644 index 0000000..2352219 --- /dev/null +++ b/soluzione appelli/Scritto PO2 1 6 23/java/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 1 6 23/java/.idea/uiDesigner.xml b/soluzione appelli/Scritto PO2 1 6 23/java/.idea/uiDesigner.xml new file mode 100644 index 0000000..2b63946 --- /dev/null +++ b/soluzione appelli/Scritto PO2 1 6 23/java/.idea/uiDesigner.xml @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 1 6 23/java/Scritto PO2 1_6_23.iml b/soluzione appelli/Scritto PO2 1 6 23/java/Scritto PO2 1_6_23.iml new file mode 100644 index 0000000..eda5e59 --- /dev/null +++ b/soluzione appelli/Scritto PO2 1 6 23/java/Scritto PO2 1_6_23.iml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 1 6 23/java/src/Es1.java b/soluzione appelli/Scritto PO2 1 6 23/java/src/Es1.java new file mode 100644 index 0000000..ffa4e3f --- /dev/null +++ b/soluzione appelli/Scritto PO2 1 6 23/java/src/Es1.java @@ -0,0 +1,119 @@ +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.*; +import java.util.function.Function; +import java.util.function.Supplier; + +public class Es1 { + + // NOTA: la classe è statica solamente perché è nested per praticità + public static class BST implements Iterable { + @NotNull + protected final Comparator cmp; + @Nullable + protected Node root; + + public BST(@NotNull Comparator cmp) { + this.cmp = cmp; + } + + public void insert(@NotNull T x) { + root = insertRec(root, x); + } + + // 1.a + @NotNull + protected Node insertRec(@Nullable Node n, @NotNull T x) { + if (n == null) + return new Node(x); + int r = cmp.compare(x, n.data); + if (r < 0) + n.left = insertRec(n.left, x); + else if (r > 0) + n.right = insertRec(n.right, x); + return n; + } + + // 1.b.i + protected void dfsInOrder(@Nullable Node n, @NotNull Collection out) { + if (n != null) { + dfsInOrder(n.left, out); + out.add(n.data); + dfsInOrder(n.right, out); + } + } + + // 1.b.ii + @NotNull + @Override + public Iterator iterator() { + Collection c = new ArrayList<>(); + dfsInOrder(root, c); + return c.iterator(); + } + + // 1.c + @Nullable + public T min() { + if (root == null) return null; + Node n = root; + while(n.left != null) n = n.left; + return n.data; + } + + @Nullable + public T max() { + if (root == null) return null; + Node n = root; + while(n.right != null) n = n.right; + return n.data; + } + + + protected class Node { + @NotNull + private final T data; + @Nullable + protected Node left, right; + + protected Node(@NotNull T data, @Nullable Node left, @Nullable Node right) { + this.data = data; + this.left = left; + this.right = right; + } + + protected Node(@NotNull T data) { + this(data, null, null); + } + } + + @Override + @NotNull + public String toString() { + StringBuilder sb = new StringBuilder(); + for (T x : this) { + sb.append(x); + sb.append(" "); + } + return sb.toString(); + } + } + + // 1.d + public static class BST2> extends BST { + public BST2() { + super(Comparable::compareTo); + } + } + + public static void main(String[] args) { + BST t = new BST2<>(); + Random rnd = new Random(); + for (int i = 0; i < 20; ++i) + t.insert(rnd.nextInt(100)); + System.out.println(t); + System.out.printf("min = %d\nmax = %d\n", t.min(), t.max()); + } + +} \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 1 7 22/.idea/.gitignore b/soluzione appelli/Scritto PO2 1 7 22/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/soluzione appelli/Scritto PO2 1 7 22/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/soluzione appelli/Scritto PO2 1 7 22/.idea/misc.xml b/soluzione appelli/Scritto PO2 1 7 22/.idea/misc.xml new file mode 100644 index 0000000..09e91bf --- /dev/null +++ b/soluzione appelli/Scritto PO2 1 7 22/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 1 7 22/.idea/modules.xml b/soluzione appelli/Scritto PO2 1 7 22/.idea/modules.xml new file mode 100644 index 0000000..b8e82d1 --- /dev/null +++ b/soluzione appelli/Scritto PO2 1 7 22/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 1 7 22/.idea/vcs.xml b/soluzione appelli/Scritto PO2 1 7 22/.idea/vcs.xml new file mode 100644 index 0000000..b2bdec2 --- /dev/null +++ b/soluzione appelli/Scritto PO2 1 7 22/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 1 7 22/Scritto PO2 1 7 22.iml b/soluzione appelli/Scritto PO2 1 7 22/Scritto PO2 1 7 22.iml new file mode 100644 index 0000000..2c505e4 --- /dev/null +++ b/soluzione appelli/Scritto PO2 1 7 22/Scritto PO2 1 7 22.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 1 7 22/cpp/Appello_1_7_22/Appello_1_7_22.sln b/soluzione appelli/Scritto PO2 1 7 22/cpp/Appello_1_7_22/Appello_1_7_22.sln new file mode 100644 index 0000000..a7d5c81 --- /dev/null +++ b/soluzione appelli/Scritto PO2 1 7 22/cpp/Appello_1_7_22/Appello_1_7_22.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.2.32526.322 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Appello_1_7_22", "Appello_1_7_22.vcxproj", "{134AAFA0-F15F-4F91-B364-962161EC5D7F}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {134AAFA0-F15F-4F91-B364-962161EC5D7F}.Debug|x64.ActiveCfg = Debug|x64 + {134AAFA0-F15F-4F91-B364-962161EC5D7F}.Debug|x64.Build.0 = Debug|x64 + {134AAFA0-F15F-4F91-B364-962161EC5D7F}.Debug|x86.ActiveCfg = Debug|Win32 + {134AAFA0-F15F-4F91-B364-962161EC5D7F}.Debug|x86.Build.0 = Debug|Win32 + {134AAFA0-F15F-4F91-B364-962161EC5D7F}.Release|x64.ActiveCfg = Release|x64 + {134AAFA0-F15F-4F91-B364-962161EC5D7F}.Release|x64.Build.0 = Release|x64 + {134AAFA0-F15F-4F91-B364-962161EC5D7F}.Release|x86.ActiveCfg = Release|Win32 + {134AAFA0-F15F-4F91-B364-962161EC5D7F}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {49DE568A-D54C-485E-A095-5948A84AED91} + EndGlobalSection +EndGlobal diff --git a/soluzione appelli/Scritto PO2 1 7 22/cpp/Appello_1_7_22/Appello_1_7_22.vcxproj b/soluzione appelli/Scritto PO2 1 7 22/cpp/Appello_1_7_22/Appello_1_7_22.vcxproj new file mode 100644 index 0000000..e1e2235 --- /dev/null +++ b/soluzione appelli/Scritto PO2 1 7 22/cpp/Appello_1_7_22/Appello_1_7_22.vcxproj @@ -0,0 +1,136 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 16.0 + Win32Proj + {134aafa0-f15f-4f91-b364-962161ec5d7f} + Appello3622 + 10.0 + + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + + + + + + + + + + + + + + + + + + + + Level3 + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + Level4 + true + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + stdcpp14 + + + Console + true + + + + + Level3 + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 1 7 22/cpp/Appello_1_7_22/Appello_1_7_22.vcxproj.user b/soluzione appelli/Scritto PO2 1 7 22/cpp/Appello_1_7_22/Appello_1_7_22.vcxproj.user new file mode 100644 index 0000000..88a5509 --- /dev/null +++ b/soluzione appelli/Scritto PO2 1 7 22/cpp/Appello_1_7_22/Appello_1_7_22.vcxproj.user @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 1 7 22/cpp/Appello_1_7_22/Appello_3_6_22.vcxproj.filters b/soluzione appelli/Scritto PO2 1 7 22/cpp/Appello_1_7_22/Appello_3_6_22.vcxproj.filters new file mode 100644 index 0000000..7676feb --- /dev/null +++ b/soluzione appelli/Scritto PO2 1 7 22/cpp/Appello_1_7_22/Appello_3_6_22.vcxproj.filters @@ -0,0 +1,22 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 1 7 22/cpp/Appello_1_7_22/Appello_3_6_22.vcxproj.user b/soluzione appelli/Scritto PO2 1 7 22/cpp/Appello_1_7_22/Appello_3_6_22.vcxproj.user new file mode 100644 index 0000000..88a5509 --- /dev/null +++ b/soluzione appelli/Scritto PO2 1 7 22/cpp/Appello_1_7_22/Appello_3_6_22.vcxproj.user @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 1 7 22/cpp/Appello_1_7_22/Es3.cpp b/soluzione appelli/Scritto PO2 1 7 22/cpp/Appello_1_7_22/Es3.cpp new file mode 100644 index 0000000..f5f1be8 --- /dev/null +++ b/soluzione appelli/Scritto PO2 1 7 22/cpp/Appello_1_7_22/Es3.cpp @@ -0,0 +1,186 @@ + +// Questo sorgente contiene le soluzioni dell'esame scritto di PO2 del 1/7/2022 per ciò che riguarda il quesito 3, ovvero la domanda che coinvolge C++. +// I quesiti 1-2 riguardanti Java sono in un progetto IntelliJ a parte, non qui. +// Il codice qui esposto è C++14 per qualche piccolo particolare, ma in gran parte è essenzialmente vanilla. + +#include +#include + +template +class smart_ptr +{ +private: + T* pt; + ptrdiff_t offset; + bool is_array; + + using counter_t = unsigned short; + + counter_t* cnt; + + void dec() + { + if (cnt != nullptr && --(*cnt) == 0) + { + if (pt != nullptr) // se non punta a nulla non c'è niente da liberare + { + if (is_array) delete pt; + else delete [] pt; + } + delete cnt; + } + } + + void inc() + { + if (cnt != nullptr) ++(*cnt); + } + +public: + using value_type = T; + + smart_ptr() : pt(nullptr), offset(0), is_array(false), cnt(nullptr) {} + + explicit smart_ptr(T* pt_, bool is_array_ = false) : pt(pt_), offset(0), is_array(is_array_), cnt(new counter_t(1)) {} + + smart_ptr(const smart_ptr& p) : pt(p.pt), offset(p.offset), is_array(p.is_array), cnt(p.cnt) + { + inc(); + } + + ~smart_ptr() + { + dec(); + } + + smart_ptr& operator=(const smart_ptr& p) + { + dec(); + pt = p.pt; + cnt = p.cnt; + offset = p.offset; + is_array = p.is_array; + inc(); + return *this; + } + + // subscript + // l'operatore di subscript è l'unica implementazione reale; tutti gli altri operatori sono implementati in funzione di questo + // questo approccio è poco error-prone perché concentra solamente qui il calcolo esatto dell'indirizzo usando l'offset + // in altre parole, l'operatore di subscript funge da API interna a basso livello; tutto il resto è costruito sopra di essa + const T& operator[](size_t i) const + { + return pt[offset + i]; + } + T& operator[](size_t i) + { + // capita spesso che l'implementazione const e l'implementazione non-const siano identiche + // in questi casi è necessario duplicare il codice, che è una pratica inelegante ed error-prone + // questo trucco sfrutta un giro di const cast per rimandare questa implementazione a quella const appena sopra, che è l'unica che implementiamo davvero + // ATTENZIONE: tutto questo NON è richiesto dal tema d'esame, lo mostriamo solamente a scopo didattico per insegnare una tecnica avanzata di non-duplicazione del codice + return const_cast(const_cast&>(*this).operator[](i)); + } + + // de-reference + const T& operator*() const + { + // usa l'operatore di subscript + return pt[0]; + } + T& operator*() + { + // stessa tecnica per non duplicare: chiamiamo la versione const di questo operatore definita qui sopra, che è l'unica che implementiamo davvero + return const_cast(const_cast&>(*this).operator*()); + } + + // field access + const T* operator->() const + { + // anche questa implementazione sfrutta altri operatori scritti sopra: in particolare usa de-reference che a sua volta usa il subscript, in questo modo non richiede manutenzione + return &*(*this); + // ^ + // si faccia attenzione a un particolare: solo l'operatore * indicato dalla freccetta invoca l'overload definito da noi + // il de-reference di this dentro le parentesi tonde e l'operatore & più esterno invocano gli operatori nativi di C++, non i nostri overload + } + T* operator->() + { + // altro uso della tecnica avanzata per non duplicare l'implementazione non-const + // cerchiamo di capirla: lo scopo è chiamare l'implementazione const di questo operatore senza duplicare il codice + // 1) trasformiamo *this (che in questo scope è di tipo smart_ptr&) in un const smart_ptr& + // 2) ora che *this è castato a const, invochiamo l'operatore o il metodo che ci interessa: la risoluzione dell'overload risolverà l'implementazione const, non farà una ricorsione! + // 3) siccome stiamo invocando la versione const, il risultato è const: ma il nostro tipo di ritorno deve essere un T* non-const, pertanto bisogna const-castare per TOGLIERE il const + return const_cast(const_cast&>(*this).operator->()); + } + + // plus + smart_ptr& operator+=(ptrdiff_t off) + { + offset += off; + return *this; + } + smart_ptr operator+(ptrdiff_t off) const + { + // questa implementazione usa il copy-constructor e l'operator+= definito qui sopra + return smart_ptr(*this) += off; + } + + // minus + smart_ptr& operator-=(ptrdiff_t off) + { + offset -= off; // analogo al += + return *this; + } + smart_ptr operator-(ptrdiff_t off) + { + return smart_ptr(*this) -= off; + } + + // pre + smart_ptr& operator++() + { + // questa implementazione usa l'operator+= e basta + return *this += 1; + } + smart_ptr& operator--() + { + return *this -= 1; // analogo al ++ ma usa il -= + } + + // post + smart_ptr operator++(int) + { + smart_ptr r(*this); // copia + ++(*this); // pre-incrementa this: usiamo il pre-incremento affinché questa implementazione dipenda totalmente dall'implementazione di operator++ + return r; // ritorna la copia + } + smart_ptr operator--(int) + { + smart_ptr r(*this); + --(*this); // analogo a ++ + return r; + } + +}; + +using std::string; + +int main() +{ + int* a = new int[5]; + smart_ptr a1(a, true), a2; + a2 = a1 + 10; + a1 -= 3; + a1 = ++a1 - *a2-- + a1[3]; + + smart_ptr b(new double[10], true); + for (unsigned int i = 0; i < 10; ++i) + b++; + + string* sp = new string("ciao"); + smart_ptr s1(sp), s2; + s2 = s1; + size_t i = s2->find('a', 0); + + + +} diff --git a/soluzione appelli/Scritto PO2 1 7 22/java/Appello_1_7_22/.idea/.gitignore b/soluzione appelli/Scritto PO2 1 7 22/java/Appello_1_7_22/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/soluzione appelli/Scritto PO2 1 7 22/java/Appello_1_7_22/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/soluzione appelli/Scritto PO2 1 7 22/java/Appello_1_7_22/.idea/.name b/soluzione appelli/Scritto PO2 1 7 22/java/Appello_1_7_22/.idea/.name new file mode 100644 index 0000000..f5d0f17 --- /dev/null +++ b/soluzione appelli/Scritto PO2 1 7 22/java/Appello_1_7_22/.idea/.name @@ -0,0 +1 @@ +Es1.java \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 1 7 22/java/Appello_1_7_22/.idea/misc.xml b/soluzione appelli/Scritto PO2 1 7 22/java/Appello_1_7_22/.idea/misc.xml new file mode 100644 index 0000000..3e5ccef --- /dev/null +++ b/soluzione appelli/Scritto PO2 1 7 22/java/Appello_1_7_22/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 1 7 22/java/Appello_1_7_22/.idea/modules.xml b/soluzione appelli/Scritto PO2 1 7 22/java/Appello_1_7_22/.idea/modules.xml new file mode 100644 index 0000000..d98a9cf --- /dev/null +++ b/soluzione appelli/Scritto PO2 1 7 22/java/Appello_1_7_22/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 1 7 22/java/Appello_1_7_22/.idea/uiDesigner.xml b/soluzione appelli/Scritto PO2 1 7 22/java/Appello_1_7_22/.idea/uiDesigner.xml new file mode 100644 index 0000000..2b63946 --- /dev/null +++ b/soluzione appelli/Scritto PO2 1 7 22/java/Appello_1_7_22/.idea/uiDesigner.xml @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 1 7 22/java/Appello_1_7_22/.idea/vcs.xml b/soluzione appelli/Scritto PO2 1 7 22/java/Appello_1_7_22/.idea/vcs.xml new file mode 100644 index 0000000..4fce1d8 --- /dev/null +++ b/soluzione appelli/Scritto PO2 1 7 22/java/Appello_1_7_22/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 1 7 22/java/Appello_1_7_22/Appello_1_7_22.iml b/soluzione appelli/Scritto PO2 1 7 22/java/Appello_1_7_22/Appello_1_7_22.iml new file mode 100644 index 0000000..0181b11 --- /dev/null +++ b/soluzione appelli/Scritto PO2 1 7 22/java/Appello_1_7_22/Appello_1_7_22.iml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 1 7 22/java/Appello_1_7_22/src/Es1.java b/soluzione appelli/Scritto PO2 1 7 22/java/Appello_1_7_22/src/Es1.java new file mode 100644 index 0000000..650b7e3 --- /dev/null +++ b/soluzione appelli/Scritto PO2 1 7 22/java/Appello_1_7_22/src/Es1.java @@ -0,0 +1,50 @@ + +// Questo sorgente contiene le soluzioni dell'esame scritto di PO2 del 1/7/2022 per ciò che riguarda i quesiti 1-2, ovvero le domande che coinvolgono Java. +// Il quesito 3 riguardante C++ è in un progetto Visual Studio a parte, non qui. +// Il codice qui esposto è Java 8+. + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.function.Function; + +public class Es1 { + + // 1.a + public interface Predicate extends Function {} + + // 1.b + public interface Either { + T onSuccess(T x); + void onFailure(T x) throws Exception; + } + + // 1.c + public static class SkippableArrayList extends ArrayList { + public Iterator iterator(Predicate p, Either f) { + final Iterator it = super.iterator(); // può anche essere un campo privato della anonymous class + return new Iterator() { + @Override + public boolean hasNext() { + return it.hasNext(); + } + + @Override + public E next() { + E x = it.next(); + if (p.apply(x)) + return f.onSuccess(x); + else { + try { + f.onFailure(x); + } + catch (Exception e) { + e.printStackTrace(); // si può anche non fare niente dentro il catch, è indifferente + } + return x; + } + } + }; + } + } + +} diff --git a/soluzione appelli/Scritto PO2 1 7 22/java/Appello_1_7_22/src/Es2.java b/soluzione appelli/Scritto PO2 1 7 22/java/Appello_1_7_22/src/Es2.java new file mode 100644 index 0000000..f2a7461 --- /dev/null +++ b/soluzione appelli/Scritto PO2 1 7 22/java/Appello_1_7_22/src/Es2.java @@ -0,0 +1,145 @@ +import org.jetbrains.annotations.NotNull; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.function.Function; + +public class Es2 { + + // 2.a + public static class FiboSequence implements Iterable { + + private final int len; + + public FiboSequence(int len) { + this.len = len; + } + + // questo metodo potrebbe essere static perché non usa nessun membro dell'oggetto + // tuttavia lo definiamo non-static così possiamo overridarlo nella sottoclasse + protected int fib(int n) { + return n < 2 ? 1 : fib(n - 1) + fib(n - 2); + } + + @Override + public Iterator iterator() { + return new Iterator<>() { + private int i = 0; + + @Override + public boolean hasNext() { + return i < len; + } + + @Override + public Integer next() { + return fib(i++); + } + }; + } + } + + // 2.b + // anziché definire una classe a sé stante, facciamo una cosa più elegante (sebbene non richiesta dal testo d'esame) + // definiamo una sottoclasse che overrida solamente il metodo fib() e reimplementa fibonacci con la cache + // l'iteratore senza saperlo invocherà questo override quando chiama fib() + public static class CachedFiboSequence extends FiboSequence { + + @NotNull + private final Map cache; + + // questo costruttore serve alle sottoclasso per passare una certa istanza di cache + protected CachedFiboSequence(@NotNull Map cache, int len) { + super(len); + this.cache = cache; + } + + // questo costruttore costruisce una cache nuova per ogni istanza + public CachedFiboSequence(int len) { + this(new HashMap<>(), len); + } + + // questo override calcola fibonacci usando la cache ricorsivamente + @Override + protected int fib(int n) { + if (n < 2) return 1; // non è necessario fare caching anche dei 2 casi base + else { + Integer r = cache.get(n); + if (r == null) { + r = fib(n - 1) + fib(n - 2); // questa è una ricorsione in dynamic dispatch + cache.put(n, r); + } + return r; + } + } + } + + // 2.c + public static class GlobalCachedFiboSequence extends CachedFiboSequence { + + // inizializziamo questa cache statica; poi passiamo al supercostruttore sempre questo campo + // così tutte le istanze useranno sempre la stessa hashmap senza saperlo + @NotNull + private final static Map globalCache = new HashMap<>(); + + public GlobalCachedFiboSequence(int max) { + super(globalCache, max); + } + } + + + /* + * funzioni di test + */ + + // questo codice non fa parte del tema d'esame, ma per coloro che desiderano testare le 3 differenti + // versioni di FiboSequence, possono curiosare qui + private static void execTimed(String text, Runnable r) { + long t0 = System.nanoTime(); + System.out.printf("[START] %s...\n", text); + r.run(); + System.out.printf("[DONE] %.3f ms\n", ((double)(System.nanoTime() - t0)) / 1000000.); + } + + private static void testFibo(FiboSequence seq, int len, int run) { + execTimed(String.format("%s(%d) #%d", seq.getClass().getName(), len, run), + () -> { + for (int n : seq) + System.out.printf("%d ", n); + System.out.println(); + }); + } + + private static void testFibo(Function cons) { + // parametri modificabili di test + final List LENS = List.of(10, 20, 35, 44); // lunghezze delle sequenze + final int REPEATS = 3; // numero di run con la stessa istanza + + // per ogni lunghezza in LENS fa un ciclo di REPEATS ripetizioni + for (int len : LENS) { + Seq seq = cons.apply(len); + // le ripetizioni usano la stessa istanza per verificare la performance della versione cached non-global + for (int i = 1; i <= REPEATS; ++i) + testFibo(seq, len, i); + } + } + + // si può lanciare questo main e leggere i risultati dei test + public static void main(String[] args) { + // i tempi sono lunghi senza cache: più alto è il numero di fibonacci da calcolare, più tempo ci mette + testFibo(FiboSequence::new); + + // con una cache per ogni istanza i tempi sono enormemente più veloci e non dipende da quanto alto è il numero + // di fibonacci da calcolare; tuttavia la prima run di ogni ripetizione ci mette leggermente più tempo + // perché deve popolare la cache per la prima volta + testFibo(CachedFiboSequence::new); + + // con la cache condivisa raggiungiamo la massima velocità: solamente i numeri di fibonacci mai calcolati finora + // da qualunque istanza vengono davvero calcolati; quindi è veloce anche la prima run di ogni ciclo + testFibo(GlobalCachedFiboSequence::new); + } + + +} diff --git a/soluzione appelli/Scritto PO2 10 1 24/.gitignore b/soluzione appelli/Scritto PO2 10 1 24/.gitignore new file mode 100644 index 0000000..f68d109 --- /dev/null +++ b/soluzione appelli/Scritto PO2 10 1 24/.gitignore @@ -0,0 +1,29 @@ +### 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 diff --git a/soluzione appelli/Scritto PO2 10 1 24/.idea/.gitignore b/soluzione appelli/Scritto PO2 10 1 24/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/soluzione appelli/Scritto PO2 10 1 24/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/soluzione appelli/Scritto PO2 10 1 24/.idea/misc.xml b/soluzione appelli/Scritto PO2 10 1 24/.idea/misc.xml new file mode 100644 index 0000000..09e91bf --- /dev/null +++ b/soluzione appelli/Scritto PO2 10 1 24/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 10 1 24/.idea/modules.xml b/soluzione appelli/Scritto PO2 10 1 24/.idea/modules.xml new file mode 100644 index 0000000..e660639 --- /dev/null +++ b/soluzione appelli/Scritto PO2 10 1 24/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 10 1 24/.idea/uiDesigner.xml b/soluzione appelli/Scritto PO2 10 1 24/.idea/uiDesigner.xml new file mode 100644 index 0000000..2b63946 --- /dev/null +++ b/soluzione appelli/Scritto PO2 10 1 24/.idea/uiDesigner.xml @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 10 1 24/Scritto PO2 10 1 24.iml b/soluzione appelli/Scritto PO2 10 1 24/Scritto PO2 10 1 24.iml new file mode 100644 index 0000000..e13cb1e --- /dev/null +++ b/soluzione appelli/Scritto PO2 10 1 24/Scritto PO2 10 1 24.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 10 1 24/cpp/Es2.cpp b/soluzione appelli/Scritto PO2 10 1 24/cpp/Es2.cpp new file mode 100644 index 0000000..5f31a09 --- /dev/null +++ b/soluzione appelli/Scritto PO2 10 1 24/cpp/Es2.cpp @@ -0,0 +1,83 @@ +// Scritto PO2 10 9 24.cpp : This file contains the 'main' function. Program execution begins and ends there. +// + +#include +#include +#include +#include + +using namespace std; + +// 2.a +template +void map(InputIterator from, InputIterator to, OutputIterator out, function f) +{ + while (from != to) + *out++ = f(*from++); +} + +// 2.b +template +vector map(const vector& v, function f) +{ + vector r(v.size()); + map(v.begin(), v.end(), r.begin(), f); + return r; +} + +// 2.c +namespace cpp03 { + + // 2.c.i + template + vector map(const vector& v, F f) + { + vector r(v.size()); + for (int i = 0; i < v.size(); ++i) + r[i] = f(v[i]); + return r; + } + + // 2.c.ii + // no, non possono coesistere, perché sarebbero overload ambigui. Infatti ho dovuto metterli in un sotto-namespace a parte per far compilare questo sorgente. + + // 2.c.iii + // bisogna usare i function object, cioè oggetti per cui è definito l'operatore di applicazione operator() + // esempio: + class myfunction { + public: + bool operator()(int n) { return n > 2; } + }; + + void test() + { + vector v1{ 1, 2, 3, 4, 5 }; + vector v2 = map(v1, myfunction()); // senza le annotazioni esplicite dei template argument non compila (questo non è richiesto nell'esame perché è una cosa molto sottile) + } +} + +// main for testing +// + +template +ostream& operator<<(ostream& os, const vector& v) +{ + os << "[ "; + for (auto it = v.begin(); it != v.end(); ++it) + os << *it << ", "; + os << "\b\b ]"; + return os; +} + +int main() +{ + vector v1{ 1, 2, 3, 4, 5 }; + vector v2(v1.size()); + map(v1.begin(), v1.end(), v2.begin(), [](int n) { return n > 2; }); + + v2 = map(v1, [](int n) { return n > 2; }); // anche qui bisogna mettere i template argument espliciti + + cout << v1 << endl << v2 << endl; + + return 0; +} \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 10 1 24/cpp/Scritto PO2 10 9 24.sln b/soluzione appelli/Scritto PO2 10 1 24/cpp/Scritto PO2 10 9 24.sln new file mode 100644 index 0000000..ecf3557 --- /dev/null +++ b/soluzione appelli/Scritto PO2 10 1 24/cpp/Scritto PO2 10 9 24.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.6.33829.357 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Scritto PO2 10 9 24", "Scritto PO2 10 9 24.vcxproj", "{03C631EE-30AC-4D4D-A5BA-A31FD0C40886}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {03C631EE-30AC-4D4D-A5BA-A31FD0C40886}.Debug|x64.ActiveCfg = Debug|x64 + {03C631EE-30AC-4D4D-A5BA-A31FD0C40886}.Debug|x64.Build.0 = Debug|x64 + {03C631EE-30AC-4D4D-A5BA-A31FD0C40886}.Debug|x86.ActiveCfg = Debug|Win32 + {03C631EE-30AC-4D4D-A5BA-A31FD0C40886}.Debug|x86.Build.0 = Debug|Win32 + {03C631EE-30AC-4D4D-A5BA-A31FD0C40886}.Release|x64.ActiveCfg = Release|x64 + {03C631EE-30AC-4D4D-A5BA-A31FD0C40886}.Release|x64.Build.0 = Release|x64 + {03C631EE-30AC-4D4D-A5BA-A31FD0C40886}.Release|x86.ActiveCfg = Release|Win32 + {03C631EE-30AC-4D4D-A5BA-A31FD0C40886}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {64686522-43E3-4D48-A3A3-15FF5D93AE3F} + EndGlobalSection +EndGlobal diff --git a/soluzione appelli/Scritto PO2 10 1 24/cpp/Scritto PO2 10 9 24.vcxproj b/soluzione appelli/Scritto PO2 10 1 24/cpp/Scritto PO2 10 9 24.vcxproj new file mode 100644 index 0000000..8a992d4 --- /dev/null +++ b/soluzione appelli/Scritto PO2 10 1 24/cpp/Scritto PO2 10 9 24.vcxproj @@ -0,0 +1,135 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 16.0 + Win32Proj + {03c631ee-30ac-4d4d-a5ba-a31fd0c40886} + ScrittoPO210924 + 10.0 + + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + + + + + + + + + + + + + + + + + + + + Level3 + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + Level3 + true + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 10 1 24/cpp/Scritto PO2 10 9 24.vcxproj.filters b/soluzione appelli/Scritto PO2 10 1 24/cpp/Scritto PO2 10 9 24.vcxproj.filters new file mode 100644 index 0000000..2833605 --- /dev/null +++ b/soluzione appelli/Scritto PO2 10 1 24/cpp/Scritto PO2 10 9 24.vcxproj.filters @@ -0,0 +1,22 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 10 1 24/cpp/Scritto PO2 10 9 24.vcxproj.user b/soluzione appelli/Scritto PO2 10 1 24/cpp/Scritto PO2 10 9 24.vcxproj.user new file mode 100644 index 0000000..88a5509 --- /dev/null +++ b/soluzione appelli/Scritto PO2 10 1 24/cpp/Scritto PO2 10 9 24.vcxproj.user @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 10 1 24/java/.idea/.gitignore b/soluzione appelli/Scritto PO2 10 1 24/java/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/soluzione appelli/Scritto PO2 10 1 24/java/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/soluzione appelli/Scritto PO2 10 1 24/java/.idea/codeStyles/Project.xml b/soluzione appelli/Scritto PO2 10 1 24/java/.idea/codeStyles/Project.xml new file mode 100644 index 0000000..919ce1f --- /dev/null +++ b/soluzione appelli/Scritto PO2 10 1 24/java/.idea/codeStyles/Project.xml @@ -0,0 +1,7 @@ + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 10 1 24/java/.idea/codeStyles/codeStyleConfig.xml b/soluzione appelli/Scritto PO2 10 1 24/java/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 0000000..a55e7a1 --- /dev/null +++ b/soluzione appelli/Scritto PO2 10 1 24/java/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 10 1 24/java/.idea/misc.xml b/soluzione appelli/Scritto PO2 10 1 24/java/.idea/misc.xml new file mode 100644 index 0000000..d15472f --- /dev/null +++ b/soluzione appelli/Scritto PO2 10 1 24/java/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 10 1 24/java/.idea/modules.xml b/soluzione appelli/Scritto PO2 10 1 24/java/.idea/modules.xml new file mode 100644 index 0000000..e660639 --- /dev/null +++ b/soluzione appelli/Scritto PO2 10 1 24/java/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 10 1 24/java/src/Es1.java b/soluzione appelli/Scritto PO2 10 1 24/java/src/Es1.java new file mode 100644 index 0000000..2d4319a --- /dev/null +++ b/soluzione appelli/Scritto PO2 10 1 24/java/src/Es1.java @@ -0,0 +1,71 @@ +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.function.Function; + +public class Es1 { + + // 1.a + public static class FactorialThread extends Thread { + private final int n; + private long res; + + public FactorialThread(int n) { + this.n = n; + } + + @Override + public void run() { + res = fact(n); + } + + public long getResult() { + try { + join(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + return res; + } + + public int getN() { + return n; + } + + private static long fact(int n) { + if (n <= 1) return 1; + return n * fact(n - 1); + } + + } + + // 1.b + 1.c + public static List parallelFactorial(Iterable c) { + List r = new ArrayList<>(); + for (int n : c) { + FactorialThread t = new FactorialThread(n); + t.start(); + r.add(t); + } + return r; + } + + // 1.d + public static void main(String[] args) { + for (FactorialThread t : parallelFactorial(List.of(0, 1, 2, 3, 11, 12, 23, 35))) // chiamare anche parallelFactorial2() per provarla + System.out.printf("fact(%d) = %d\n", t.getN(), t.getResult()); + } + + // 1.e.i + public static List map(Iterable i, Function f) { + List r = new ArrayList<>(); + for (A a : i) + r.add(f.apply(a)); + return r; + } + + // 1.e.ii + public static Collection parallelFactorial2(Collection c) { + return map(c, (n) -> { FactorialThread t = new FactorialThread(n); t.start(); return t; }); + } +} \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 10 9 24/cpp/Appello_14_6_24/Appello_14_6_24.cpp b/soluzione appelli/Scritto PO2 10 9 24/cpp/Appello_14_6_24/Appello_14_6_24.cpp new file mode 100644 index 0000000..df04c28 --- /dev/null +++ b/soluzione appelli/Scritto PO2 10 9 24/cpp/Appello_14_6_24/Appello_14_6_24.cpp @@ -0,0 +1,35 @@ + +// Questo sorgente contiene le soluzioni dell'esame scritto di PO2 del 5/9/2023 per ciò che riguarda il quesito 2, ovvero la domanda che coinvolge C++. +// I quesiti 1-5 riguardanti Java sono in un sorgente Java a parte, non qui. +// Il codice C++ qui esposto è standard C++ vanilla (a.k.a. C++03), sebbene il progetto VS sia configurato con il compilatore di default C++14 + +#include +#include + +using namespace std; + +template +ostream& operator<<(ostream& os, const Container& c) +{ + os << "["; + for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) + os << " " << *it; + os << "]"; + return os; +} + +template +typename Container::value_type sum(const Container& c) +{ + typename Container::value_type r; + for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) + { + r += *it; + } + return r; +} + + +int main() +{ +} diff --git a/soluzione appelli/Scritto PO2 10 9 24/cpp/Appello_14_6_24/Appello_14_6_24.sln b/soluzione appelli/Scritto PO2 10 9 24/cpp/Appello_14_6_24/Appello_14_6_24.sln new file mode 100644 index 0000000..9683cae --- /dev/null +++ b/soluzione appelli/Scritto PO2 10 9 24/cpp/Appello_14_6_24/Appello_14_6_24.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.2.32526.322 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Appello_14_6_24", "Appello_14_6_24.vcxproj", "{C7C15495-50AD-4636-90B2-C312702B99FD}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C7C15495-50AD-4636-90B2-C312702B99FD}.Debug|x64.ActiveCfg = Debug|x64 + {C7C15495-50AD-4636-90B2-C312702B99FD}.Debug|x64.Build.0 = Debug|x64 + {C7C15495-50AD-4636-90B2-C312702B99FD}.Debug|x86.ActiveCfg = Debug|Win32 + {C7C15495-50AD-4636-90B2-C312702B99FD}.Debug|x86.Build.0 = Debug|Win32 + {C7C15495-50AD-4636-90B2-C312702B99FD}.Release|x64.ActiveCfg = Release|x64 + {C7C15495-50AD-4636-90B2-C312702B99FD}.Release|x64.Build.0 = Release|x64 + {C7C15495-50AD-4636-90B2-C312702B99FD}.Release|x86.ActiveCfg = Release|Win32 + {C7C15495-50AD-4636-90B2-C312702B99FD}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {49DE568A-D54C-485E-A095-5948A84AED91} + EndGlobalSection +EndGlobal diff --git a/soluzione appelli/Scritto PO2 10 9 24/cpp/Appello_14_6_24/Appello_14_6_24.vcxproj b/soluzione appelli/Scritto PO2 10 9 24/cpp/Appello_14_6_24/Appello_14_6_24.vcxproj new file mode 100644 index 0000000..748b08d --- /dev/null +++ b/soluzione appelli/Scritto PO2 10 9 24/cpp/Appello_14_6_24/Appello_14_6_24.vcxproj @@ -0,0 +1,135 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 16.0 + Win32Proj + {C7C15495-50AD-4636-90B2-C312702B99FD} + Appello3622 + 10.0 + + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + + + + + + + + + + + + + + + + + + + + Level3 + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + Level4 + true + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 10 9 24/cpp/Appello_14_6_24/Appello_14_6_24.vcxproj.user b/soluzione appelli/Scritto PO2 10 9 24/cpp/Appello_14_6_24/Appello_14_6_24.vcxproj.user new file mode 100644 index 0000000..88a5509 --- /dev/null +++ b/soluzione appelli/Scritto PO2 10 9 24/cpp/Appello_14_6_24/Appello_14_6_24.vcxproj.user @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 10 9 24/java/.idea/workspace.xml b/soluzione appelli/Scritto PO2 10 9 24/java/.idea/workspace.xml new file mode 100644 index 0000000..b8c4216 --- /dev/null +++ b/soluzione appelli/Scritto PO2 10 9 24/java/.idea/workspace.xml @@ -0,0 +1,50 @@ + + + + + + + + + + + + + + + + + + + + + 1725443138444 + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 10 9 24/java/Scritto PO2 10 9 24/.gitignore b/soluzione appelli/Scritto PO2 10 9 24/java/Scritto PO2 10 9 24/.gitignore new file mode 100644 index 0000000..f68d109 --- /dev/null +++ b/soluzione appelli/Scritto PO2 10 9 24/java/Scritto PO2 10 9 24/.gitignore @@ -0,0 +1,29 @@ +### 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 diff --git a/soluzione appelli/Scritto PO2 10 9 24/java/Scritto PO2 10 9 24/.idea/.gitignore b/soluzione appelli/Scritto PO2 10 9 24/java/Scritto PO2 10 9 24/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/soluzione appelli/Scritto PO2 10 9 24/java/Scritto PO2 10 9 24/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/soluzione appelli/Scritto PO2 10 9 24/java/Scritto PO2 10 9 24/.idea/misc.xml b/soluzione appelli/Scritto PO2 10 9 24/java/Scritto PO2 10 9 24/.idea/misc.xml new file mode 100644 index 0000000..8633114 --- /dev/null +++ b/soluzione appelli/Scritto PO2 10 9 24/java/Scritto PO2 10 9 24/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 10 9 24/java/Scritto PO2 10 9 24/.idea/modules.xml b/soluzione appelli/Scritto PO2 10 9 24/java/Scritto PO2 10 9 24/.idea/modules.xml new file mode 100644 index 0000000..6303aee --- /dev/null +++ b/soluzione appelli/Scritto PO2 10 9 24/java/Scritto PO2 10 9 24/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 10 9 24/java/Scritto PO2 10 9 24/Scritto PO2 10 9 24.iml b/soluzione appelli/Scritto PO2 10 9 24/java/Scritto PO2 10 9 24/Scritto PO2 10 9 24.iml new file mode 100644 index 0000000..c90834f --- /dev/null +++ b/soluzione appelli/Scritto PO2 10 9 24/java/Scritto PO2 10 9 24/Scritto PO2 10 9 24.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 10 9 24/java/Scritto PO2 10 9 24/src/Es1.java b/soluzione appelli/Scritto PO2 10 9 24/java/Scritto PO2 10 9 24/src/Es1.java new file mode 100644 index 0000000..3cd97fe --- /dev/null +++ b/soluzione appelli/Scritto PO2 10 9 24/java/Scritto PO2 10 9 24/src/Es1.java @@ -0,0 +1,10 @@ +public class Es1 { + + public static void m() { + double x = 3.; + int y = 5; + System.out.println(x / y); + } + + +} diff --git a/soluzione appelli/Scritto PO2 13 1 23/.idea/.gitignore b/soluzione appelli/Scritto PO2 13 1 23/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/soluzione appelli/Scritto PO2 13 1 23/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/soluzione appelli/Scritto PO2 13 1 23/.idea/misc.xml b/soluzione appelli/Scritto PO2 13 1 23/.idea/misc.xml new file mode 100644 index 0000000..2fef783 --- /dev/null +++ b/soluzione appelli/Scritto PO2 13 1 23/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 13 1 23/.idea/modules.xml b/soluzione appelli/Scritto PO2 13 1 23/.idea/modules.xml new file mode 100644 index 0000000..1a7b376 --- /dev/null +++ b/soluzione appelli/Scritto PO2 13 1 23/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 13 1 23/.idea/vcs.xml b/soluzione appelli/Scritto PO2 13 1 23/.idea/vcs.xml new file mode 100644 index 0000000..b2bdec2 --- /dev/null +++ b/soluzione appelli/Scritto PO2 13 1 23/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 13 1 23/Scritto PO2 13 1 2023.iml b/soluzione appelli/Scritto PO2 13 1 23/Scritto PO2 13 1 2023.iml new file mode 100644 index 0000000..908ad4f --- /dev/null +++ b/soluzione appelli/Scritto PO2 13 1 23/Scritto PO2 13 1 2023.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 13 1 23/Scritto PO2 13 1 23.iml b/soluzione appelli/Scritto PO2 13 1 23/Scritto PO2 13 1 23.iml new file mode 100644 index 0000000..908ad4f --- /dev/null +++ b/soluzione appelli/Scritto PO2 13 1 23/Scritto PO2 13 1 23.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 13 1 23/cpp/Appello_13_.vcxproj b/soluzione appelli/Scritto PO2 13 1 23/cpp/Appello_13_.vcxproj new file mode 100644 index 0000000..a94f4fc --- /dev/null +++ b/soluzione appelli/Scritto PO2 13 1 23/cpp/Appello_13_.vcxproj @@ -0,0 +1,137 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 16.0 + Win32Proj + {3c05ab7e-1582-4bd1-866b-5da21b3a6778} + Appello13 + 10.0 + Appello_13_1_2023 + + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + + + + + + + + + + + + + + + + + + + + Level3 + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + Level3 + true + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + Default + + + Console + true + + + + + Level3 + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 13 1 23/cpp/Appello_13_.vcxproj.filters b/soluzione appelli/Scritto PO2 13 1 23/cpp/Appello_13_.vcxproj.filters new file mode 100644 index 0000000..ed2698d --- /dev/null +++ b/soluzione appelli/Scritto PO2 13 1 23/cpp/Appello_13_.vcxproj.filters @@ -0,0 +1,22 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 13 1 23/cpp/Appello_13_.vcxproj.user b/soluzione appelli/Scritto PO2 13 1 23/cpp/Appello_13_.vcxproj.user new file mode 100644 index 0000000..88a5509 --- /dev/null +++ b/soluzione appelli/Scritto PO2 13 1 23/cpp/Appello_13_.vcxproj.user @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 13 1 23/cpp/Appello_13_1_2023.sln b/soluzione appelli/Scritto PO2 13 1 23/cpp/Appello_13_1_2023.sln new file mode 100644 index 0000000..76133ad --- /dev/null +++ b/soluzione appelli/Scritto PO2 13 1 23/cpp/Appello_13_1_2023.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.3.32901.215 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Appello_13_", "Appello_13_.vcxproj", "{3C05AB7E-1582-4BD1-866B-5DA21B3A6778}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {3C05AB7E-1582-4BD1-866B-5DA21B3A6778}.Debug|x64.ActiveCfg = Debug|x64 + {3C05AB7E-1582-4BD1-866B-5DA21B3A6778}.Debug|x64.Build.0 = Debug|x64 + {3C05AB7E-1582-4BD1-866B-5DA21B3A6778}.Debug|x86.ActiveCfg = Debug|Win32 + {3C05AB7E-1582-4BD1-866B-5DA21B3A6778}.Debug|x86.Build.0 = Debug|Win32 + {3C05AB7E-1582-4BD1-866B-5DA21B3A6778}.Release|x64.ActiveCfg = Release|x64 + {3C05AB7E-1582-4BD1-866B-5DA21B3A6778}.Release|x64.Build.0 = Release|x64 + {3C05AB7E-1582-4BD1-866B-5DA21B3A6778}.Release|x86.ActiveCfg = Release|Win32 + {3C05AB7E-1582-4BD1-866B-5DA21B3A6778}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {66CDDA76-E424-4DD8-87CF-E87E03399139} + EndGlobalSection +EndGlobal diff --git a/soluzione appelli/Scritto PO2 13 1 23/cpp/curve.cpp b/soluzione appelli/Scritto PO2 13 1 23/cpp/curve.cpp new file mode 100644 index 0000000..2032bdd --- /dev/null +++ b/soluzione appelli/Scritto PO2 13 1 23/cpp/curve.cpp @@ -0,0 +1,131 @@ + +#include +#include +#include +#include + +using namespace std; + + +using real = double; +using unary_fun = function; + +#define RESOLUTION (10) + + +class curve +{ + +private: + real a, b; + unary_fun f; + +public: + curve(const real& a_, const real& b_, const unary_fun& f_) : f(f_), a(a_), b(b_) {} + + real get_dx() const { return (b - a) / RESOLUTION; } + + pair interval() const { return pair(a, b); } + + curve derivative() const + { + return curve(a, b, [&, dx = get_dx()](const real& x) { // anche la capture [=] sarebbe stata sufficiente + const real dy = f(x + dx) - f(x); + return dy / dx; + }); + } + + curve primitive() const + { + return curve(a, b, [&, dx = get_dx()](const real& x) { // oppure la [&] + const real y = f(x); + return y * dx; + }); + } + + real integral() const + { + const unary_fun& F = primitive(); + return F(b) - F(a); + } + + real operator()(const real& x) const + { + return f(x); + } + + class iterator + { + private: + const curve& c; + real x; + + public: + iterator(const curve& c_, const real& x_) : c(c_), x(x_) {} + + pair operator*() const + { + return pair(x, c.f(x)); + } + + iterator& operator++() // il pre-incremento modifica sè stesso e non ritorna una copia + { + x += c.get_dx(); + return *this; + } + + iterator operator++(int) // il post-incremento fa una copia, modifica sé stesso e ritorna la copia + { + auto r(*this); + ++(*this); + return r; + } + + bool operator!=(const iterator& it) const + { + return fabs(x - it.x) >= c.get_dx(); // non si confrontano mai i float direttamente con l'operatore di uguaglianza o disuguaglianza + } + }; + + iterator begin() const + { + return iterator(*this, a); + } + + iterator end() const + { + return iterator(*this, b + get_dx()); + } + +}; + + +ostream& operator<<(ostream& os, const curve& c) +{ + os << "dom = [" << c.interval().first << ", " << c.interval().second << "] dx = " << c.get_dx() << ": " << endl; + /*for (const pair& p : c) + { + const real& x = p.first, & y = p.second; + os << "\tf(" << x << ") = " << y << endl; + }*/ + for (curve::iterator it = c.begin(); it != c.end(); ++it) + { + const pair& p = *it; + const real& x = p.first, & y = p.second; + os << "\tf(" << x << ") = " << y << endl; + } + return os << endl; +} + +int main() +{ + curve f(-1., 1., [](const real& x) { return x * x; }); + + cout << f << endl + << f.derivative() << endl + << f.primitive() << endl + << f.primitive().derivative() << endl + << f.derivative().primitive() << endl + ; + return 0; +} \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 13 1 23/java/.idea/.gitignore b/soluzione appelli/Scritto PO2 13 1 23/java/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/soluzione appelli/Scritto PO2 13 1 23/java/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/soluzione appelli/Scritto PO2 13 1 23/java/.idea/misc.xml b/soluzione appelli/Scritto PO2 13 1 23/java/.idea/misc.xml new file mode 100644 index 0000000..d15472f --- /dev/null +++ b/soluzione appelli/Scritto PO2 13 1 23/java/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 13 1 23/java/.idea/modules.xml b/soluzione appelli/Scritto PO2 13 1 23/java/.idea/modules.xml new file mode 100644 index 0000000..01b0bca --- /dev/null +++ b/soluzione appelli/Scritto PO2 13 1 23/java/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 13 1 23/java/.idea/vcs.xml b/soluzione appelli/Scritto PO2 13 1 23/java/.idea/vcs.xml new file mode 100644 index 0000000..c2365ab --- /dev/null +++ b/soluzione appelli/Scritto PO2 13 1 23/java/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 13 1 23/java/Appello_13_1_2023.iml b/soluzione appelli/Scritto PO2 13 1 23/java/Appello_13_1_2023.iml new file mode 100644 index 0000000..8b2ade9 --- /dev/null +++ b/soluzione appelli/Scritto PO2 13 1 23/java/Appello_13_1_2023.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 13 1 23/java/Es1.java b/soluzione appelli/Scritto PO2 13 1 23/java/Es1.java new file mode 100644 index 0000000..9aff19f --- /dev/null +++ b/soluzione appelli/Scritto PO2 13 1 23/java/Es1.java @@ -0,0 +1,94 @@ +import java.util.Random; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; + +public class Es1 { + + public interface Pool { + R acquire() throws InterruptedException; + void release(R x); + } + + // 2.b + public static class SimplePool implements Pool { + + private final BlockingQueue q = new LinkedBlockingQueue<>(); + + @Override + public T acquire() throws InterruptedException { + return q.take(); + } + + @Override + public void release(T x) { + q.add(x); + } + } + + // 2.c + 2.d + + public interface Resource { + T get(); + void autorelease(); + } + + public static class AutoPool implements Pool> { + + private final BlockingQueue q = new LinkedBlockingQueue<>(); + + // questo metodo non è richiesto dall'interfaccia AutoPool, però è utile perché serve a popolare la pool, come accade nel main + public void add(T x) { + q.add(x); + } + + public Resource acquire() throws InterruptedException { + T r = q.take(); + return new Resource<>() { + + @Override + public T get() { + System.out.printf("acquired: %s%n", r); + return r; + } + + @Override + public void autorelease() { + System.out.printf("released: %s%n", r); + add(r); + } + + @SuppressWarnings("deprecation") + @Override + protected void finalize() { + autorelease(); + } + }; + } + + @Override + public void release(Resource x) { + x.autorelease(); + } + } + + public static void main(String[] args) { + AutoPool pool = new AutoPool<>(); + Random rnd = new Random(); + for (int i = 0; i < 5; ++i) { + pool.add(i); // popolo la pool con alcuni oggetti + } + + try { + while (true) { + Resource r = pool.acquire(); + System.out.println("using " + r.get()); + Thread.sleep(Math.abs(rnd.nextInt() % 1000)); + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + + } + + +} diff --git a/soluzione appelli/Scritto PO2 13 9 22/Scritto PO2 13 9 22.iml b/soluzione appelli/Scritto PO2 13 9 22/Scritto PO2 13 9 22.iml new file mode 100644 index 0000000..e13cb1e --- /dev/null +++ b/soluzione appelli/Scritto PO2 13 9 22/Scritto PO2 13 9 22.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 13 9 22/cpp/Appello_13_9_22/Appello_13_9_22.cpp b/soluzione appelli/Scritto PO2 13 9 22/cpp/Appello_13_9_22/Appello_13_9_22.cpp new file mode 100644 index 0000000..85a0b9f --- /dev/null +++ b/soluzione appelli/Scritto PO2 13 9 22/cpp/Appello_13_9_22/Appello_13_9_22.cpp @@ -0,0 +1,364 @@ + +// Questo sorgente contiene le soluzioni dell'esame scritto di PO2 del 1/7/2022 per ciò che riguarda il quesito 2, ovvero l'esercizio di C++. +// Il quesito 1 riguardante Java è in un progetto IntelliJ a parte, non qui. +// Il codice qui esposto è C++14. +// ATTENZIONE: il codice qui fornito è ricco di dettagli e complessità, allo scopo di fornire materiale di studio. La versione richiesta all'esame è molto più semplice. + +#include +#include +#include +#include + +using std::vector; + +#define EASY_ITERATOR // commentare questa macro per compilare la versione ottimizzata degli iteratori + +template +class tree_node +{ +public: + T data; + tree_node* left, * right; + + static bool are_equal(const tree_node* a, const tree_node* b) + { + return a == b || (a != nullptr && b != nullptr && *a == *b); + } + +public: + // 2.c + + tree_node() = default; + tree_node(const tree_node& t) = default; + tree_node& operator=(const tree_node& t) = default; + + ~tree_node() + { + if (left != nullptr) + { + delete left; + left = nullptr; + } + if (right != nullptr) + { + delete right; + right = nullptr; + } + } + + tree_node(const T& v, tree_node* l, tree_node* r) : data(v), left(l), right(r) + { +# ifdef EASY_ITERATOR + prepopulate(); +# else + if (left != nullptr) left->parent = this; + if (right != nullptr) right->parent = this; +# endif + } + + // 2.b + + bool operator==(const tree_node& t) const + { + return data == t.data && are_equal(left, t.left) && are_equal(right, t.right); + } + + // 2.a + + using value_type = T; + + + // implementazione facile degli iteratori, suggerita pubblicamente dal docente durante l'appello del 13/9/22 + // + +# ifdef EASY_ITERATOR + + using const_iterator = typename vector::const_iterator; + using iterator = typename vector::iterator; + +private: + // per motivi di semplicità ogni nodo ha un campo di tipo vector che viene popolato al volo per essere iterator + // si faccia attenzione ad un particolare: per poter ritornare begin() ed end() dello stesso vector, bisogna conservarlo come membro del nodo + vector children; + + void dfs(vector& v) + { + // perché non popoliamo direttamente il campo children? il motivo è molto sottile: ogni nodo ha un suo campo children, ma noi non vogliamo che ogni nodo popoli il proprio vector; noi vogliamo + // che quando decidiamo di popolare il campo di children di un certo nodo, allora viene popolato il vector di QUEL nodo + // ogni nodo quindi ha un suo campo children che viene popolato con i SUOI sottorami: tutto ciò è uno spreco di spazio, certo, però permette di fare iteratori a partire da QUALUNQUE nodo + // in maniera semplice e immutabile + v.push_back(data); + if (left != nullptr) left->dfs(v); + if (right != nullptr) right->dfs(v); + } + + // questa viene chiamata dal costruttore: ogni nodo prepopola il proprio campo children + void prepopulate() + { + dfs(children); + } + +public: + + const_iterator begin() const + { + return children.begin(); + } + + const_iterator end() const + { + return children.end(); + } + + iterator begin() + { + return children.begin(); + } + + iterator end() + { + return children.end(); + } + + + // implementazione ottimizzata degli iteratori + // + +# else + +private: + tree_node* parent; + + static tree_node* get_next_node(const tree_node* n) { + if (n->left != nullptr) + return n->left; + else if (n->right != nullptr) + return n->right; + else { + while (n->parent != nullptr) { + const tree_node* last = n; + n = n->parent; + if (n->right != nullptr && n->right != last) + return n->right; + } + return nullptr; + } + } + +public: + // iteratore non-const + class my_iterator + { + friend class my_const_iterator; // questo serve perché altrimenti my_const_iterator non può accedere al campo current di my_iterator + + private: + tree_node* current; + + public: + using iterator_category = std::forward_iterator_tag; // questo member type indica che si tratta di un ForwardIterator, si veda la doc di STL per i dettagli + using difference_type = std::ptrdiff_t; + using value_type = T; + using pointer = T*; + using reference = T&; + + my_iterator() = default; + my_iterator(const my_iterator& i) = default; + my_iterator& operator=(const my_iterator& i) = default; + + my_iterator(tree_node* t) : current(t) {} + + reference operator*() { return current->data; } + pointer operator->() { return ¤t->data; } + + my_iterator& operator++() + { + current = get_next_node(current); + return *this; + } + + my_iterator operator++(int) + { + my_iterator r(*this); + current = get_next_node(); + return r; + } + + bool operator==(const my_iterator& i) const { return current == i.current; } + bool operator!=(const my_iterator& i) const { return !(*this == i); } + + }; + + // interatore const + // si noti come sono praticamente uguali a parte il fatto che gesticono un nodo const oppure no, con conseguente impatto in tutti i tipi di ritorno dei vari operatori + // questa replicazione di codice sarebbe evitabile solamente tramite un complesso uso dei template, troppo complesso per questo corso + // chi è interessato a sapere come evitare questa duplicazione di codice dovuta a const vs. non-const può approfondire qui: https://stackoverflow.com/questions/765148/how-to-remove-constness-of-const-iterator + class my_const_iterator + { + private: + const tree_node* current; + + public: + using iterator_category = std::forward_iterator_tag; + using difference_type = std::ptrdiff_t; + using value_type = const T; + using pointer = const T*; + using reference = const T&; + + my_const_iterator() = default; + my_const_iterator(const my_const_iterator& i) = default; + my_const_iterator& operator=(const my_const_iterator& i) = default; + + // questo costruttore è molto interessante: permette di costruire un my_const_iterator dato un my_iterator: in altre parole possiamo convertire un iteratore non-const in uno const + // il motivo per cui è necessario è se chiamiamo begin() su un tree_node non-const ma vogliamo un const_iterator perché lo leggiamo soltanto + my_const_iterator(const my_iterator& i) : current(i.current) {} + + my_const_iterator(const tree_node* t) : current(t) {} + + reference operator*() const { return current->data; } + pointer operator->() const { return ¤t->data; } + + my_const_iterator& operator++() + { + current = get_next_node(current); + return *this; + } + + my_const_iterator operator++(int) + { + my_const_iterator r(*this); + current = get_next_node(); + return r; + } + + bool operator==(const my_const_iterator& i) const { return current == i.current; } + bool operator!=(const my_const_iterator& i) const { return !(*this == i); } + + }; + + // definiamo questi member type perché sono quelli che i Container STL solitamente definiscono + using const_iterator = my_const_iterator; // rebinding della nested class my_const_iterator definita sopra + using iterator = my_iterator; // rebinding della nested class my_iterator definita sopra + using value_type = T; + + const_iterator begin() const + { + return const_iterator(this); + } + + const_iterator end() const + { + return const_iterator(nullptr); + } + + iterator begin() + { + return iterator(this); + } + + iterator end() + { + return iterator(nullptr); + } + +# endif + +}; + +// 2.c +// pseudo-costruttori +// invece di fare metodi statici facciamo funzioni templatizzate globali, così il template argument è inferito e diventano più comode da usare + +template +tree_node* lr(const T& v, tree_node* l, tree_node* r) +{ + return new tree_node(v, l, r); +} + +template +tree_node* l(const T& v, tree_node* n) +{ + return new tree_node(v, n, nullptr); +} + +template +tree_node* r(const T& v, tree_node* n) +{ + return new tree_node(v, nullptr, n); +} + +template +tree_node* v(const T& v) +{ + return new tree_node(v, nullptr, nullptr); +} + +// 2.e + +template +std::ostream& operator<<(std::ostream& os, const tree_node& t) +{ + os << t.data; + if (t.left != nullptr) os << "(" << *t.left << ")"; + if (t.right != nullptr) os << "[" << *t.right << "]"; + return os; +} + +using namespace std; + +// 2.d + +int main() +{ + auto t1 = + shared_ptr>( // usiamo gli shared_ptr per non doverci ricordare di fare delete + // con i pseudo-costruttori globali è comodissimo costruire un albero, basta innestare le chiamate + lr(1, + lr(2, + v(3), + v(4)), + r(5, + lr(6, + v(7), + v(8))))); + + auto t2 = + shared_ptr>( + lr(1, + r(5, // il sottoalbero destro di t2 è uguale al sinistro di t1 e viceversa + lr(6, + v(7), + v(8))), + lr(2, + v(3), + v(4)))); + + // test dell'operatore di stream (<<) + cout << "pretty printer: " << endl + << "t1: " << *t1 << endl // dereferenziamo per stampare perché il nostro operator<< non vuole un pointer ma un reference + << "t2: " << *t2 << endl; + + // test dell'operatore di uguaglianza (==) + cout << "equality: " << (*t1 == *t2) << ", " << (*t1->left == *t2->right) << endl; // dereferenziamo gli operandi sinistro e destro del nostro operator== perchè non accetta pointer ma reference + + // test dell'iteratore non-const + cout << "iterator: "; + for (tree_node::iterator it = t1->begin(); it != t1->end(); ++it) + { + int& n = *it; // dereferenziando l'iteratore abbiamo accesso non-const al dato dentro il nodo + n *= 2; // il campo data in ogni nodo può quindi essere modificato + cout << n << " "; + } + cout << endl << "t1 modificato: " << *t1 << endl; // ristampiamo t1 dopo le modifiche + + // test dell'iteratore const + cout << "const iterator: "; + for (tree_node::const_iterator it = t1->begin(); it != t1->end(); ++it) // t1->begin() ritorna un iterator, che viene convertito in un const_iterator dal costruttore alla linea 142 + { + const int& n = *it; // dereferenziando l'iteratore abbiamo accesso const al dato dentro il nodo, quindi non possiamo modificarlo ma solo leggerlo + cout << n << " "; + } + cout << endl; + + + +} diff --git a/soluzione appelli/Scritto PO2 13 9 22/cpp/Appello_13_9_22/Appello_13_9_22.sln b/soluzione appelli/Scritto PO2 13 9 22/cpp/Appello_13_9_22/Appello_13_9_22.sln new file mode 100644 index 0000000..a6f521c --- /dev/null +++ b/soluzione appelli/Scritto PO2 13 9 22/cpp/Appello_13_9_22/Appello_13_9_22.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.2.32630.192 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Appello_13_9_22", "Appello_13_9_22.vcxproj", "{E8ACD1DF-24EF-429E-84EF-4EB4C65986A8}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {E8ACD1DF-24EF-429E-84EF-4EB4C65986A8}.Debug|x64.ActiveCfg = Debug|x64 + {E8ACD1DF-24EF-429E-84EF-4EB4C65986A8}.Debug|x64.Build.0 = Debug|x64 + {E8ACD1DF-24EF-429E-84EF-4EB4C65986A8}.Debug|x86.ActiveCfg = Debug|Win32 + {E8ACD1DF-24EF-429E-84EF-4EB4C65986A8}.Debug|x86.Build.0 = Debug|Win32 + {E8ACD1DF-24EF-429E-84EF-4EB4C65986A8}.Release|x64.ActiveCfg = Release|x64 + {E8ACD1DF-24EF-429E-84EF-4EB4C65986A8}.Release|x64.Build.0 = Release|x64 + {E8ACD1DF-24EF-429E-84EF-4EB4C65986A8}.Release|x86.ActiveCfg = Release|Win32 + {E8ACD1DF-24EF-429E-84EF-4EB4C65986A8}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {67D120F8-8926-4693-8B0B-591C7F23EAE0} + EndGlobalSection +EndGlobal diff --git a/soluzione appelli/Scritto PO2 13 9 22/cpp/Appello_13_9_22/Appello_13_9_22.vcxproj b/soluzione appelli/Scritto PO2 13 9 22/cpp/Appello_13_9_22/Appello_13_9_22.vcxproj new file mode 100644 index 0000000..73f7552 --- /dev/null +++ b/soluzione appelli/Scritto PO2 13 9 22/cpp/Appello_13_9_22/Appello_13_9_22.vcxproj @@ -0,0 +1,136 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 16.0 + Win32Proj + {e8acd1df-24ef-429e-84ef-4eb4c65986a8} + Appello13922 + 10.0 + + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + + + + + + + + + + + + + + + + + + + + Level3 + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + Level3 + true + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + Default + + + Console + true + + + + + Level3 + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 13 9 22/cpp/Appello_13_9_22/Appello_13_9_22.vcxproj.filters b/soluzione appelli/Scritto PO2 13 9 22/cpp/Appello_13_9_22/Appello_13_9_22.vcxproj.filters new file mode 100644 index 0000000..09a4bf5 --- /dev/null +++ b/soluzione appelli/Scritto PO2 13 9 22/cpp/Appello_13_9_22/Appello_13_9_22.vcxproj.filters @@ -0,0 +1,22 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 13 9 22/cpp/Appello_13_9_22/Appello_13_9_22.vcxproj.user b/soluzione appelli/Scritto PO2 13 9 22/cpp/Appello_13_9_22/Appello_13_9_22.vcxproj.user new file mode 100644 index 0000000..88a5509 --- /dev/null +++ b/soluzione appelli/Scritto PO2 13 9 22/cpp/Appello_13_9_22/Appello_13_9_22.vcxproj.user @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 13 9 22/java/.idea/.gitignore b/soluzione appelli/Scritto PO2 13 9 22/java/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/soluzione appelli/Scritto PO2 13 9 22/java/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/soluzione appelli/Scritto PO2 13 9 22/java/.idea/.name b/soluzione appelli/Scritto PO2 13 9 22/java/.idea/.name new file mode 100644 index 0000000..fd55a0e --- /dev/null +++ b/soluzione appelli/Scritto PO2 13 9 22/java/.idea/.name @@ -0,0 +1 @@ +Appello_13_9_22.iml \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 13 9 22/java/.idea/codeStyles/codeStyleConfig.xml b/soluzione appelli/Scritto PO2 13 9 22/java/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 0000000..a55e7a1 --- /dev/null +++ b/soluzione appelli/Scritto PO2 13 9 22/java/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 13 9 22/java/.idea/misc.xml b/soluzione appelli/Scritto PO2 13 9 22/java/.idea/misc.xml new file mode 100644 index 0000000..d15472f --- /dev/null +++ b/soluzione appelli/Scritto PO2 13 9 22/java/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 13 9 22/java/.idea/modules.xml b/soluzione appelli/Scritto PO2 13 9 22/java/.idea/modules.xml new file mode 100644 index 0000000..eefc65a --- /dev/null +++ b/soluzione appelli/Scritto PO2 13 9 22/java/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 13 9 22/java/.idea/vcs.xml b/soluzione appelli/Scritto PO2 13 9 22/java/.idea/vcs.xml new file mode 100644 index 0000000..c2365ab --- /dev/null +++ b/soluzione appelli/Scritto PO2 13 9 22/java/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 13 9 22/java/Appello_13_9_22.iml b/soluzione appelli/Scritto PO2 13 9 22/java/Appello_13_9_22.iml new file mode 100644 index 0000000..0181b11 --- /dev/null +++ b/soluzione appelli/Scritto PO2 13 9 22/java/Appello_13_9_22.iml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 13 9 22/java/src/Es1.java b/soluzione appelli/Scritto PO2 13 9 22/java/src/Es1.java new file mode 100644 index 0000000..8c42583 --- /dev/null +++ b/soluzione appelli/Scritto PO2 13 9 22/java/src/Es1.java @@ -0,0 +1,187 @@ +// Questo sorgente contiene le soluzioni dell'esame scritto di PO2 del 13/9/2022 per ciò che riguarda il quesito 1, +// ovvero l'esercizio in Java. +// Il quesito 2 riguardante C++ è in una Solution per Visual Studio a parte. + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.concurrent.BlockingQueue; + +public class Es1 { + + // 1.d + + public static void main(String[] args) { + TreeNode t1 = + TreeNode.lr(1, + TreeNode.lr(2, + TreeNode.v(3), + TreeNode.v(4)), + TreeNode.r(5, + TreeNode.lr(6, + TreeNode.v(7), + TreeNode.v(8)))); + + TreeNode t2 = + TreeNode.lr(1, + TreeNode.r(5, + TreeNode.lr(6, + TreeNode.v(7), + TreeNode.v(8))), + TreeNode.lr(2, + TreeNode.v(3), + TreeNode.v(4))); + + + // test pretty printer + System.out.println("pretty printer:"); + System.out.println("t1: " + t1); + System.out.println("t2: " + t2); + + // test equality + System.out.print("equality: "); + System.out.println(t1.equals(t2) + ", " + (t1.left != null ? t1.left.equals(t2.right) : "")); + + // test iterator + System.out.print("iterator: "); + for (Integer n : t1) { + System.out.printf("%d ", n); + } + System.out.println(); + + } + + public static class TreeNode implements Iterable { + + @NotNull + private final T data; + @Nullable + private final TreeNode left, right; + @Nullable + private TreeNode parent = null; + + // 1.c + + public TreeNode(@NotNull T data, @Nullable TreeNode left, @Nullable TreeNode right) { + this.data = data; + this.left = left; + this.right = right; + if (left != null) left.parent = this; + if (right != null) right.parent = this; + } + + // i seguenti pseudo-costruttori aiutano a costruire alberi in modo più succinto e controllato rispetto + // all'innestamento dei costruttori + + // solo ramo sinistro + public static TreeNode l(@NotNull T data, @NotNull TreeNode left) { + return new TreeNode<>(data, left, null); + } + + // solo ramo destro + public static TreeNode r(@NotNull T data, @NotNull TreeNode right) { + return new TreeNode<>(data, null, right); + } + + // ramo sinistro e destro + public static TreeNode lr(@NotNull T data, @NotNull TreeNode left, @NotNull TreeNode right) { + return new TreeNode<>(data, left, right); + } + + // foglia + public static TreeNode v(@NotNull T data) { + return new TreeNode<>(data, null, null); + } + + // 1.b + + @Override + public boolean equals(@Nullable Object o) { + if (o instanceof TreeNode) { + BlockingQueue b; + + TreeNode t = (TreeNode) o; + return areEqual(data, t.data) && areEqual(left, t.left) && areEqual(right, t.right); + } + return false; + } + + private static boolean areEqual(@Nullable Object a, @Nullable Object b) { + return a == b || (a != null && a.equals(b)); + //return Objects.equals(a, b); // alternativamente si può usare questo metodo del JDK + } + + // 1.e + + @Override + @NotNull + public String toString() { + return String.format("%s%s%s", data, left != null ? String.format("(%s)", left) : "", right != null ? + String.format("[%s]", right) : ""); + } + + // 1.a + + @Override + public Iterator iterator() { + return iterator_easy(); // stub ad una delle due implementazione; cambiare lo stub per testare l'altra + } + + + // questo è l'implementazione facile, suggerita pubblicamente dal docente in classe duranto l'appello del 13/9/22 + private Iterator iterator_easy() { + Collection r = new ArrayList<>(); + dfs(r); + return r.iterator(); + } + + private void dfs(Collection c) { + c.add(data); + if (left != null) left.dfs(c); + if (right != null) right.dfs(c); + } + + // questo è l'implementazione ottimizzata, che attraversa l'albero senza liste d'appoggio + private Iterator iterator_opt() { + return new Iterator<>() { + @Nullable + private TreeNode current = TreeNode.this; + + @Override + public boolean hasNext() { + return current != null; + } + + @Nullable + private static TreeNode getNextNode(@NotNull TreeNode n) { + if (n.left != null) + return n.left; + else if (n.right != null) + return n.right; + else { + while (n.parent != null) { + final TreeNode last = n; + n = n.parent; + if (n.right != null && n.right != last) + return n.right; + } + return null; + } + } + + @Override + @NotNull + public T next() { + T r = current.data; + current = getNextNode(current); + return r; + } + }; + } + + } + +} diff --git a/soluzione appelli/Scritto PO2 14 6 24/cpp/Appello_14_6_24/Appello_14_6_24.cpp b/soluzione appelli/Scritto PO2 14 6 24/cpp/Appello_14_6_24/Appello_14_6_24.cpp new file mode 100644 index 0000000..df04c28 --- /dev/null +++ b/soluzione appelli/Scritto PO2 14 6 24/cpp/Appello_14_6_24/Appello_14_6_24.cpp @@ -0,0 +1,35 @@ + +// Questo sorgente contiene le soluzioni dell'esame scritto di PO2 del 5/9/2023 per ciò che riguarda il quesito 2, ovvero la domanda che coinvolge C++. +// I quesiti 1-5 riguardanti Java sono in un sorgente Java a parte, non qui. +// Il codice C++ qui esposto è standard C++ vanilla (a.k.a. C++03), sebbene il progetto VS sia configurato con il compilatore di default C++14 + +#include +#include + +using namespace std; + +template +ostream& operator<<(ostream& os, const Container& c) +{ + os << "["; + for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) + os << " " << *it; + os << "]"; + return os; +} + +template +typename Container::value_type sum(const Container& c) +{ + typename Container::value_type r; + for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) + { + r += *it; + } + return r; +} + + +int main() +{ +} diff --git a/soluzione appelli/Scritto PO2 14 6 24/cpp/Appello_14_6_24/Appello_14_6_24.sln b/soluzione appelli/Scritto PO2 14 6 24/cpp/Appello_14_6_24/Appello_14_6_24.sln new file mode 100644 index 0000000..9683cae --- /dev/null +++ b/soluzione appelli/Scritto PO2 14 6 24/cpp/Appello_14_6_24/Appello_14_6_24.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.2.32526.322 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Appello_14_6_24", "Appello_14_6_24.vcxproj", "{C7C15495-50AD-4636-90B2-C312702B99FD}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C7C15495-50AD-4636-90B2-C312702B99FD}.Debug|x64.ActiveCfg = Debug|x64 + {C7C15495-50AD-4636-90B2-C312702B99FD}.Debug|x64.Build.0 = Debug|x64 + {C7C15495-50AD-4636-90B2-C312702B99FD}.Debug|x86.ActiveCfg = Debug|Win32 + {C7C15495-50AD-4636-90B2-C312702B99FD}.Debug|x86.Build.0 = Debug|Win32 + {C7C15495-50AD-4636-90B2-C312702B99FD}.Release|x64.ActiveCfg = Release|x64 + {C7C15495-50AD-4636-90B2-C312702B99FD}.Release|x64.Build.0 = Release|x64 + {C7C15495-50AD-4636-90B2-C312702B99FD}.Release|x86.ActiveCfg = Release|Win32 + {C7C15495-50AD-4636-90B2-C312702B99FD}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {49DE568A-D54C-485E-A095-5948A84AED91} + EndGlobalSection +EndGlobal diff --git a/soluzione appelli/Scritto PO2 14 6 24/cpp/Appello_14_6_24/Appello_14_6_24.vcxproj b/soluzione appelli/Scritto PO2 14 6 24/cpp/Appello_14_6_24/Appello_14_6_24.vcxproj new file mode 100644 index 0000000..748b08d --- /dev/null +++ b/soluzione appelli/Scritto PO2 14 6 24/cpp/Appello_14_6_24/Appello_14_6_24.vcxproj @@ -0,0 +1,135 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 16.0 + Win32Proj + {C7C15495-50AD-4636-90B2-C312702B99FD} + Appello3622 + 10.0 + + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + + + + + + + + + + + + + + + + + + + + Level3 + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + Level4 + true + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 14 6 24/cpp/Appello_14_6_24/Appello_14_6_24.vcxproj.user b/soluzione appelli/Scritto PO2 14 6 24/cpp/Appello_14_6_24/Appello_14_6_24.vcxproj.user new file mode 100644 index 0000000..88a5509 --- /dev/null +++ b/soluzione appelli/Scritto PO2 14 6 24/cpp/Appello_14_6_24/Appello_14_6_24.vcxproj.user @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 14 6 24/java/.gitignore b/soluzione appelli/Scritto PO2 14 6 24/java/.gitignore new file mode 100644 index 0000000..f68d109 --- /dev/null +++ b/soluzione appelli/Scritto PO2 14 6 24/java/.gitignore @@ -0,0 +1,29 @@ +### 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 diff --git a/soluzione appelli/Scritto PO2 14 6 24/java/.idea/.gitignore b/soluzione appelli/Scritto PO2 14 6 24/java/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/soluzione appelli/Scritto PO2 14 6 24/java/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/soluzione appelli/Scritto PO2 14 6 24/java/.idea/codeStyles/Project.xml b/soluzione appelli/Scritto PO2 14 6 24/java/.idea/codeStyles/Project.xml new file mode 100644 index 0000000..919ce1f --- /dev/null +++ b/soluzione appelli/Scritto PO2 14 6 24/java/.idea/codeStyles/Project.xml @@ -0,0 +1,7 @@ + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 14 6 24/java/.idea/codeStyles/codeStyleConfig.xml b/soluzione appelli/Scritto PO2 14 6 24/java/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 0000000..a55e7a1 --- /dev/null +++ b/soluzione appelli/Scritto PO2 14 6 24/java/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 14 6 24/java/.idea/misc.xml b/soluzione appelli/Scritto PO2 14 6 24/java/.idea/misc.xml new file mode 100644 index 0000000..cd639fe --- /dev/null +++ b/soluzione appelli/Scritto PO2 14 6 24/java/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 14 6 24/java/.idea/modules.xml b/soluzione appelli/Scritto PO2 14 6 24/java/.idea/modules.xml new file mode 100644 index 0000000..0c9761c --- /dev/null +++ b/soluzione appelli/Scritto PO2 14 6 24/java/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 14 6 24/java/Scritto PO2 13 6 24.iml b/soluzione appelli/Scritto PO2 14 6 24/java/Scritto PO2 13 6 24.iml new file mode 100644 index 0000000..c90834f --- /dev/null +++ b/soluzione appelli/Scritto PO2 14 6 24/java/Scritto PO2 13 6 24.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 14 6 24/java/src/Es1.java b/soluzione appelli/Scritto PO2 14 6 24/java/src/Es1.java new file mode 100644 index 0000000..793f487 --- /dev/null +++ b/soluzione appelli/Scritto PO2 14 6 24/java/src/Es1.java @@ -0,0 +1,85 @@ +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; + +public class Es1 { + + public static Iterator mapIterator(Iterator it, Function f) { + return new Iterator<>() { + @Override + public boolean hasNext() { + return it.hasNext(); + } + + @Override + public B next() { + return f.apply(it.next()); + } + }; + } + + public static void forEach(Iterable it, Consumer f) { + for (T x : it) + f.accept(x); + } + + public static class Pair { + public final X fst; + public final Y snd; + public Pair(X x, Y y) { + fst = x; + snd = y; + } + } + + public static void main1(String[] args) { + List, String>> l = new ArrayList<>(); + Iterator it = mapIterator(l.iterator(), (p) -> p.fst.apply(p.snd)); + } + + public static Iterator applyFuns(Iterable, A>> l) { + return mapIterator(l.iterator(), (p) -> p.fst.apply(p.snd)); + } + + public static void main2(String[] args) { + List, Integer>> l = new ArrayList<>(); + forEach(l, (p) -> p.fst.accept(p.snd)); + } + + public static void acceptFuns(Iterable, A>> l) { + forEach(l, (p) -> p.fst.accept(p.snd)); + } + + public static Iterator> asyncMapIterator(Iterator it, Function f) { + return new Iterator<>() { + @Override + public boolean hasNext() { + return it.hasNext(); + } + + @Override + public Supplier next() { + final A x = it.next(); + final B[] r = (B[]) new Object[1]; + Thread t = new Thread(() -> { r[0] = f.apply(x); }); + t.start(); + return () -> { + try { + t.join(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + return r[0]; + }; + } + }; + } + + public static void asyncForEach(Iterable it, Consumer f) { + for (T x : it) + new Thread(() -> f.accept(x)).start(); + } +} diff --git a/soluzione appelli/Scritto PO2 15 9 25/cpp/Appello_15_9_25/Appello_15_9_25.cpp b/soluzione appelli/Scritto PO2 15 9 25/cpp/Appello_15_9_25/Appello_15_9_25.cpp new file mode 100644 index 0000000..e8e88f5 --- /dev/null +++ b/soluzione appelli/Scritto PO2 15 9 25/cpp/Appello_15_9_25/Appello_15_9_25.cpp @@ -0,0 +1,29 @@ +// Appello_15_9_25.cpp +// + +#include +#include + +using namespace std; + +template +typename InputIterator::value_type average(InputIterator begin, InputIterator end) +{ + typename iterator_traits::value_type r{}; // chiamiamo esplcitamente il costruttore di default con la sintassi di C++14 (perché MSVS non supporta più il vanilla) + //anche InputIterator::value_type andava bene + + size_t n = 0; + for (; begin != end; ++n) + r += *begin++; // il value_type deve avere l'operatore += + if (n == 0) + throw runtime_error("average of empty range"); + return r / n; // e l'opereratore / con size_t some secondo argomento +} + + +int main() +{ + vector v = { 1, 2, 3, 4, 5 }; + cout << average(v.begin(), v.end()) << endl; +} + diff --git a/soluzione appelli/Scritto PO2 15 9 25/cpp/Appello_15_9_25/Appello_15_9_25.sln b/soluzione appelli/Scritto PO2 15 9 25/cpp/Appello_15_9_25/Appello_15_9_25.sln new file mode 100644 index 0000000..d1024f1 --- /dev/null +++ b/soluzione appelli/Scritto PO2 15 9 25/cpp/Appello_15_9_25/Appello_15_9_25.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.14.36429.23 d17.14 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Appello_15_9_25", "Appello_15_9_25.vcxproj", "{EAC4145E-6577-4D78-9117-35B81B4A4ADE}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {EAC4145E-6577-4D78-9117-35B81B4A4ADE}.Debug|x64.ActiveCfg = Debug|x64 + {EAC4145E-6577-4D78-9117-35B81B4A4ADE}.Debug|x64.Build.0 = Debug|x64 + {EAC4145E-6577-4D78-9117-35B81B4A4ADE}.Debug|x86.ActiveCfg = Debug|Win32 + {EAC4145E-6577-4D78-9117-35B81B4A4ADE}.Debug|x86.Build.0 = Debug|Win32 + {EAC4145E-6577-4D78-9117-35B81B4A4ADE}.Release|x64.ActiveCfg = Release|x64 + {EAC4145E-6577-4D78-9117-35B81B4A4ADE}.Release|x64.Build.0 = Release|x64 + {EAC4145E-6577-4D78-9117-35B81B4A4ADE}.Release|x86.ActiveCfg = Release|Win32 + {EAC4145E-6577-4D78-9117-35B81B4A4ADE}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {24327C14-2D26-49B5-A017-9A80DAEEC947} + EndGlobalSection +EndGlobal diff --git a/soluzione appelli/Scritto PO2 15 9 25/cpp/Appello_15_9_25/Appello_15_9_25.vcxproj b/soluzione appelli/Scritto PO2 15 9 25/cpp/Appello_15_9_25/Appello_15_9_25.vcxproj new file mode 100644 index 0000000..e912a6a --- /dev/null +++ b/soluzione appelli/Scritto PO2 15 9 25/cpp/Appello_15_9_25/Appello_15_9_25.vcxproj @@ -0,0 +1,131 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 17.0 + Win32Proj + {eac4145e-6577-4d78-9117-35b81b4a4ade} + Appello15925 + 10.0 + + + + Application + true + v145 + Unicode + + + Application + false + v145 + true + Unicode + + + Application + true + v145 + Unicode + + + Application + false + v145 + true + Unicode + + + + + + + + + + + + + + + + + + + + + + Level3 + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 15 9 25/cpp/Appello_15_9_25/Appello_15_9_25.vcxproj.filters b/soluzione appelli/Scritto PO2 15 9 25/cpp/Appello_15_9_25/Appello_15_9_25.vcxproj.filters new file mode 100644 index 0000000..9f933e4 --- /dev/null +++ b/soluzione appelli/Scritto PO2 15 9 25/cpp/Appello_15_9_25/Appello_15_9_25.vcxproj.filters @@ -0,0 +1,22 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 15 9 25/cpp/Appello_15_9_25/Appello_15_9_25.vcxproj.user b/soluzione appelli/Scritto PO2 15 9 25/cpp/Appello_15_9_25/Appello_15_9_25.vcxproj.user new file mode 100644 index 0000000..88a5509 --- /dev/null +++ b/soluzione appelli/Scritto PO2 15 9 25/cpp/Appello_15_9_25/Appello_15_9_25.vcxproj.user @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 15 9 25/java/Scritto PO2 15 9 25/.gitignore b/soluzione appelli/Scritto PO2 15 9 25/java/Scritto PO2 15 9 25/.gitignore new file mode 100644 index 0000000..f68d109 --- /dev/null +++ b/soluzione appelli/Scritto PO2 15 9 25/java/Scritto PO2 15 9 25/.gitignore @@ -0,0 +1,29 @@ +### 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 diff --git a/soluzione appelli/Scritto PO2 15 9 25/java/Scritto PO2 15 9 25/.idea/.gitignore b/soluzione appelli/Scritto PO2 15 9 25/java/Scritto PO2 15 9 25/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/soluzione appelli/Scritto PO2 15 9 25/java/Scritto PO2 15 9 25/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/soluzione appelli/Scritto PO2 15 9 25/java/Scritto PO2 15 9 25/.idea/misc.xml b/soluzione appelli/Scritto PO2 15 9 25/java/Scritto PO2 15 9 25/.idea/misc.xml new file mode 100644 index 0000000..31e1ebc --- /dev/null +++ b/soluzione appelli/Scritto PO2 15 9 25/java/Scritto PO2 15 9 25/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 15 9 25/java/Scritto PO2 15 9 25/.idea/modules.xml b/soluzione appelli/Scritto PO2 15 9 25/java/Scritto PO2 15 9 25/.idea/modules.xml new file mode 100644 index 0000000..4d0b0cf --- /dev/null +++ b/soluzione appelli/Scritto PO2 15 9 25/java/Scritto PO2 15 9 25/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 15 9 25/java/Scritto PO2 15 9 25/Scritto PO2 15 9 25.iml b/soluzione appelli/Scritto PO2 15 9 25/java/Scritto PO2 15 9 25/Scritto PO2 15 9 25.iml new file mode 100644 index 0000000..c90834f --- /dev/null +++ b/soluzione appelli/Scritto PO2 15 9 25/java/Scritto PO2 15 9 25/Scritto PO2 15 9 25.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 15 9 25/java/Scritto PO2 15 9 25/src/Es1.java b/soluzione appelli/Scritto PO2 15 9 25/java/Scritto PO2 15 9 25/src/Es1.java new file mode 100644 index 0000000..467efef --- /dev/null +++ b/soluzione appelli/Scritto PO2 15 9 25/java/Scritto PO2 15 9 25/src/Es1.java @@ -0,0 +1,23 @@ +import javax.script.Bindings; +import java.time.Instant; +import java.util.*; +import java.util.function.Consumer; + +public class Es1 { + public enum Priority { HIGH, MEDIUM, LOW }; + + private Map> map = new EnumMap<>(Priority.class); + + public void register(Priority priority, Consumer consumer) { + map.put(priority, consumer); + } + + public void dispatcher() { + SortedSet>> set = new TreeSet<>(Comparator.comparing(Map.Entry::getKey)); + set.addAll(map.entrySet()); + for (Map.Entry> p : set) { + p.getValue().accept(Instant.now()); + } + } + +} diff --git a/soluzione appelli/Scritto PO2 20 6 19/Scritto PO2 20 6 19.iml b/soluzione appelli/Scritto PO2 20 6 19/Scritto PO2 20 6 19.iml index 1a7f0f7..c90834f 100644 --- a/soluzione appelli/Scritto PO2 20 6 19/Scritto PO2 20 6 19.iml +++ b/soluzione appelli/Scritto PO2 20 6 19/Scritto PO2 20 6 19.iml @@ -7,14 +7,5 @@ - - - - - - - - - \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 22 1 19/.idea/vcs.xml b/soluzione appelli/Scritto PO2 22 1 19/.idea/vcs.xml new file mode 100644 index 0000000..b2bdec2 --- /dev/null +++ b/soluzione appelli/Scritto PO2 22 1 19/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 22 1 19/.idea/workspace.xml b/soluzione appelli/Scritto PO2 22 1 19/.idea/workspace.xml index bd71a55..aa0b220 100644 --- a/soluzione appelli/Scritto PO2 22 1 19/.idea/workspace.xml +++ b/soluzione appelli/Scritto PO2 22 1 19/.idea/workspace.xml @@ -7,11 +7,9 @@ - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + @@ -103,14 +80,15 @@ - - - - - - - + + + @@ -119,18 +97,6 @@ - - - + @@ -208,9 +175,9 @@ - - - + + + diff --git a/soluzione appelli/Scritto PO2 25 6 24/cpp/Appello_25_6_24/Appello_25_6_24.cpp b/soluzione appelli/Scritto PO2 25 6 24/cpp/Appello_25_6_24/Appello_25_6_24.cpp new file mode 100644 index 0000000..106371f --- /dev/null +++ b/soluzione appelli/Scritto PO2 25 6 24/cpp/Appello_25_6_24/Appello_25_6_24.cpp @@ -0,0 +1,81 @@ + +// Questo sorgente contiene le soluzioni dell'esame scritto di PO2 del 25/6/2024 per ciò che riguarda il quesito 2, ovvero la domanda che coinvolge C++. +// I quesiti 1-5 riguardanti Java sono in un sorgente Java a parte, non qui. +// Il codice C++ qui esposto è standard C++ vanilla (a.k.a. C++03), sebbene il progetto VS sia configurato con il compilatore di default C++14 + +#include +#include + +using namespace std; + +template +class matrix +{ +private: + size_t cols; + vector v; + +public: + matrix() : cols(0), v() {} + matrix(const matrix& m) : cols(m.cols), v(m.v) {} + matrix(size_t rows, size_t cols_, const T& v = T()) : cols(cols_), v(rows* cols, v) {} + + typedef T value_type; + typedef typename vector::iterator iterator; + typedef typename vector::const_iterator const_iterator; + + matrix& operator=(const matrix& m) + { + v = m.v; + return *this; + } + + T& operator()(size_t i, size_t j) + { + return v[i * cols + j]; + } + + const T& operator()(size_t i, size_t j) const + { + return (*this)(i, j); + } + + iterator begin() + { + return v.begin(); + } + + iterator end() + { + return v.end(); + } + + const_iterator begin() const + { + return begin(); + } + + const_iterator end() const + { + return end(); + } +}; + + +int main() +{ + matrix m1; // non inizializzata + matrix m2(10, 20); // 10*20 inizializzata col default constructor di double + matrix m3(m2); // costruita per copia + m1 = m2; // assegnamento + m3(3, 1) = 11.23; // operatore di accesso come left-value + + for (typename matrix::iterator it = m1.begin(); it != m1.end(); ++it) { + typename matrix::value_type& x = *it; // de-reference non-const + x = m2(0, 2); // operatore di accesso come right-value + } + + matrix ms(5, 4, "ciao"); // 5*4 inizializzata col la stringa passata come terzo argomento + for (typename matrix::const_iterator it = ms.begin(); it != ms.end(); ++it) + cout << *it; // de-reference const +} diff --git a/soluzione appelli/Scritto PO2 25 6 24/cpp/Appello_25_6_24/Appello_25_6_24.sln b/soluzione appelli/Scritto PO2 25 6 24/cpp/Appello_25_6_24/Appello_25_6_24.sln new file mode 100644 index 0000000..22261e2 --- /dev/null +++ b/soluzione appelli/Scritto PO2 25 6 24/cpp/Appello_25_6_24/Appello_25_6_24.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.2.32526.322 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Appello_25_6_24", "Appello_25_6_24.vcxproj", "{C7C15495-50AD-4636-90B2-C312702B99FD}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C7C15495-50AD-4636-90B2-C312702B99FD}.Debug|x64.ActiveCfg = Debug|x64 + {C7C15495-50AD-4636-90B2-C312702B99FD}.Debug|x64.Build.0 = Debug|x64 + {C7C15495-50AD-4636-90B2-C312702B99FD}.Debug|x86.ActiveCfg = Debug|Win32 + {C7C15495-50AD-4636-90B2-C312702B99FD}.Debug|x86.Build.0 = Debug|Win32 + {C7C15495-50AD-4636-90B2-C312702B99FD}.Release|x64.ActiveCfg = Release|x64 + {C7C15495-50AD-4636-90B2-C312702B99FD}.Release|x64.Build.0 = Release|x64 + {C7C15495-50AD-4636-90B2-C312702B99FD}.Release|x86.ActiveCfg = Release|Win32 + {C7C15495-50AD-4636-90B2-C312702B99FD}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {49DE568A-D54C-485E-A095-5948A84AED91} + EndGlobalSection +EndGlobal diff --git a/soluzione appelli/Scritto PO2 25 6 24/cpp/Appello_25_6_24/Appello_25_6_24.vcxproj b/soluzione appelli/Scritto PO2 25 6 24/cpp/Appello_25_6_24/Appello_25_6_24.vcxproj new file mode 100644 index 0000000..f7c2f90 --- /dev/null +++ b/soluzione appelli/Scritto PO2 25 6 24/cpp/Appello_25_6_24/Appello_25_6_24.vcxproj @@ -0,0 +1,135 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 16.0 + Win32Proj + {C7C15495-50AD-4636-90B2-C312702B99FD} + Appello3622 + 10.0 + + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + + + + + + + + + + + + + + + + + + + + Level3 + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + Level4 + true + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 25 6 24/cpp/Appello_25_6_24/Appello_25_6_24.vcxproj.user b/soluzione appelli/Scritto PO2 25 6 24/cpp/Appello_25_6_24/Appello_25_6_24.vcxproj.user new file mode 100644 index 0000000..88a5509 --- /dev/null +++ b/soluzione appelli/Scritto PO2 25 6 24/cpp/Appello_25_6_24/Appello_25_6_24.vcxproj.user @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 25 6 24/java/.gitignore b/soluzione appelli/Scritto PO2 25 6 24/java/.gitignore new file mode 100644 index 0000000..f68d109 --- /dev/null +++ b/soluzione appelli/Scritto PO2 25 6 24/java/.gitignore @@ -0,0 +1,29 @@ +### 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 diff --git a/soluzione appelli/Scritto PO2 25 6 24/java/.idea/.gitignore b/soluzione appelli/Scritto PO2 25 6 24/java/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/soluzione appelli/Scritto PO2 25 6 24/java/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/soluzione appelli/Scritto PO2 25 6 24/java/.idea/codeStyles/Project.xml b/soluzione appelli/Scritto PO2 25 6 24/java/.idea/codeStyles/Project.xml new file mode 100644 index 0000000..919ce1f --- /dev/null +++ b/soluzione appelli/Scritto PO2 25 6 24/java/.idea/codeStyles/Project.xml @@ -0,0 +1,7 @@ + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 25 6 24/java/.idea/codeStyles/codeStyleConfig.xml b/soluzione appelli/Scritto PO2 25 6 24/java/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 0000000..a55e7a1 --- /dev/null +++ b/soluzione appelli/Scritto PO2 25 6 24/java/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 25 6 24/java/.idea/misc.xml b/soluzione appelli/Scritto PO2 25 6 24/java/.idea/misc.xml new file mode 100644 index 0000000..cd639fe --- /dev/null +++ b/soluzione appelli/Scritto PO2 25 6 24/java/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 25 6 24/java/.idea/modules.xml b/soluzione appelli/Scritto PO2 25 6 24/java/.idea/modules.xml new file mode 100644 index 0000000..0c9761c --- /dev/null +++ b/soluzione appelli/Scritto PO2 25 6 24/java/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 25 6 24/java/Scritto PO2 25 6 24.iml b/soluzione appelli/Scritto PO2 25 6 24/java/Scritto PO2 25 6 24.iml new file mode 100644 index 0000000..c90834f --- /dev/null +++ b/soluzione appelli/Scritto PO2 25 6 24/java/Scritto PO2 25 6 24.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 25 6 24/java/src/.idea/.gitignore b/soluzione appelli/Scritto PO2 25 6 24/java/src/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/soluzione appelli/Scritto PO2 25 6 24/java/src/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/soluzione appelli/Scritto PO2 25 6 24/java/src/.idea/misc.xml b/soluzione appelli/Scritto PO2 25 6 24/java/src/.idea/misc.xml new file mode 100644 index 0000000..1b2d693 --- /dev/null +++ b/soluzione appelli/Scritto PO2 25 6 24/java/src/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 25 6 24/java/src/.idea/modules.xml b/soluzione appelli/Scritto PO2 25 6 24/java/src/.idea/modules.xml new file mode 100644 index 0000000..76859a0 --- /dev/null +++ b/soluzione appelli/Scritto PO2 25 6 24/java/src/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 25 6 24/java/src/Es1.java b/soluzione appelli/Scritto PO2 25 6 24/java/src/Es1.java new file mode 100644 index 0000000..2bfc1b8 --- /dev/null +++ b/soluzione appelli/Scritto PO2 25 6 24/java/src/Es1.java @@ -0,0 +1,142 @@ +import java.util.*; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; + +public class Es1 { + + // 1.a + public static class Point { + public final double x, y; + + public Point(double x, double y) { + this.x = x; + this.y = y; + } + } + + // 1.b + public static class Segment { + public final Point a, b; + + public Segment(Point a, Point b) { + this.a = a; + this.b = b; + } + + public double length() { + return Math.sqrt(Math.pow(b.x - a.x, 2) + Math.pow(b.y - a.y, 2)); + } + } + + // 1.c + public static abstract class Polygon implements Iterable { + protected final List points; + + protected Polygon(List points) { + assert points.size() >= 3; + this.points = points; + } + + public Iterator iterator() { + return new Iterator() { + private int i = 0; + + @Override + public boolean hasNext() { + return i < points.size(); + } + + @Override + public Segment next() { + return new Segment(points.get(i++), points.get(i % points.size())); + } + }; + } + + public double perimeter() { + double r = 0.; + for (Segment s : this) + r += s.length(); + return r; + } + + public abstract double area(); + } + + // 1.d.i + public static class Triangle extends Polygon { + public Triangle(Point p1, Point p2, Point p3) { + super(List.of(p1, p2, p3)); + } + + @Override + public double area() { + double p = perimeter() / 2.; + List segs = new ArrayList<>(); + for (Segment s : this) segs.add(s.length()); + return Math.sqrt(p * (p - segs.get(0)) * (p - segs.get(1)) * (p - segs.get(2))); + } + } + + // 1.d.ii + public static class Rectangle extends Polygon { + public Rectangle(Point p1, Point p3) { + super(List.of(p1, new Point(p3.x, p1.y), p3, new Point(p1.x, p3.y))); + } + + @Override + public double area() { + Iterator it = iterator(); + double b = it.next().length(), h = it.next().length(); + return b * h; + } + } + + // 1.d.iii + public static class Square extends Rectangle { + public Square(Point p1, double side) { + super(p1, new Point(p1.x + side, p1.y + side)); + } + + // 1.d.iv + // In generale non vale la pena fare questo override. + // Sicuramente non è necessario perché il metodo area() ereditato da Rectangle è più che sufficiente. + // Volendo si può fare un ragionamento sulla performance: calcolare il lato e poi calcolarne il quadrato è + // più performante rispetto a pescare i primi due lati dall'iteratore di Segment e moltiplicarne le lunghezze, + // però parliamo di un vantaggio davvero negligibile. + @Override + public double area() { + // Il costruttore potrebbe salvare side in un campo ed evitare la seguente sottrazione + // ma sarebbe una replicazione di dati non molto elegante. + double side = points.get(1).x - points.get(0).x; + return side * side; + } + } + + // 1.e.i + public static void main(String args[]) { + Square sq1 = new Square(new Point(11.235, -8.53), 0.1), + sq2 = new Square(new Point(1., 20.), 0.01), + sq3 = new Square(new Point(0., 0.), 0.2); + List squares = new ArrayList<>(); // nel testo d'esame qui c'era List.of(sq1, sq2, sq3) per brevità + squares.add(sq1); // ma List.of() produce liste immutabili, che non possono essere ordinate + squares.add(sq2); // quindi qui abbiamo fatto un arraylist popolato a mano + squares.add(sq3); + Square r = min(squares, (a, b) -> (int) (a.area() - b.area())); + } + + static T min(List l, Comparator c) { + Collections.sort(l, c); + return l.get(0); + } + + // 1.e.ii + // sq1 == r + // ATTENZIONE: il quadrato con l'area più piccola teoricamente è sq2; tuttavia a causa del cast a int nella lambda + // del Comparator tutte le differenze tra le aree vengono arrotondate a 0. L'algoritmo di sorting è stabile sull'ordine originale + // degli elementi, quindi alla fine viene fuori sq1 semplicemente perché è il primo della lista. + // Le altre opzioni possibili nel testo dell'esame sono tutte false; in particolar modo quelle che usano equals(), + // perché non c'è nessun override di equals() per la classe Square, quindi viene invocata la versione ereditata + // da Object che restituisce false di default. +} diff --git a/soluzione appelli/Scritto PO2 25 6 24/java/src/Scritto PO2 25 6 24.iml b/soluzione appelli/Scritto PO2 25 6 24/java/src/Scritto PO2 25 6 24.iml new file mode 100644 index 0000000..b107a2d --- /dev/null +++ b/soluzione appelli/Scritto PO2 25 6 24/java/src/Scritto PO2 25 6 24.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 3 6 22/Scritto PO2 3 6 22.iml b/soluzione appelli/Scritto PO2 3 6 22/Scritto PO2 3 6 22.iml new file mode 100644 index 0000000..e13cb1e --- /dev/null +++ b/soluzione appelli/Scritto PO2 3 6 22/Scritto PO2 3 6 22.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 3 6 22/cpp/Appello_3_6_22/Appello_3_6_22.cpp b/soluzione appelli/Scritto PO2 3 6 22/cpp/Appello_3_6_22/Appello_3_6_22.cpp new file mode 100644 index 0000000..b8a2c83 --- /dev/null +++ b/soluzione appelli/Scritto PO2 3 6 22/cpp/Appello_3_6_22/Appello_3_6_22.cpp @@ -0,0 +1,83 @@ + +// Questo sorgente contiene le soluzioni dell'esame scritto di PO2 del 3/6/2022 per ciò che riguarda il quesito 6, ovvero la domanda che coinvolge C++. +// I quesiti 1-5 riguardanti Java sono in un progetto IntelliJ a parte, non qui. +// Il codice C++ qui esposto è standard C++ vanilla (a.k.a. C++03), sebbene il progetto VS sia configurato con il compilatore di default C++14 + +#include +#include + +using namespace std; + +// 6 +template +class matrix +{ +private: + size_t cols; + vector v; + +public: + matrix() : cols(0), v() {} + matrix(size_t rows, size_t cols_) : cols(cols_), v(rows * cols) {} + matrix(size_t rows, size_t cols_, const T& v) : cols(cols_), v(rows* cols, v) {} + matrix(const matrix& m) : cols(m.cols), v(m.v) {} + + typedef T value_type; + typedef typename vector::iterator iterator; + typedef typename vector::const_iterator const_iterator; + + matrix& operator=(const matrix& m) + { + v = m.v; + return *this; + } + + T& operator()(size_t i, size_t j) + { + return v[i * cols + j]; + } + + const T& operator()(size_t i, size_t j) const + { + return (*this)(i, j); + } + + iterator begin() + { + return v.begin(); + } + + iterator end() + { + return v.end(); + } + + const_iterator begin() const + { + return begin(); + } + + const_iterator end() const + { + return end(); + } +}; + + +int main() +{ + matrix m1; // non inizializzata + matrix m2(10, 20); // 10*20 inizializzata col default constructor di double + matrix m3(m2); // costruita per copia + m1 = m2; // assegnamento + m3(3, 1) = 11.23; // operatore di accesso come left-value + + for (typename matrix::iterator it = m1.begin(); it != m1.end(); ++it) { + typename matrix::value_type& x = *it; // de-reference non-const + x = m2(0, 2); // operatore di accesso come right-value + } + + matrix ms(5, 4, "ciao"); // 5*4 inizializzata col la stringa passata come terzo argomento + for (typename matrix::const_iterator it = ms.begin(); it != ms.end(); ++it) + cout << *it; // de-reference const +} diff --git a/soluzione appelli/Scritto PO2 3 6 22/cpp/Appello_3_6_22/Appello_3_6_22.sln b/soluzione appelli/Scritto PO2 3 6 22/cpp/Appello_3_6_22/Appello_3_6_22.sln new file mode 100644 index 0000000..160d856 --- /dev/null +++ b/soluzione appelli/Scritto PO2 3 6 22/cpp/Appello_3_6_22/Appello_3_6_22.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.2.32526.322 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Appello_3_6_22", "Appello_3_6_22.vcxproj", "{134AAFA0-F15F-4F91-B364-962161EC5D7F}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {134AAFA0-F15F-4F91-B364-962161EC5D7F}.Debug|x64.ActiveCfg = Debug|x64 + {134AAFA0-F15F-4F91-B364-962161EC5D7F}.Debug|x64.Build.0 = Debug|x64 + {134AAFA0-F15F-4F91-B364-962161EC5D7F}.Debug|x86.ActiveCfg = Debug|Win32 + {134AAFA0-F15F-4F91-B364-962161EC5D7F}.Debug|x86.Build.0 = Debug|Win32 + {134AAFA0-F15F-4F91-B364-962161EC5D7F}.Release|x64.ActiveCfg = Release|x64 + {134AAFA0-F15F-4F91-B364-962161EC5D7F}.Release|x64.Build.0 = Release|x64 + {134AAFA0-F15F-4F91-B364-962161EC5D7F}.Release|x86.ActiveCfg = Release|Win32 + {134AAFA0-F15F-4F91-B364-962161EC5D7F}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {49DE568A-D54C-485E-A095-5948A84AED91} + EndGlobalSection +EndGlobal diff --git a/soluzione appelli/Scritto PO2 3 6 22/cpp/Appello_3_6_22/Appello_3_6_22.vcxproj b/soluzione appelli/Scritto PO2 3 6 22/cpp/Appello_3_6_22/Appello_3_6_22.vcxproj new file mode 100644 index 0000000..04e7e58 --- /dev/null +++ b/soluzione appelli/Scritto PO2 3 6 22/cpp/Appello_3_6_22/Appello_3_6_22.vcxproj @@ -0,0 +1,135 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 16.0 + Win32Proj + {134aafa0-f15f-4f91-b364-962161ec5d7f} + Appello3622 + 10.0 + + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + + + + + + + + + + + + + + + + + + + + Level3 + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + Level4 + true + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 3 6 22/cpp/Appello_3_6_22/Appello_3_6_22.vcxproj.filters b/soluzione appelli/Scritto PO2 3 6 22/cpp/Appello_3_6_22/Appello_3_6_22.vcxproj.filters new file mode 100644 index 0000000..7676feb --- /dev/null +++ b/soluzione appelli/Scritto PO2 3 6 22/cpp/Appello_3_6_22/Appello_3_6_22.vcxproj.filters @@ -0,0 +1,22 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 3 6 22/cpp/Appello_3_6_22/Appello_3_6_22.vcxproj.user b/soluzione appelli/Scritto PO2 3 6 22/cpp/Appello_3_6_22/Appello_3_6_22.vcxproj.user new file mode 100644 index 0000000..88a5509 --- /dev/null +++ b/soluzione appelli/Scritto PO2 3 6 22/cpp/Appello_3_6_22/Appello_3_6_22.vcxproj.user @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 3 6 22/java/.idea/.gitignore b/soluzione appelli/Scritto PO2 3 6 22/java/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/soluzione appelli/Scritto PO2 3 6 22/java/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/soluzione appelli/Scritto PO2 3 6 22/java/.idea/.name b/soluzione appelli/Scritto PO2 3 6 22/java/.idea/.name new file mode 100644 index 0000000..8ba47ca --- /dev/null +++ b/soluzione appelli/Scritto PO2 3 6 22/java/.idea/.name @@ -0,0 +1 @@ +Appello_3_6_22.iml \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 3 6 22/java/.idea/codeStyles/codeStyleConfig.xml b/soluzione appelli/Scritto PO2 3 6 22/java/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 0000000..a55e7a1 --- /dev/null +++ b/soluzione appelli/Scritto PO2 3 6 22/java/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 3 6 22/java/.idea/inspectionProfiles/Project_Default.xml b/soluzione appelli/Scritto PO2 3 6 22/java/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 0000000..a8d3774 --- /dev/null +++ b/soluzione appelli/Scritto PO2 3 6 22/java/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,30 @@ + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 3 6 22/java/.idea/misc.xml b/soluzione appelli/Scritto PO2 3 6 22/java/.idea/misc.xml new file mode 100644 index 0000000..09e91bf --- /dev/null +++ b/soluzione appelli/Scritto PO2 3 6 22/java/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 3 6 22/java/.idea/modules.xml b/soluzione appelli/Scritto PO2 3 6 22/java/.idea/modules.xml new file mode 100644 index 0000000..82465c0 --- /dev/null +++ b/soluzione appelli/Scritto PO2 3 6 22/java/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 3 6 22/java/.idea/uiDesigner.xml b/soluzione appelli/Scritto PO2 3 6 22/java/.idea/uiDesigner.xml new file mode 100644 index 0000000..2b63946 --- /dev/null +++ b/soluzione appelli/Scritto PO2 3 6 22/java/.idea/uiDesigner.xml @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 3 6 22/java/.idea/vcs.xml b/soluzione appelli/Scritto PO2 3 6 22/java/.idea/vcs.xml new file mode 100644 index 0000000..c2365ab --- /dev/null +++ b/soluzione appelli/Scritto PO2 3 6 22/java/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 3 6 22/java/Appello_3_6_22.iml b/soluzione appelli/Scritto PO2 3 6 22/java/Appello_3_6_22.iml new file mode 100644 index 0000000..c90834f --- /dev/null +++ b/soluzione appelli/Scritto PO2 3 6 22/java/Appello_3_6_22.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 3 6 22/java/src/Appello_3_6_22.java b/soluzione appelli/Scritto PO2 3 6 22/java/src/Appello_3_6_22.java new file mode 100644 index 0000000..caf344a --- /dev/null +++ b/soluzione appelli/Scritto PO2 3 6 22/java/src/Appello_3_6_22.java @@ -0,0 +1,221 @@ +import java.util.*; +import java.util.function.BiFunction; +import java.util.function.Function; + +// Questo sorgente contiene le soluzioni dell'esame scritto di PO2 del 3/6/2022 per ciò che riguarda i quesiti 1-5, ovvero le domande che coinvolgono Java. +// Il quesito 6 riguardante C++ è in una Solution per Visual Studio a parte, non qui. + +public class Appello_3_6_22 { + + public static State fold(Iterable i, final State st0, BiFunction f) { + State st = st0; + for (final T e : i) { + st = f.apply(st, e); + } + return st; + } + + // 1.a + public static double sumBy(Iterable i, Function f) { + return fold(i, 0., (r, x) -> r + f.apply(x)); + } + + // 1.b + public static int compareBy(T s1, T s2, Function f) { + return Double.compare(f.apply(s1), f.apply(s2)); + } + + public static class Edge implements Comparable { + private final double len; + + public Edge(double len) { + this.len = len; + } + + public double length() { + return len; + } + + // 2.a + @Override + public int compareTo(Edge s) { + return compareBy(this, s, Edge::length); + } + } + + public interface Surface extends Comparable { + double area(); + + double perimiter(); + + // 2.b + @Override + default int compareTo(Surface s) { + return compareBy(this, s, Surface::area); + } + } + + public interface Polygon extends Surface, Iterable { + // 2.c + @Override + default double perimiter() { + return sumBy(this, Edge::length); + } + } + + public interface Solid extends Comparable { + double outerArea(); + + double volume(); + + // 2.d + default int compareTo(Solid s) { + return compareBy(this, s, Solid::volume); + } + } + + public interface Polyhedron

extends Solid, Iterable

{ + // 2.e + @Override + default double outerArea() { + return sumBy(this, P::area); + } + } + + // 3.a + public static class Sphere implements Solid { + private final double radius; + + public Sphere(double radius) { + this.radius = radius; + } + + @Override + public double outerArea() { + return 4. * Math.PI * radius * radius; + } + + @Override + public double volume() { + return 4. / 3. * Math.PI * radius * radius * radius; + } + } + + // 3.b + public static class Cilinder implements Solid { + private final double radius, height; + + public Cilinder(double radius, double height) { + this.radius = radius; + this.height = height; + } + + @Override + public double outerArea() { + double b = Math.PI * radius * radius, l = 2. * Math.PI * radius * height; // hanno capito solo laterale + return 2. * b + l; + } + + @Override + public double volume() { + return Math.PI * radius * radius * height; + } + } + + // 3.c + public static class Rectangle implements Polygon { + private final double width, height; + + public Rectangle(double width, double height) { + this.width = width; + this.height = height; + } + + @Override + public double area() { + return width * height; + } + + @Override + public Iterator iterator() { + Edge w = new Edge(width), h = new Edge(height); + return List.of(w, h, w, h).iterator(); + } + } + + // 3.d + public static class Square extends Rectangle { + public Square(double side) { + super(side, side); + } + } + + public static class Parallelepiped implements Polyhedron { + protected double width, height, depth; + + public Parallelepiped(double width, double height, double depth) { + this.width = width; + this.height = height; + this.depth = depth; + } + + // 4.a + @Override + public double volume() { + return width * height * depth; + } + + @Override + public Iterator iterator() { + Rectangle r1 = new Rectangle(width, height), r2 = new Rectangle(width, depth), r3 = new Rectangle(height, depth); + return List.of(r1, r2, r3, r1, r2, r3).iterator(); + } + } + + // 4.b + public static class Cube extends Parallelepiped { + public Cube(double side) { + super(side, side, side); + } + } + + + public static void main(String[] args) { + // 4.d + { + int facet_cnt = 1; + // questo foreach non compila perché Cube è sottotipo di Iterable, non di Iterable + // si badi che NON è possibile co-variare il tipo di ritorno del metodo iterator() di Cube in modo che si specializzi in Iterator + // perché è sound co-variare il tipo più esterno di un tipo parametrico, ma non il type argument + // for (Square sq : new Cube(10.)) { + for (Rectangle sq : new Cube(10.)) { // così invece compilerebbe + int side_cnt = 1; + for (Edge e : sq) { + System.out.printf("side #%d/%d = %f\n", side_cnt++, facet_cnt, e.length()); + } + ++facet_cnt; + } + } + + // 5 + { + Cube c1 = new Cube(1.), c2 = new Cube(2.); + Parallelepiped p1 = new Parallelepiped(1., 2., 3.), p2 = new Parallelepiped(2., 3., 4.); + List> polys = new ArrayList<>(List.of(c1, c2, p1, p2)); + + // per testare rapidamente i risultati di queste sort, si usi debugger + Collections.sort(polys); // c1 + Collections.sort(polys, (x, y) -> compareBy(x, y, Polyhedron::outerArea)); // c1 + Collections.sort(polys, (x, y) -> compareBy(x, y, (p) -> p.outerArea())); // c1 +// Collections.sort(polys, (x, y) -> compareBy(x, y, (r) -> r.perimiter())); // non compila + Collections.sort(polys, (x, y) -> compareBy(x, y, new Function<>() { // c1 + @Override + public Double apply(Polyhedron r) { + return r.volume(); + } + })); +// Collections.sort(polys, (x, y) -> Double.compare(sumBy(x, Square::perimiter), // non compila +// sumBy(y, Rectangle::perimiter))); + } + } +} diff --git a/soluzione appelli/Scritto PO2 30 5 19/.idea/.gitignore b/soluzione appelli/Scritto PO2 30 5 19/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/soluzione appelli/Scritto PO2 30 5 19/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/soluzione appelli/Scritto PO2 30 5 19/.idea/Scritto PO2 30 5 19.iml b/soluzione appelli/Scritto PO2 30 5 19/.idea/Scritto PO2 30 5 19.iml new file mode 100644 index 0000000..d6ebd48 --- /dev/null +++ b/soluzione appelli/Scritto PO2 30 5 19/.idea/Scritto PO2 30 5 19.iml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 30 5 19/.idea/codeStyles/codeStyleConfig.xml b/soluzione appelli/Scritto PO2 30 5 19/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 0000000..a55e7a1 --- /dev/null +++ b/soluzione appelli/Scritto PO2 30 5 19/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 30 5 19/.idea/misc.xml b/soluzione appelli/Scritto PO2 30 5 19/.idea/misc.xml new file mode 100644 index 0000000..ddb2beb --- /dev/null +++ b/soluzione appelli/Scritto PO2 30 5 19/.idea/misc.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 30 5 19/.idea/modules.xml b/soluzione appelli/Scritto PO2 30 5 19/.idea/modules.xml new file mode 100644 index 0000000..c20025c --- /dev/null +++ b/soluzione appelli/Scritto PO2 30 5 19/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 30 5 19/.idea/vcs.xml b/soluzione appelli/Scritto PO2 30 5 19/.idea/vcs.xml new file mode 100644 index 0000000..b2bdec2 --- /dev/null +++ b/soluzione appelli/Scritto PO2 30 5 19/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 30 5 19/src/Es3.java b/soluzione appelli/Scritto PO2 30 5 19/src/Es3.java index 03811f9..cd89349 100644 --- a/soluzione appelli/Scritto PO2 30 5 19/src/Es3.java +++ b/soluzione appelli/Scritto PO2 30 5 19/src/Es3.java @@ -13,6 +13,15 @@ public FactThread(int n) { this.n = n; } + private static int fact(int n) { + return n < 2 ? 1 : n * fact(n - 1); + } + + @Override + public void run() { + result = fact(n); + } + public int getResult() { return result; } @@ -23,7 +32,9 @@ public int getResult() { public static Collection multiFact(Collection ns) { Collection r = new ArrayList<>(); for (int n : ns) { - r.add(new FactThread(n)); + FactThread t = new FactThread(n); + t.start(); + r.add(t); } return r; } diff --git a/soluzione appelli/Scritto PO2 30 6 23/.gitignore b/soluzione appelli/Scritto PO2 30 6 23/.gitignore new file mode 100644 index 0000000..f68d109 --- /dev/null +++ b/soluzione appelli/Scritto PO2 30 6 23/.gitignore @@ -0,0 +1,29 @@ +### 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 diff --git a/soluzione appelli/Scritto PO2 30 6 23/cpp/Appello_30_6_23.sln b/soluzione appelli/Scritto PO2 30 6 23/cpp/Appello_30_6_23.sln new file mode 100644 index 0000000..6d7bfb9 --- /dev/null +++ b/soluzione appelli/Scritto PO2 30 6 23/cpp/Appello_30_6_23.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.3.32901.215 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Appello_30_6_23", "Appello_30_6_23.vcxproj", "{6A49BB9B-DE9D-46D5-BB18-BD13737F5026}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {6A49BB9B-DE9D-46D5-BB18-BD13737F5026}.Debug|x64.ActiveCfg = Debug|x64 + {6A49BB9B-DE9D-46D5-BB18-BD13737F5026}.Debug|x64.Build.0 = Debug|x64 + {6A49BB9B-DE9D-46D5-BB18-BD13737F5026}.Debug|x86.ActiveCfg = Debug|Win32 + {6A49BB9B-DE9D-46D5-BB18-BD13737F5026}.Debug|x86.Build.0 = Debug|Win32 + {6A49BB9B-DE9D-46D5-BB18-BD13737F5026}.Release|x64.ActiveCfg = Release|x64 + {6A49BB9B-DE9D-46D5-BB18-BD13737F5026}.Release|x64.Build.0 = Release|x64 + {6A49BB9B-DE9D-46D5-BB18-BD13737F5026}.Release|x86.ActiveCfg = Release|Win32 + {6A49BB9B-DE9D-46D5-BB18-BD13737F5026}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {66CDDA76-E424-4DD8-87CF-E87E03399139} + EndGlobalSection +EndGlobal diff --git a/soluzione appelli/Scritto PO2 30 6 23/cpp/Appello_30_6_23.vcxproj b/soluzione appelli/Scritto PO2 30 6 23/cpp/Appello_30_6_23.vcxproj new file mode 100644 index 0000000..e0c7fac --- /dev/null +++ b/soluzione appelli/Scritto PO2 30 6 23/cpp/Appello_30_6_23.vcxproj @@ -0,0 +1,137 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 16.0 + Win32Proj + {6A49BB9B-DE9D-46D5-BB18-BD13737F5026} + Appello13 + 10.0 + Appello_30_6_23 + + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + + + + + + + + + + + + + + + + + + + + Level3 + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + Level3 + true + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + stdcpp20 + + + Console + true + + + + + Level3 + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 30 6 23/cpp/Appello_30_6_23.vcxproj.user b/soluzione appelli/Scritto PO2 30 6 23/cpp/Appello_30_6_23.vcxproj.user new file mode 100644 index 0000000..88a5509 --- /dev/null +++ b/soluzione appelli/Scritto PO2 30 6 23/cpp/Appello_30_6_23.vcxproj.user @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 30 6 23/cpp/es2.ixx b/soluzione appelli/Scritto PO2 30 6 23/cpp/es2.ixx new file mode 100644 index 0000000..5da8c48 --- /dev/null +++ b/soluzione appelli/Scritto PO2 30 6 23/cpp/es2.ixx @@ -0,0 +1,80 @@ +export module pairs; + +import ; +import ; +import ; + +using namespace std; + +export +template +class fun_seq +{ +private: + const X a, b, dx; + const function f; + +public: + using value_type = pair; + + fun_seq(const X& _a, const X& _b, const X& _dx, const function& _f) : a(_a), b(_b), dx(_dx), f(_f) {} + + class iterator + { + private: + X x; + fun_seq that; + + public: + explicit iterator(const X& _x, const fun_seq& _that) : x(_x), that(_that) {} + + iterator(const iterator& it) : x(it.x), that(it.that) {} + + pair operator*() const + { + return pair(x, that.f(x)); + } + + bool operator!=(const iterator& it) + { + return !(x > it.x - that.dx && x < it.x + that.dx); + } + + iterator operator++() + { + iterator r(*this); + x += that.dx; + return r; + } + }; + + iterator begin() const + { + return iterator(a, *this); + } + + iterator end() const + { + return iterator(b, *this); + } + + +}; + + +export int main() +{ + fun_seq sq1(-2., 2., 0.1, [](const double& x) { return x * x + 2 * x - 1; }); + for (pair p : sq1) + cout << "f(" << p.first << ") = " << p.second << endl; + + fun_seq sq2(-2., 2., 0.1, [](const double& x) { return int(x * x + 2 * x - 1); }); + for (pair p : sq2) + cout << "f(" << p.first << ") = " << p.second << endl; + + return 0; +} + + + + diff --git a/soluzione appelli/Scritto PO2 30 6 23/java/.idea/.gitignore b/soluzione appelli/Scritto PO2 30 6 23/java/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/soluzione appelli/Scritto PO2 30 6 23/java/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/soluzione appelli/Scritto PO2 30 6 23/java/.idea/misc.xml b/soluzione appelli/Scritto PO2 30 6 23/java/.idea/misc.xml new file mode 100644 index 0000000..cf9abe6 --- /dev/null +++ b/soluzione appelli/Scritto PO2 30 6 23/java/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 30 6 23/java/.idea/modules.xml b/soluzione appelli/Scritto PO2 30 6 23/java/.idea/modules.xml new file mode 100644 index 0000000..4f87663 --- /dev/null +++ b/soluzione appelli/Scritto PO2 30 6 23/java/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 30 6 23/java/.idea/vcs.xml b/soluzione appelli/Scritto PO2 30 6 23/java/.idea/vcs.xml new file mode 100644 index 0000000..def3818 --- /dev/null +++ b/soluzione appelli/Scritto PO2 30 6 23/java/.idea/vcs.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 30 6 23/java/Scritto PO2 30_6_23.iml b/soluzione appelli/Scritto PO2 30 6 23/java/Scritto PO2 30_6_23.iml new file mode 100644 index 0000000..eda5e59 --- /dev/null +++ b/soluzione appelli/Scritto PO2 30 6 23/java/Scritto PO2 30_6_23.iml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 30 6 23/java/src/Es1.java b/soluzione appelli/Scritto PO2 30 6 23/java/src/Es1.java new file mode 100644 index 0000000..a925a9d --- /dev/null +++ b/soluzione appelli/Scritto PO2 30 6 23/java/src/Es1.java @@ -0,0 +1,84 @@ +import java.util.Iterator; +import java.util.function.Function; + +public class Es1 { + + // 1.a + public static class Pair { + public final A fst; + public final B snd; + + public Pair(A a, B b) { + fst = a; + snd = b; + } + } + + public static class FunSeq, Y extends Number> + implements Iterable> { + + private final X a, b; + private final Function f; + private final Function inc; + + public FunSeq(X a, X b, Function f, Function inc) { + this.a = a; + this.b = b; + this.f = f; + this.inc = inc; + } + + // 1.b + @Override + public Iterator> iterator() { + return new Iterator<>() { + private X x = a; + @Override + public boolean hasNext() { + return x.compareTo(b) <= 0; + } + + @Override + public Pair next() { + Pair r = new Pair<>(x, f.apply(x)); + x = inc.apply(x); + return r; + } + }; + } + } + + // 1.c + public static void test1() { + for (Pair p : new FunSeq<>(-2., 2., (x) -> x * x - 2 * x + 1, (x) -> x + 0.1)) { + final double x = p.fst, y = p.snd; + System.out.printf("f(%g) = %g\n", x, y); + } + } + + // 1.d + public static void test2() { + for (Pair p : new FunSeq<>(-2., 2., (x) -> (int) (x * x - 2 * x + 1), (x) -> x + 0.1)) { + final double x = p.fst; + final int y = p.snd; + System.out.printf("f(%g) = %d\n", x, y); + } + } + + + public static void main(String[] args) { + test1(); + test2(); + } +} + + + + + + + + + + + diff --git a/soluzione appelli/Scritto PO2 4 9 18/Scritto PO2 4 9 18.iml b/soluzione appelli/Scritto PO2 4 9 18/Scritto PO2 4 9 18.iml index 1a7f0f7..c90834f 100644 --- a/soluzione appelli/Scritto PO2 4 9 18/Scritto PO2 4 9 18.iml +++ b/soluzione appelli/Scritto PO2 4 9 18/Scritto PO2 4 9 18.iml @@ -7,14 +7,5 @@ - - - - - - - - - \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 5 9 23/.gitignore b/soluzione appelli/Scritto PO2 5 9 23/.gitignore new file mode 100644 index 0000000..f68d109 --- /dev/null +++ b/soluzione appelli/Scritto PO2 5 9 23/.gitignore @@ -0,0 +1,29 @@ +### 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 diff --git a/soluzione appelli/Scritto PO2 5 9 23/.idea/.gitignore b/soluzione appelli/Scritto PO2 5 9 23/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/soluzione appelli/Scritto PO2 5 9 23/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/soluzione appelli/Scritto PO2 5 9 23/.idea/misc.xml b/soluzione appelli/Scritto PO2 5 9 23/.idea/misc.xml new file mode 100644 index 0000000..cf9abe6 --- /dev/null +++ b/soluzione appelli/Scritto PO2 5 9 23/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 5 9 23/.idea/modules.xml b/soluzione appelli/Scritto PO2 5 9 23/.idea/modules.xml new file mode 100644 index 0000000..af0b507 --- /dev/null +++ b/soluzione appelli/Scritto PO2 5 9 23/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 5 9 23/.idea/vcs.xml b/soluzione appelli/Scritto PO2 5 9 23/.idea/vcs.xml new file mode 100644 index 0000000..b2bdec2 --- /dev/null +++ b/soluzione appelli/Scritto PO2 5 9 23/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 5 9 23/Scritto PO2 5 9 23.iml b/soluzione appelli/Scritto PO2 5 9 23/Scritto PO2 5 9 23.iml new file mode 100644 index 0000000..eda5e59 --- /dev/null +++ b/soluzione appelli/Scritto PO2 5 9 23/Scritto PO2 5 9 23.iml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 5 9 23/cpp/Appello_3_6_22/Appello_3_6_22.cpp b/soluzione appelli/Scritto PO2 5 9 23/cpp/Appello_3_6_22/Appello_3_6_22.cpp new file mode 100644 index 0000000..d343e97 --- /dev/null +++ b/soluzione appelli/Scritto PO2 5 9 23/cpp/Appello_3_6_22/Appello_3_6_22.cpp @@ -0,0 +1,82 @@ + +// Questo sorgente contiene le soluzioni dell'esame scritto di PO2 del 5/9/2023 per ciò che riguarda il quesito 2, ovvero la domanda che coinvolge C++. +// I quesiti 1-5 riguardanti Java sono in un sorgente Java a parte, non qui. +// Il codice C++ qui esposto è standard C++ vanilla (a.k.a. C++03), sebbene il progetto VS sia configurato con il compilatore di default C++14 + +#include +#include + +using namespace std; + +// 6 +template +class matrix +{ +private: + size_t cols; + vector v; + +public: + matrix() : cols(0), v() {} + matrix(const matrix& m) : cols(m.cols), v(m.v) {} + matrix(size_t rows, size_t cols_, const T& v = T()) : cols(cols_), v(rows* cols, v) {} + + typedef T value_type; + typedef typename vector::iterator iterator; + typedef typename vector::const_iterator const_iterator; + + matrix& operator=(const matrix& m) + { + v = m.v; + return *this; + } + + T& operator()(size_t i, size_t j) + { + return v[i * cols + j]; + } + + const T& operator()(size_t i, size_t j) const + { + return (*this)(i, j); + } + + iterator begin() + { + return v.begin(); + } + + iterator end() + { + return v.end(); + } + + const_iterator begin() const + { + return begin(); + } + + const_iterator end() const + { + return end(); + } +}; + + +int main() +{ + matrix m1; // non inizializzata + matrix m2(10, 20); // 10*20 inizializzata col default constructor di double + matrix m3(m2); // costruita per copia + m1 = m2; // assegnamento + m3(3, 1) = 11.23; // operatore di accesso come left-value + + for (typename matrix::iterator it = m1.begin(); it != m1.end(); ++it) { + typename matrix::value_type& x = *it; // de-reference non-const + x = m2(0, 2); // operatore di accesso come right-value + } + + matrix ms(5, 4, "ciao"); // 5*4 inizializzata col la stringa passata come terzo argomento + for (typename matrix::const_iterator it = ms.begin(); it != ms.end(); ++it) + cout << *it; // de-reference const +} diff --git a/soluzione appelli/Scritto PO2 5 9 23/cpp/Appello_3_6_22/Appello_3_6_22.sln b/soluzione appelli/Scritto PO2 5 9 23/cpp/Appello_3_6_22/Appello_3_6_22.sln new file mode 100644 index 0000000..160d856 --- /dev/null +++ b/soluzione appelli/Scritto PO2 5 9 23/cpp/Appello_3_6_22/Appello_3_6_22.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.2.32526.322 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Appello_3_6_22", "Appello_3_6_22.vcxproj", "{134AAFA0-F15F-4F91-B364-962161EC5D7F}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {134AAFA0-F15F-4F91-B364-962161EC5D7F}.Debug|x64.ActiveCfg = Debug|x64 + {134AAFA0-F15F-4F91-B364-962161EC5D7F}.Debug|x64.Build.0 = Debug|x64 + {134AAFA0-F15F-4F91-B364-962161EC5D7F}.Debug|x86.ActiveCfg = Debug|Win32 + {134AAFA0-F15F-4F91-B364-962161EC5D7F}.Debug|x86.Build.0 = Debug|Win32 + {134AAFA0-F15F-4F91-B364-962161EC5D7F}.Release|x64.ActiveCfg = Release|x64 + {134AAFA0-F15F-4F91-B364-962161EC5D7F}.Release|x64.Build.0 = Release|x64 + {134AAFA0-F15F-4F91-B364-962161EC5D7F}.Release|x86.ActiveCfg = Release|Win32 + {134AAFA0-F15F-4F91-B364-962161EC5D7F}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {49DE568A-D54C-485E-A095-5948A84AED91} + EndGlobalSection +EndGlobal diff --git a/soluzione appelli/Scritto PO2 5 9 23/cpp/Appello_3_6_22/Appello_3_6_22.vcxproj b/soluzione appelli/Scritto PO2 5 9 23/cpp/Appello_3_6_22/Appello_3_6_22.vcxproj new file mode 100644 index 0000000..04e7e58 --- /dev/null +++ b/soluzione appelli/Scritto PO2 5 9 23/cpp/Appello_3_6_22/Appello_3_6_22.vcxproj @@ -0,0 +1,135 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 16.0 + Win32Proj + {134aafa0-f15f-4f91-b364-962161ec5d7f} + Appello3622 + 10.0 + + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + + + + + + + + + + + + + + + + + + + + Level3 + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + Level4 + true + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 5 9 23/cpp/Appello_3_6_22/Appello_3_6_22.vcxproj.filters b/soluzione appelli/Scritto PO2 5 9 23/cpp/Appello_3_6_22/Appello_3_6_22.vcxproj.filters new file mode 100644 index 0000000..7676feb --- /dev/null +++ b/soluzione appelli/Scritto PO2 5 9 23/cpp/Appello_3_6_22/Appello_3_6_22.vcxproj.filters @@ -0,0 +1,22 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 5 9 23/cpp/Appello_3_6_22/Appello_3_6_22.vcxproj.user b/soluzione appelli/Scritto PO2 5 9 23/cpp/Appello_3_6_22/Appello_3_6_22.vcxproj.user new file mode 100644 index 0000000..88a5509 --- /dev/null +++ b/soluzione appelli/Scritto PO2 5 9 23/cpp/Appello_3_6_22/Appello_3_6_22.vcxproj.user @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 5 9 23/src/cpp/Appello_5_9_23/Appello_5_9_23.cpp b/soluzione appelli/Scritto PO2 5 9 23/src/cpp/Appello_5_9_23/Appello_5_9_23.cpp new file mode 100644 index 0000000..b8a2c83 --- /dev/null +++ b/soluzione appelli/Scritto PO2 5 9 23/src/cpp/Appello_5_9_23/Appello_5_9_23.cpp @@ -0,0 +1,83 @@ + +// Questo sorgente contiene le soluzioni dell'esame scritto di PO2 del 3/6/2022 per ciò che riguarda il quesito 6, ovvero la domanda che coinvolge C++. +// I quesiti 1-5 riguardanti Java sono in un progetto IntelliJ a parte, non qui. +// Il codice C++ qui esposto è standard C++ vanilla (a.k.a. C++03), sebbene il progetto VS sia configurato con il compilatore di default C++14 + +#include +#include + +using namespace std; + +// 6 +template +class matrix +{ +private: + size_t cols; + vector v; + +public: + matrix() : cols(0), v() {} + matrix(size_t rows, size_t cols_) : cols(cols_), v(rows * cols) {} + matrix(size_t rows, size_t cols_, const T& v) : cols(cols_), v(rows* cols, v) {} + matrix(const matrix& m) : cols(m.cols), v(m.v) {} + + typedef T value_type; + typedef typename vector::iterator iterator; + typedef typename vector::const_iterator const_iterator; + + matrix& operator=(const matrix& m) + { + v = m.v; + return *this; + } + + T& operator()(size_t i, size_t j) + { + return v[i * cols + j]; + } + + const T& operator()(size_t i, size_t j) const + { + return (*this)(i, j); + } + + iterator begin() + { + return v.begin(); + } + + iterator end() + { + return v.end(); + } + + const_iterator begin() const + { + return begin(); + } + + const_iterator end() const + { + return end(); + } +}; + + +int main() +{ + matrix m1; // non inizializzata + matrix m2(10, 20); // 10*20 inizializzata col default constructor di double + matrix m3(m2); // costruita per copia + m1 = m2; // assegnamento + m3(3, 1) = 11.23; // operatore di accesso come left-value + + for (typename matrix::iterator it = m1.begin(); it != m1.end(); ++it) { + typename matrix::value_type& x = *it; // de-reference non-const + x = m2(0, 2); // operatore di accesso come right-value + } + + matrix ms(5, 4, "ciao"); // 5*4 inizializzata col la stringa passata come terzo argomento + for (typename matrix::const_iterator it = ms.begin(); it != ms.end(); ++it) + cout << *it; // de-reference const +} diff --git a/soluzione appelli/Scritto PO2 5 9 23/src/cpp/Appello_5_9_23/Appello_5_9_23.sln b/soluzione appelli/Scritto PO2 5 9 23/src/cpp/Appello_5_9_23/Appello_5_9_23.sln new file mode 100644 index 0000000..cb13ab3 --- /dev/null +++ b/soluzione appelli/Scritto PO2 5 9 23/src/cpp/Appello_5_9_23/Appello_5_9_23.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.2.32526.322 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Appello_3_6_22", "..\..\..\cpp\Appello_3_6_22\Appello_3_6_22.vcxproj", "{134AAFA0-F15F-4F91-B364-962161EC5D7F}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {134AAFA0-F15F-4F91-B364-962161EC5D7F}.Debug|x64.ActiveCfg = Debug|x64 + {134AAFA0-F15F-4F91-B364-962161EC5D7F}.Debug|x64.Build.0 = Debug|x64 + {134AAFA0-F15F-4F91-B364-962161EC5D7F}.Debug|x86.ActiveCfg = Debug|Win32 + {134AAFA0-F15F-4F91-B364-962161EC5D7F}.Debug|x86.Build.0 = Debug|Win32 + {134AAFA0-F15F-4F91-B364-962161EC5D7F}.Release|x64.ActiveCfg = Release|x64 + {134AAFA0-F15F-4F91-B364-962161EC5D7F}.Release|x64.Build.0 = Release|x64 + {134AAFA0-F15F-4F91-B364-962161EC5D7F}.Release|x86.ActiveCfg = Release|Win32 + {134AAFA0-F15F-4F91-B364-962161EC5D7F}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {49DE568A-D54C-485E-A095-5948A84AED91} + EndGlobalSection +EndGlobal diff --git a/soluzione appelli/Scritto PO2 5 9 23/src/cpp/Appello_5_9_23/Appello_5_9_23.vcxproj b/soluzione appelli/Scritto PO2 5 9 23/src/cpp/Appello_5_9_23/Appello_5_9_23.vcxproj new file mode 100644 index 0000000..04e7e58 --- /dev/null +++ b/soluzione appelli/Scritto PO2 5 9 23/src/cpp/Appello_5_9_23/Appello_5_9_23.vcxproj @@ -0,0 +1,135 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 16.0 + Win32Proj + {134aafa0-f15f-4f91-b364-962161ec5d7f} + Appello3622 + 10.0 + + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + + + + + + + + + + + + + + + + + + + + Level3 + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + Level4 + true + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 5 9 23/src/cpp/Appello_5_9_23/Appello_5_9_23.vcxproj.filters b/soluzione appelli/Scritto PO2 5 9 23/src/cpp/Appello_5_9_23/Appello_5_9_23.vcxproj.filters new file mode 100644 index 0000000..7676feb --- /dev/null +++ b/soluzione appelli/Scritto PO2 5 9 23/src/cpp/Appello_5_9_23/Appello_5_9_23.vcxproj.filters @@ -0,0 +1,22 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 5 9 23/src/cpp/Appello_5_9_23/Appello_5_9_23.vcxproj.user b/soluzione appelli/Scritto PO2 5 9 23/src/cpp/Appello_5_9_23/Appello_5_9_23.vcxproj.user new file mode 100644 index 0000000..88a5509 --- /dev/null +++ b/soluzione appelli/Scritto PO2 5 9 23/src/cpp/Appello_5_9_23/Appello_5_9_23.vcxproj.user @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 5 9 23/src/java/Main.java b/soluzione appelli/Scritto PO2 5 9 23/src/java/Main.java new file mode 100644 index 0000000..ddaf336 --- /dev/null +++ b/soluzione appelli/Scritto PO2 5 9 23/src/java/Main.java @@ -0,0 +1,60 @@ +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.function.Function; +import java.util.function.Supplier; + +public class Main { + + // 1.a + public static Iterator> asyncIterator(Iterator it, Function f) { + return new Iterator<>() { + @Override + public boolean hasNext() { + return it.hasNext(); + } + + private class Future implements Supplier { + @Nullable + private B r; + @NotNull + private final Thread t; + + public Future(Supplier f) { + t = new Thread(() -> { r = f.get(); }); + t.start(); + } + + @Override + @NotNull + public B get() { + try { + t.join(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + return r; + } + } + + @Override + public Supplier next() { + A a = it.next(); + return new Future(() -> f.apply(a)); + } + }; + } + + // 1.b + static > void sortLists(Iterable> c) { + Iterator>> it = asyncIterator(c.iterator(), (l) -> { Collections.sort(l); return l; }); + while (it.hasNext()) { + Supplier> f = it.next(); + System.out.println(f.get()); // questo non è davvero necessario, ma + } + } + +} \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 6 9 19/Scritto PO2 6 9 19.iml b/soluzione appelli/Scritto PO2 6 9 19/Scritto PO2 6 9 19.iml index 1a7f0f7..c90834f 100644 --- a/soluzione appelli/Scritto PO2 6 9 19/Scritto PO2 6 9 19.iml +++ b/soluzione appelli/Scritto PO2 6 9 19/Scritto PO2 6 9 19.iml @@ -7,14 +7,5 @@ - - - - - - - - - \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 6 9 19/src/.idea/.gitignore b/soluzione appelli/Scritto PO2 6 9 19/src/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/soluzione appelli/Scritto PO2 6 9 19/src/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/soluzione appelli/Scritto PO2 6 9 19/src/.idea/misc.xml b/soluzione appelli/Scritto PO2 6 9 19/src/.idea/misc.xml new file mode 100644 index 0000000..09e91bf --- /dev/null +++ b/soluzione appelli/Scritto PO2 6 9 19/src/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 6 9 19/src/.idea/modules.xml b/soluzione appelli/Scritto PO2 6 9 19/src/.idea/modules.xml new file mode 100644 index 0000000..30358ae --- /dev/null +++ b/soluzione appelli/Scritto PO2 6 9 19/src/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 6 9 19/src/.idea/vcs.xml b/soluzione appelli/Scritto PO2 6 9 19/src/.idea/vcs.xml new file mode 100644 index 0000000..c2365ab --- /dev/null +++ b/soluzione appelli/Scritto PO2 6 9 19/src/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 6 9 19/src/Es.java b/soluzione appelli/Scritto PO2 6 9 19/src/Es.java index 9df4fc4..1767fc7 100644 --- a/soluzione appelli/Scritto PO2 6 9 19/src/Es.java +++ b/soluzione appelli/Scritto PO2 6 9 19/src/Es.java @@ -37,11 +37,10 @@ protected Polygon(List points) { // 1.c.ii public Iterator lineIterator() { - Iterator it = points.iterator(); - final Point[] last = new Point[1]; // questo trucco serve a mettere il final sull'array e non sugli elementi, così da poter essere modificato da dentro la anonymous class - assert it.hasNext(); // si assicura che non iteriamo su una lista vuota (in realtà ha almeno 3 elementi) - last[0] = it.next(); return new Iterator<>() { + private final Iterator it = points.iterator(); + private Point last = it.next(); // ci sono sempre almeno 3 punti, non può fallire questa next() + @Override public boolean hasNext() { return it.hasNext(); @@ -50,8 +49,8 @@ public boolean hasNext() { @Override public Line next() { Point p = it.next(); - Line r = new Line(last[0], p); - last[0] = p; + Line r = new Line(last, p); + last = p; return r; } }; diff --git a/soluzione appelli/Scritto PO2 6 9 19/src/Scritto PO2 6 9 19.iml b/soluzione appelli/Scritto PO2 6 9 19/src/Scritto PO2 6 9 19.iml new file mode 100644 index 0000000..b107a2d --- /dev/null +++ b/soluzione appelli/Scritto PO2 6 9 19/src/Scritto PO2 6 9 19.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/soluzione appelli/Scritto PO2 7 1 22/java/.idea/workspace.xml b/soluzione appelli/Scritto PO2 7 1 22/java/.idea/workspace.xml new file mode 100644 index 0000000..73b8a42 --- /dev/null +++ b/soluzione appelli/Scritto PO2 7 1 22/java/.idea/workspace.xml @@ -0,0 +1,104 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1651049919437 + + + + + + + + + + + + + file://$PROJECT_DIR$/src/Appello_1_7_22.java + 9 + + + + + \ No newline at end of file