├── code ├── things.txt ├── files │ ├── things.txt │ ├── file2.txt │ ├── file-for-testing-1.dat │ ├── file1.txt │ ├── JavaCat.java │ ├── TestFile.java │ ├── TestPrintWriter.java │ ├── TestBinaryWriting.java │ ├── TestScanner.java │ ├── TestBinaryReading.java │ ├── TestEOFException.java │ ├── TextWritingReadingIntegers.java │ ├── TestBuffers.java │ └── SeeDirectory.java ├── integers.in2 ├── input.txt ├── run-examples.sh ├── file2.txt ├── compile-examples.sh ├── linear-data-structures │ ├── sample_data │ │ ├── datos.in │ │ └── datos.ans │ ├── linear.jar │ ├── linear-data-structures.iml │ ├── makefile │ └── src │ │ ├── TestQueues.java │ │ ├── TestStacks.java │ │ └── LinkedSequences.java ├── file1.txt ├── misc │ ├── p2.c │ ├── p1.c │ ├── nested_blocks.c │ ├── mcd.c │ ├── swap.cpp │ ├── p1.s │ ├── p2.s │ └── mcd.s ├── atp.in ├── basic │ ├── HelloWorld.java │ ├── Basic.java │ ├── Fahrenheit2Celsius.java │ ├── CharExample2.java │ ├── Dice2.java │ ├── DivisionByZero.java │ ├── TestRectangle.java │ ├── NestedBlocks.java │ ├── CharExample3.java │ ├── IntegerConstants.java │ ├── Overflow2.java │ ├── StudentSelection.java │ ├── TestPoint.java │ ├── DivisionByZero2.java │ ├── Modulus.java │ ├── Square.java │ ├── Trace01.java │ ├── IntegerDataTypes.java │ ├── Rounding.java │ ├── RealDataTypes.java │ ├── ExampleOfStandardInputOutput.java │ ├── Overflow.java │ ├── Test01.java │ ├── TimeConversion.java │ ├── DataTypeConversions2.java │ ├── Dice.java │ ├── SphereExample1.java │ ├── CharExample1.java │ ├── ComparingPoints.java │ ├── ProblemsInClass.java │ ├── CheckingExpressions.java │ ├── UserInteraction1.java │ ├── DataTypeConversions.java │ ├── CheckingExpressionsWithFloats.java │ ├── RealDataTypes2.java │ ├── Triangle.java │ ├── TestCircle.java │ ├── PrintfExamples.java │ └── Rectangle.java ├── integers.txt ├── exams_from_previous_years │ ├── 2019_2020 │ │ ├── scripts │ │ │ ├── gen_documentation.sh │ │ │ ├── clean-development-tree.sh │ │ │ ├── run.sh │ │ │ └── compile.sh │ │ └── src │ │ │ └── Exercises2and3.java │ ├── GameManager.java │ ├── PolygonalNumbers.java │ ├── 2018-2019 │ │ ├── WorkWithFiles2.java │ │ └── WorkWithFiles1.java │ └── SaveArea.java ├── errors_found.txt ├── arrays │ ├── Args.java │ ├── TestRainfall1.java │ ├── agenda.txt │ ├── Example1.java │ ├── ComputeAverage.java │ ├── Palindrome.java │ └── Contact.java ├── inheritance │ ├── TestStudent.java │ ├── TestStudent2.java │ ├── B.java │ ├── A.java │ ├── Person.java │ ├── TestStudent3.java │ ├── Student.java │ ├── NewStudent.java │ ├── Point2D.java │ └── Point3D.java ├── methods │ ├── Swap.java │ ├── Swap2.java │ ├── Swap3.java │ ├── Methods1.java │ ├── TestingEquals.java │ ├── Swap4.java │ └── Program02.java ├── testing.sh ├── loops │ ├── JavaCat.java │ ├── N100.java │ ├── EuclidesGCD.java │ ├── Figures2.java │ ├── PrimeFactors.java │ ├── Fibonacci.java │ └── Triangles.java ├── agenda.txt ├── recursion │ ├── ToBinary.java │ ├── Reverse.java │ ├── GreatestCommonDivisor.java │ ├── Quotient.java │ ├── PascalTriangle2.java │ ├── Powers.java │ ├── FibonacciWithMemoization.java │ ├── PascalTriangle.java │ ├── Exam20190418.java │ ├── KeyPalindrome.java │ ├── NaturalNumbers.java │ └── Exam20180619.java ├── exceptions │ ├── IllegalDateException.java │ ├── ReadNumbersOriginal.java │ ├── TestAskingForDate.java │ ├── ExceptionHandling2.java │ ├── ExceptionHandling.java │ ├── ExceptionHandling3.java │ ├── Main.java │ └── ReadNumbers2.java ├── testing-final-grade.sh └── conditionals │ ├── TestingEquals.java │ ├── Grades1b.java │ ├── Grades1.java │ ├── Grades2.java │ ├── Plane.java │ ├── Grades3.java │ ├── FinalGrade.java │ ├── SecondDegreeEquations.java │ ├── NewSDE.java │ └── PaperStoneScissors.java ├── images ├── Linear-Data-Structures.pdf ├── Linear-Data-Structures.png ├── Conditionals - if -else.pdf ├── Conditionals - if -else.png ├── Java-built-in-data-types.pdf ├── Java-built-in-data-types.png ├── Computer-Programming-contents.pdf ├── Computer-Programming-contents.png ├── Computer-programming-in-the-GII.pdf ├── Computer-programming-in-the-GII.png ├── Conditionals-if-else-if-else-if.pdf ├── Conditionals-if-else-if-else-if.png ├── Second-degree-equation-flow-chart.pdf └── Second-degree-equation-flow-chart.png ├── cpr ├── cpp │ ├── heights_and_weights.txt │ ├── check_gcd.cpp │ ├── makefile │ ├── check_pf.cpp │ ├── primeFactorization.cpp │ └── greatestCommonDivisor.cpp ├── java │ ├── StringComparator.java │ ├── ObjectComparator.java │ ├── StringHash.java │ ├── FindCycles.java │ ├── ConnectedComponents.java │ ├── fsa │ │ ├── TestPrefixAcceptor.java │ │ └── Vertex.java │ ├── Vertex.java │ ├── Point3D.java │ ├── Edge.java │ ├── AllSubsets2.java │ ├── AllSubsets.java │ ├── Point2D.java │ ├── AllPermutations.java │ ├── NQueens.java │ └── NetworkFlow.java └── python │ └── point2d.py ├── examples ├── agenda1 │ ├── scripts │ │ ├── gen_documentation.sh │ │ ├── clean-development-tree.sh │ │ ├── run.sh │ │ └── compile.sh │ ├── agenda1.iml │ └── README.md ├── agenda2 │ ├── scripts │ │ ├── gen_documentation.sh │ │ ├── clean-development-tree.sh │ │ ├── run.sh │ │ └── compile.sh │ ├── agenda2.iml │ ├── agenda.bak │ ├── agenda.txt │ └── src │ │ └── Date.java ├── agenda3 │ ├── scripts │ │ ├── gen_documentation.sh │ │ ├── clean-development-tree.sh │ │ ├── run.sh │ │ └── compile.sh │ ├── agenda3.iml │ ├── agenda.bak │ ├── agenda.txt │ └── src │ │ ├── NodeEvent.java │ │ ├── NodeContact.java │ │ └── Date.java ├── covid_19 │ ├── scripts │ │ ├── gen_documentation.sh │ │ ├── clean-development-tree.sh │ │ ├── run.sh │ │ ├── download_data.sh │ │ └── compile.sh │ ├── covid_19.iml │ └── test_src │ │ └── TestingCovid19.java └── README.md ├── CONTRIBUTING.md ├── LICENSE.md └── README.md /code/things.txt: -------------------------------------------------------------------------------- 1 | 1 2 2 | 3 4 3 | Hello! 4 | -------------------------------------------------------------------------------- /code/files/things.txt: -------------------------------------------------------------------------------- 1 | 1 2 2 | 3 4 3 | Hello! 4 | -------------------------------------------------------------------------------- /code/integers.in2: -------------------------------------------------------------------------------- 1 | 4 5 2 | 20 1 2x3 10 3 | 3 4 | -------------------------------------------------------------------------------- /code/input.txt: -------------------------------------------------------------------------------- 1 | 1 10 2 | 100 200 3 | 201 210 4 | 900 1000 5 | -------------------------------------------------------------------------------- /code/run-examples.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | java -cp classes $* 4 | 5 | 6 | -------------------------------------------------------------------------------- /code/file2.txt: -------------------------------------------------------------------------------- 1 | El veloz murciélago hindú comía feliz cardillo y kiwi 2 | 4.815162342 3 | -------------------------------------------------------------------------------- /code/compile-examples.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | javac -cp classes -d classes $* 4 | 5 | 6 | -------------------------------------------------------------------------------- /code/files/file2.txt: -------------------------------------------------------------------------------- 1 | El veloz murciélago hindú comía feliz cardillo y kiwi 2 | 4.815162342 3 | -------------------------------------------------------------------------------- /code/linear-data-structures/sample_data/datos.in: -------------------------------------------------------------------------------- 1 | -756 -536 109 92 394 421 253 240 774 -761 2 | -------------------------------------------------------------------------------- /code/files/file-for-testing-1.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jonandergomez/programming/HEAD/code/files/file-for-testing-1.dat -------------------------------------------------------------------------------- /images/Linear-Data-Structures.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jonandergomez/programming/HEAD/images/Linear-Data-Structures.pdf -------------------------------------------------------------------------------- /images/Linear-Data-Structures.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jonandergomez/programming/HEAD/images/Linear-Data-Structures.png -------------------------------------------------------------------------------- /images/Conditionals - if -else.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jonandergomez/programming/HEAD/images/Conditionals - if -else.pdf -------------------------------------------------------------------------------- /images/Conditionals - if -else.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jonandergomez/programming/HEAD/images/Conditionals - if -else.png -------------------------------------------------------------------------------- /images/Java-built-in-data-types.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jonandergomez/programming/HEAD/images/Java-built-in-data-types.pdf -------------------------------------------------------------------------------- /images/Java-built-in-data-types.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jonandergomez/programming/HEAD/images/Java-built-in-data-types.png -------------------------------------------------------------------------------- /code/file1.txt: -------------------------------------------------------------------------------- 1 | 0 2 | 1 3 | 2 4 | 3 5 | 4 6 | 5 7 | 6 8 | 7 9 | 8 10 | 9 11 | -------------------------------------------------------------------------------- /code/linear-data-structures/linear.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jonandergomez/programming/HEAD/code/linear-data-structures/linear.jar -------------------------------------------------------------------------------- /code/files/file1.txt: -------------------------------------------------------------------------------- 1 | 0 2 | 1 3 | 2 4 | 3 5 | 4 6 | 5 7 | 6 8 | 7 9 | 8 10 | 9 11 | -------------------------------------------------------------------------------- /images/Computer-Programming-contents.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jonandergomez/programming/HEAD/images/Computer-Programming-contents.pdf -------------------------------------------------------------------------------- /images/Computer-Programming-contents.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jonandergomez/programming/HEAD/images/Computer-Programming-contents.png -------------------------------------------------------------------------------- /images/Computer-programming-in-the-GII.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jonandergomez/programming/HEAD/images/Computer-programming-in-the-GII.pdf -------------------------------------------------------------------------------- /images/Computer-programming-in-the-GII.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jonandergomez/programming/HEAD/images/Computer-programming-in-the-GII.png -------------------------------------------------------------------------------- /images/Conditionals-if-else-if-else-if.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jonandergomez/programming/HEAD/images/Conditionals-if-else-if-else-if.pdf -------------------------------------------------------------------------------- /images/Conditionals-if-else-if-else-if.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jonandergomez/programming/HEAD/images/Conditionals-if-else-if-else-if.png -------------------------------------------------------------------------------- /images/Second-degree-equation-flow-chart.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jonandergomez/programming/HEAD/images/Second-degree-equation-flow-chart.pdf -------------------------------------------------------------------------------- /images/Second-degree-equation-flow-chart.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jonandergomez/programming/HEAD/images/Second-degree-equation-flow-chart.png -------------------------------------------------------------------------------- /cpr/cpp/heights_and_weights.txt: -------------------------------------------------------------------------------- 1 | 10 2 | 189 98 3 | 189 88 4 | 189 85 5 | 192 85 6 | 192 104 7 | 175 87 8 | 177 74 9 | 177 79 10 | 177 86 11 | 168 93 12 | -------------------------------------------------------------------------------- /code/misc/p2.c: -------------------------------------------------------------------------------- 1 | 2 | int pow2(int a, int b) 3 | { 4 | int p = 1; 5 | for (int i = 1; i <= b; i++) { 6 | p *= a; 7 | } 8 | return p; 9 | } 10 | -------------------------------------------------------------------------------- /code/misc/p1.c: -------------------------------------------------------------------------------- 1 | 2 | int pow1(int a, int b) 3 | { 4 | int p = 1; 5 | int i = 1; 6 | while (i <= b) { 7 | p *= a; 8 | i++; 9 | } 10 | return p; 11 | } 12 | -------------------------------------------------------------------------------- /code/atp.in: -------------------------------------------------------------------------------- 1 | Djokovic 31 12115 17 2 | Nadal -32 7945 16 3 | Federer 37 5770 17 4 | Thiem 25 4845 24 4 5 | Zverev 22 4745 6 | Nishikori 29 3860 23.5 7 | Tsitsipas 20 3790 28 8 | Anderson 32 3755.3 17 9 | -------------------------------------------------------------------------------- /code/basic/HelloWorld.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class HelloWorld 4 | { 5 | public static void main(String [] args) 6 | { 7 | System.out.println("Hello World!"); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /examples/agenda1/scripts/gen_documentation.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | javadoc -d docs \ 4 | -private -author -version \ 5 | -sourcepath src \ 6 | -classpath classes \ 7 | src/*.java 8 | -------------------------------------------------------------------------------- /examples/agenda2/scripts/gen_documentation.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | javadoc -d docs \ 4 | -private -author -version \ 5 | -sourcepath src \ 6 | -classpath classes \ 7 | src/*.java 8 | -------------------------------------------------------------------------------- /examples/agenda3/scripts/gen_documentation.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | javadoc -d docs \ 4 | -private -author -version \ 5 | -sourcepath src \ 6 | -classpath classes \ 7 | src/*.java 8 | -------------------------------------------------------------------------------- /examples/covid_19/scripts/gen_documentation.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | javadoc -d docs \ 4 | -private -author -version \ 5 | -sourcepath src \ 6 | -classpath classes \ 7 | src/*.java 8 | -------------------------------------------------------------------------------- /code/integers.txt: -------------------------------------------------------------------------------- 1 | 12686 2 | 29753 3 | 25399 4 | 20947 5 | 12430 6 | 21143 7 | 26289 8 | 7437 9 | 31250 10 | 23759 11 | 20983 12 | 21339 13 | 1 14 | 17884 15 | 1662 16 | 21245 17 | 28975 18 | 19294 19 | 18244 20 | 24589 21 | -------------------------------------------------------------------------------- /code/exams_from_previous_years/2019_2020/scripts/gen_documentation.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | javadoc -d docs \ 4 | -private -author -version \ 5 | -sourcepath src \ 6 | -classpath classes \ 7 | src/*.java 8 | -------------------------------------------------------------------------------- /code/errors_found.txt: -------------------------------------------------------------------------------- 1 | Error line 2: Negative value. 2 | Error line 4: Unexpected number of columns. 3 | Error line 5: Unexpected number of columns. 4 | Error line 6: Invalid format for an integer. 5 | Error line 8: Invalid format for an integer. 6 | -------------------------------------------------------------------------------- /code/linear-data-structures/sample_data/datos.ans: -------------------------------------------------------------------------------- 1 | -756 109 2 | -536 92 3 | -761 394 4 | 421 5 | 253 6 | 240 7 | 774 8 | -------------------------------------------------------------------------------- /examples/agenda1/scripts/clean-development-tree.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | rm -rf docs 4 | 5 | find classes -type f -name "*.class" -exec rm -f {} \; 6 | 7 | rmdir classes/etsinf/prg/agenda1 8 | rmdir classes/etsinf/prg 9 | rmdir classes/etsinf 10 | 11 | -------------------------------------------------------------------------------- /examples/agenda2/scripts/clean-development-tree.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | rm -rf docs 4 | 5 | find classes -type f -name "*.class" -exec rm -f {} \; 6 | 7 | rmdir classes/etsinf/prg/agenda2 8 | rmdir classes/etsinf/prg 9 | rmdir classes/etsinf 10 | 11 | -------------------------------------------------------------------------------- /examples/agenda3/scripts/clean-development-tree.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | rm -rf docs 4 | 5 | find classes -type f -name "*.class" -exec rm -f {} \; 6 | 7 | rmdir classes/etsinf/prg/agenda3 8 | rmdir classes/etsinf/prg 9 | rmdir classes/etsinf 10 | 11 | -------------------------------------------------------------------------------- /examples/covid_19/scripts/clean-development-tree.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | rm -rf docs 4 | 5 | find classes -type f -name "*.class" -exec rm -f {} \; 6 | 7 | rmdir classes/etsinf/prg/covid19 8 | rmdir classes/etsinf/prg 9 | rmdir classes/etsinf 10 | 11 | -------------------------------------------------------------------------------- /code/basic/Basic.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | import java.io.*; 4 | 5 | public class Basic 6 | { 7 | private static Scanner input = new Scanner(System.in).useLocale(Locale.US); 8 | 9 | public static void main(String [] args) 10 | { 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /code/exams_from_previous_years/2019_2020/scripts/clean-development-tree.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | rm -rf docs 4 | 5 | find classes -type f -name "*.class" -exec rm -f {} \; 6 | 7 | rmdir classes/etsinf/prg/exam2 8 | rmdir classes/etsinf/prg 9 | rmdir classes/etsinf 10 | 11 | -------------------------------------------------------------------------------- /code/basic/Fahrenheit2Celsius.java: -------------------------------------------------------------------------------- 1 | public class Fahrenheit2Celsius 2 | { 3 | public static void main(String [] args) 4 | { 5 | double f = -40; 6 | double c = (5.0 / 9) * (f - 32); 7 | 8 | System.out.printf(" %.3f ºF = %.3f ºC\n" , f, c); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /code/misc/nested_blocks.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(int argc, char *arg[]) 5 | { 6 | int x = 10; 7 | 8 | { 9 | int x = 91; 10 | printf("%d\n", x); 11 | } 12 | printf("%d\n", x); 13 | 14 | return EXIT_SUCCESS; 15 | } 16 | -------------------------------------------------------------------------------- /cpr/java/StringComparator.java: -------------------------------------------------------------------------------- 1 | 2 | package es.upv.etsinf.sorting; 3 | 4 | import java.util.Comparator; 5 | 6 | 7 | public class StringComparator implements Comparator 8 | { 9 | public int compare( String s1, String s2 ) 10 | { 11 | return s1.compareTo( s2 ); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /examples/agenda1/scripts/run.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Example of running classes with the main method and using the classes of the 4 | # package gathered in the JAR file that can be used as one of the paths the 5 | # JVM can look for compiled classes. 6 | java -cp lib/agenda1.jar:classes TestingAgenda1 7 | -------------------------------------------------------------------------------- /examples/agenda2/scripts/run.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Example of running classes with the main method and using the classes of the 4 | # package gathered in the JAR file that can be used as one of the paths the 5 | # JVM can look for compiled classes. 6 | java -cp lib/agenda2.jar:classes TestingAgenda2 7 | -------------------------------------------------------------------------------- /examples/agenda3/scripts/run.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Example of running classes with the main method and using the classes of the 4 | # package gathered in the JAR file that can be used as one of the paths the 5 | # JVM can look for compiled classes. 6 | java -cp lib/agenda3.jar:classes TestingAgenda3 7 | -------------------------------------------------------------------------------- /examples/covid_19/scripts/run.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Example of running classes with the main method and using the classes of the 4 | # package gathered in the JAR file that can be used as one of the paths the 5 | # JVM can look for compiled classes. 6 | java -cp lib/covid19.jar:classes TestingCovid19 7 | -------------------------------------------------------------------------------- /code/arrays/Args.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | import java.util.*; 4 | import java.io.*; 5 | 6 | 7 | public class Args 8 | { 9 | public static void main(String [] args) 10 | { 11 | for (int i = 0; i < args.length; i++) { 12 | System.out.printf("args[%d]= %s \n", i, args[i]); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /code/exams_from_previous_years/2019_2020/scripts/run.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Example of running classes with the main method and using the classes of the 4 | # package gathered in the JAR file that can be used as one of the paths the 5 | # JVM can look for compiled classes. 6 | java -cp lib/exam2.jar:classes TestExam2 7 | -------------------------------------------------------------------------------- /code/basic/CharExample2.java: -------------------------------------------------------------------------------- 1 | public class CharExample2 2 | { 3 | public static void main(String [] args) 4 | { 5 | System.out.println("¡Hola mundo! \u00A1Hello world\u0021"); 6 | System.out.println("\n"); 7 | System.out.println("\u03b1 \u03b2 \u03b3 \u03b4 \u03b5 \u03b6 \u03b7"); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /code/misc/mcd.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int mcd(int a, int b) 4 | { 5 | while (a != b && a != 0 && b != 0) { 6 | if (a > b) { 7 | a = a % b; 8 | } else { 9 | b = b % a; 10 | } 11 | } 12 | if (a != 0) return a; 13 | else if (b != 0) return b; 14 | else return 1; 15 | } -------------------------------------------------------------------------------- /code/inheritance/TestStudent.java: -------------------------------------------------------------------------------- 1 | public class TestStudent { 2 | public static void main(String[] args) { 3 | Student s = new Student("John Smith", 19); 4 | 5 | System.out.printf("Person: %s\n", s.toString()); 6 | System.out.printf("%s is enrolled in %d ECTS.\n", 7 | s.getName(), s.getECTS()); 8 | } 9 | } -------------------------------------------------------------------------------- /code/basic/Dice2.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Dice2 4 | { 5 | private static Scanner input = new Scanner(System.in).useLocale(Locale.US); 6 | 7 | 8 | public static void main(String [] args) 9 | { 10 | Random r = new Random(); 11 | 12 | System.out.println("dice thrown with value: " + (r.nextInt(6)+1)); 13 | } 14 | } -------------------------------------------------------------------------------- /code/files/JavaCat.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class JavaCat 4 | { 5 | public static void main(String [] args) 6 | { 7 | Scanner input = new Scanner(System.in); 8 | 9 | while (input.hasNext()) { 10 | String line = input.nextLine(); 11 | System.out.println(line); 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /code/inheritance/TestStudent2.java: -------------------------------------------------------------------------------- 1 | public class TestStudent2 { 2 | public static void main(String[] args) { 3 | Student s = new Student("John Smith", 19); 4 | Person p = new Person("John Smith", 19); 5 | 6 | System.out.println("Person.: " + p.toString()); 7 | System.out.println("Student: " + s.toString()); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /code/methods/Swap.java: -------------------------------------------------------------------------------- 1 | public class Swap 2 | { 3 | public static void swap(int a, int b) 4 | { 5 | int temp = a; 6 | a = b; 7 | b = temp; 8 | } 9 | public static void main(String [] args) 10 | { 11 | int a = 5, b = 2; 12 | swap(a, b); 13 | System.out.println("a = " + a + " b = " + b); 14 | } 15 | } -------------------------------------------------------------------------------- /code/basic/DivisionByZero.java: -------------------------------------------------------------------------------- 1 | public class DivisionByZero 2 | { 3 | public static void main(String [] args) 4 | { 5 | int a, b, c; 6 | 7 | a = 2; b = 7; c = a / b; 8 | System.out.printf("a = %d | b = %d | c = %d\n", a, b, c); 9 | a = 2; b = 0; c = a / b; 10 | System.out.printf("a = %d | b = %d | c = %d\n", a, b, c); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /code/arrays/TestRainfall1.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | import java.io.*; 4 | 5 | 6 | public class TestRainfall1 7 | { 8 | private static Scanner input = new Scanner(System.in).useLocale(Locale.US); 9 | 10 | public static void main(String [] args) 11 | { 12 | Rainfall1 rf = new Rainfall1("November", 2019); 13 | 14 | System.out.println(rf); 15 | 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /code/basic/TestRectangle.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.util.Locale; 3 | 4 | public class TestRectangle { 5 | public static void main(String [] args) { 6 | Rectangle r1 = new Rectangle(new Point(10, 10), new Point(2, 12)); 7 | 8 | System.out.println(r1); 9 | 10 | Square s1 = new Square(3, 10, 70); 11 | 12 | System.out.println(s1); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /code/misc/swap.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void swap(int & a, int & b) 4 | { 5 | int temp = a; 6 | a = b; 7 | b = temp; 8 | } 9 | 10 | int main(int argc, char * args[]) 11 | { 12 | int a = 5, b = 2; 13 | std::cout << "BEFORE: a = " << a << " b = " << b << std::endl; 14 | swap(a, b); 15 | std::cout << "AFTER.: a = " << a << " b = " << b << std::endl; 16 | 17 | return EXIT_SUCCESS; 18 | } -------------------------------------------------------------------------------- /code/inheritance/B.java: -------------------------------------------------------------------------------- 1 | public class B extends A { 2 | private int z; 3 | 4 | public B(int x, int y, int z) { 5 | super(x, y); // invokes the constructor of the parent class 6 | this.z = z; 7 | } 8 | 9 | public int sum() { 10 | return this.getX() + this.getY() + z; 11 | } 12 | 13 | public int product() { 14 | return super.product() * z; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /code/basic/NestedBlocks.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class NestedBlocks 4 | { 5 | public static void main(String [] args) 6 | { // outer block start 7 | int x = 10; 8 | 9 | { // nested block starts 10 | int x = 91; 11 | 12 | System.out.println(x); 13 | } // nested block ends 14 | 15 | System.out.println(x); 16 | } // outer block ends 17 | } 18 | -------------------------------------------------------------------------------- /examples/covid_19/scripts/download_data.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | 4 | if [ -f owid-covid-data.csv ] 5 | then 6 | mv owid-covid-data.csv owid-covid-data.csv-old 7 | fi 8 | wget https://covid.ourworldindata.org/data/owid-covid-data.csv 9 | 10 | if [ -f datos_provincias.csv ] 11 | then 12 | mv datos_provincias.csv datos_provincias.csv-old 13 | fi 14 | wget https://cnecovid.isciii.es/covid19/resources/datos_provincias.csv 15 | -------------------------------------------------------------------------------- /code/methods/Swap2.java: -------------------------------------------------------------------------------- 1 | public class Swap2 2 | { 3 | public static void swap(Point p1, Point p2) 4 | { 5 | Point temp = p1; 6 | p1 = p2; 7 | p2 = temp; 8 | } 9 | public static void main(String [] args) 10 | { 11 | Point p1 = new Point(); 12 | Point p2 = new Point(5, 2); 13 | swap(p1, p2); 14 | System.out.println("p1 = " + p1 + " p2 = " + p2); 15 | } 16 | } -------------------------------------------------------------------------------- /cpr/cpp/check_gcd.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int gcd(int a, int b, int *x, int *y); 4 | 5 | using namespace std; 6 | 7 | int main(int argc, char * argv[]) 8 | { 9 | int x, y; 10 | // int a = 34398, b = 2132; 11 | int a = 17, b = 14; 12 | // int a = 4, b = 6; 13 | 14 | int g = gcd(a, b, &x, &y); 15 | 16 | printf("\n\n"); 17 | printf("%d * %d + %d * %d = %d\n", a, x, b, y, g); 18 | 19 | return 0; 20 | } -------------------------------------------------------------------------------- /code/inheritance/A.java: -------------------------------------------------------------------------------- 1 | public class A { 2 | private int x, y; 3 | 4 | public A(int x, int y) { 5 | this.x = x; 6 | this.y = y; 7 | } 8 | 9 | public int getX() { 10 | return x; 11 | } 12 | 13 | public int getY() { 14 | return y; 15 | } 16 | 17 | private int sum() { 18 | return x + y; 19 | } 20 | 21 | public int product() { 22 | return x * y; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /code/testing.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | while [ true ] 4 | do 5 | a=$(( ((${RANDOM} % 120 ) / 10) - 1 )) 6 | b=${RANDOM} 7 | 8 | grade="${a}.${b}" 9 | 10 | x=$(echo ${grade} | ./run-examples.sh Grades1) 11 | y=$(echo ${grade} | ./run-examples.sh Grades2) 12 | 13 | echo ${grade} 14 | #echo ${grade} ${x} ${y} 15 | 16 | if [ "${x}" != "${y}" ] 17 | then 18 | echo $x $y 19 | break 20 | fi 21 | done 22 | -------------------------------------------------------------------------------- /code/basic/CharExample3.java: -------------------------------------------------------------------------------- 1 | public class CharExample3 2 | { 3 | public static void main(String [] args) 4 | { 5 | char letterA = 'A'; 6 | char letterB = (char)(letterA + 1); 7 | char letterC = letterB; 8 | letterC++; 9 | char letterN = 'n'; 10 | letterN = (char)(letterN + ('A' - 'a')); 11 | 12 | System.out.println(letterA + "\t" + letterB + "\t" + 13 | letterC + "\t" + letterN); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /code/loops/JavaCat.java: -------------------------------------------------------------------------------- 1 | import java.io.File; 2 | import java.util.Scanner; 3 | 4 | public class JavaCat 5 | { 6 | public static void main(String [] args) 7 | throws Exception 8 | { 9 | String filename = args[0]; 10 | 11 | Scanner f = new Scanner(new File(filename)); 12 | 13 | while (f.hasNextLine()) { 14 | String line = f.nextLine(); 15 | System.out.println(line); 16 | } 17 | f.close(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /code/basic/IntegerConstants.java: -------------------------------------------------------------------------------- 1 | public class IntegerConstants 2 | { 3 | public static void main(String [] args) 4 | { 5 | int a = -37, b = 89; 6 | 7 | 8 | System.out.println(" Decimal Octal Hexadecimal"); 9 | System.out.println("--------------------------------------------------"); 10 | System.out.printf("a = %12d %12o %8x %8X\n", a, a, a, a); 11 | System.out.printf("b = %12d %12o %8x %8X\n", b, b, b, b); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /code/basic/Overflow2.java: -------------------------------------------------------------------------------- 1 | public class Overflow2 2 | { 3 | public static void main(String [] args) 4 | { 5 | float f = 1.0e+38F; 6 | double d = 1.0e+308; 7 | 8 | System.out.printf(" %e * 10 = %e\n", f, f * 10); 9 | System.out.printf(" %e * 10 = %e\n", d, d * 10); 10 | 11 | System.out.printf(" (5.0 / 0.0) + 166.386 = %f\n", (5.0 / 0.0) + 166.386); 12 | 13 | System.out.printf(" (0.0 / 0.0) + 166.386 = %f\n", (0.0 / 0.0) + 166.386); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /code/basic/StudentSelection.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | import java.io.*; 4 | 5 | 6 | public class StudentSelection 7 | { 8 | private static Scanner input = new Scanner(System.in).useLocale(Locale.US); 9 | 10 | 11 | public static void main(String [] args) 12 | { 13 | int n = 25; 14 | 15 | if (args.length > 0) n = Integer.parseInt(args[0]); 16 | 17 | Random r = new Random(); 18 | 19 | System.out.println("student number: " + (r.nextInt(n) + 1)); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /code/basic/TestPoint.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class TestPoint 4 | { 5 | public static void main(String [] args) 6 | { 7 | Point p0 = new Point(); 8 | Point p1 = new Point(7, 8); 9 | Point p2 = new Point(1, 2); 10 | 11 | System.out.println("p0: " + p0); 12 | System.out.println("p1: " + p1); 13 | System.out.println("p2: " + p2); 14 | 15 | p0.setX(65); 16 | p0.setY(-7); 17 | System.out.println("p0: " + p0); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /code/basic/DivisionByZero2.java: -------------------------------------------------------------------------------- 1 | public class DivisionByZero2 2 | { 3 | public static void main(String [] args) 4 | { 5 | double x, y, z; 6 | 7 | x = 1.0; y = 0.0; z = x / y; 8 | System.out.printf("x = %13e | y = %13e | z = %13e\n", x, y, z); 9 | x = -1.0; y = 0.0; z = x / y; 10 | System.out.printf("x = %13e | y = %13e | z = %13e\n", x, y, z); 11 | x = 0.0; y = 0.0; z = x / y; 12 | System.out.printf("x = %13e | y = %13e | z = %13e\n", x, y, z); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /code/linear-data-structures/linear-data-structures.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | When contributing to this repository, please first discuss the change 4 | you wish to make via issue with the owners of this repository before 5 | making a change. 6 | 7 | Please note we have a code of conduct, we encourage you to follow it 8 | in all your interactions with the project. 9 | 10 | ## Pull Request Process 11 | 12 | 1. Describe the error you encountered in the code. 13 | 2. Test: compile and run the code corrected in your computer. 14 | 3. Ensure proposed changes run as expected. 15 | -------------------------------------------------------------------------------- /code/linear-data-structures/makefile: -------------------------------------------------------------------------------- 1 | 2 | 3 | all: 4 | javac -cp classes -d classes src/*.java 5 | #javac -cp . -d . src/*.java 6 | 7 | clean: 8 | rm -rf classes/* 9 | rm -rf linear/* 10 | rm -rf docs/ 11 | 12 | doc: 13 | javadoc -d docs src/*.java 14 | 15 | 16 | jar: 17 | jar cvf linear.jar linear src 18 | 19 | 20 | test-stacks: 21 | java -cp . linear.TestStacks 22 | 23 | test-queues: 24 | java -cp . linear.TestQueues 25 | 26 | test-lists: 27 | java -cp . linear.TestLists 28 | 29 | test-lists2: 30 | java -cp . linear.TestLists2 31 | -------------------------------------------------------------------------------- /code/agenda.txt: -------------------------------------------------------------------------------- 1 | Coltrane 2 | John 3 | john.coltrane@bluenote.www 4 | 2354545 5 | 1927 09 09 6 | Davis 7 | Miles 8 | miles.davis@bluenote.www 9 | 5345874 10 | 1930 03 31 11 | Petterson 12 | Oscar 13 | oscar.p@jazzworld.www 14 | 2234234 15 | 1938 07 17 16 | James 17 | Skip 18 | sjames@blueslegends.www 19 | 372834223 20 | 1918 11 19 21 | Cullum 22 | Jamie 23 | me@jamiecullum.com 24 | 347827482 25 | 1980 2 12 26 | King 27 | B.B. 28 | bbk@blueslegends.www 29 | 34242343 30 | 1922 11 07 31 | Monk 32 | Thelonious 33 | tmonk@bluenote.www 34 | 57834573 35 | 1917 10 10 36 | -------------------------------------------------------------------------------- /code/arrays/agenda.txt: -------------------------------------------------------------------------------- 1 | Coltrane 2 | John 3 | john.coltrane@bluenote.www 4 | 2354545 5 | 1927 09 09 6 | Davis 7 | Miles 8 | miles.davis@bluenote.www 9 | 5345874 10 | 1930 03 31 11 | Petterson 12 | Oscar 13 | oscar.p@jazzworld.www 14 | 2234234 15 | 1938 07 17 16 | James 17 | Skip 18 | sjames@blueslegends.www 19 | 372834223 20 | 1918 11 19 21 | Cullum 22 | Jamie 23 | me@jamiecullum.com 24 | 347827482 25 | 1980 2 12 26 | King 27 | B.B. 28 | bbk@blueslegends.www 29 | 34242343 30 | 1922 11 07 31 | Monk 32 | Thelonious 33 | tmonk@bluenote.www 34 | 57834573 35 | 1917 10 10 36 | -------------------------------------------------------------------------------- /code/methods/Swap3.java: -------------------------------------------------------------------------------- 1 | public class Swap3 2 | { 3 | public static void swap(Point p1, Point p2) 4 | { 5 | double temp; 6 | 7 | temp = p1.getX(); 8 | p1.setX(p2.getX()); 9 | p2.setX(temp); 10 | 11 | temp = p1.getY(); 12 | p1.setY(p2.getY()); 13 | p2.setY(temp); 14 | } 15 | public static void main(String [] args) 16 | { 17 | Point p1 = new Point(); 18 | Point p2 = new Point(5, 2); 19 | swap(p1, p2); 20 | System.out.println("p1 = " + p1 + " p2 = " + p2); 21 | } 22 | } -------------------------------------------------------------------------------- /code/basic/Modulus.java: -------------------------------------------------------------------------------- 1 | public class Modulus 2 | { 3 | public static void main(String [] args) 4 | { 5 | int a = 123456; 6 | 7 | System.out.printf(" %8d %8d\n", a / 10, a % 10); 8 | System.out.printf(" %8d %8d\n", a / 100, a % 100); 9 | System.out.printf(" %8d %8d\n", a / 1000, a % 1000); 10 | System.out.printf(" %8d %8d\n", a / 10000, a % 10000); 11 | System.out.printf(" %8d %8d\n", a / 100000, a % 100000); 12 | System.out.printf(" %8d %8d\n", a / 1000000, a % 1000000); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /code/recursion/ToBinary.java: -------------------------------------------------------------------------------- 1 | import java.util.Random; 2 | 3 | public class ToBinary 4 | { 5 | public static void main(String [] args) 6 | { 7 | Random r = new Random(); 8 | 9 | for (int i = 0; i < 10; i++) { 10 | long n = r.nextInt(1 << 10); 11 | System.out.printf(" %12d %20d\n", n, toBinary(n)); 12 | } 13 | } 14 | 15 | private static long toBinary(long n) 16 | { 17 | if (n < 2) 18 | return n; 19 | else 20 | return 10 * toBinary(n >> 1) + (n % 2); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /code/exceptions/IllegalDateException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * User-defined exception. 3 | * 4 | * @author Jon Ander Gómez (jon@dsic.upv.es) 5 | * @version 1.0 (March 2012) 6 | */ 7 | public class IllegalDateException 8 | extends Exception 9 | { 10 | /** 11 | * Constructor for preparing objects of this class. 12 | * 13 | * @param msg Error message describing the conditions that cause this exception. 14 | */ 15 | public IllegalDateException(String msg) 16 | { 17 | // Call to one constructor of the superclass. 18 | super("Illegal date: " + msg); 19 | } 20 | } -------------------------------------------------------------------------------- /cpr/cpp/makefile: -------------------------------------------------------------------------------- 1 | CFLAGS=-g -Wall -std=c11 -O3 -I. 2 | CPPFLAGS=-g -Wall -std=c++11 -O3 -I. 3 | 4 | all: sorting.exe sorting_stl.exe check_gcd.exe check_pf.exe 5 | 6 | check_gcd.exe: greatestCommonDivisor.o check_gcd.o 7 | g++ $(CPPFLAGS) -o $@ $+ 8 | 9 | check_pf.exe: primeFactorization.o check_pf.o 10 | g++ $(CPPFLAGS) -o $@ $+ 11 | 12 | clean: 13 | rm -f *.exe *.o *.a *.so 14 | rm -rf *.exe.dSYM 15 | 16 | 17 | %.o: %.c 18 | gcc $(CFLAGS) -c $? 19 | 20 | %.exe: %.c 21 | gcc $(CFLAGS) -o $@ $? 22 | 23 | %.o: %.cpp 24 | g++ $(CPPFLAGS) -c $? 25 | 26 | %.exe: %.cpp 27 | g++ $(CPPFLAGS) -o $@ $? 28 | -------------------------------------------------------------------------------- /code/basic/Square.java: -------------------------------------------------------------------------------- 1 | public class Square extends Rectangle { 2 | 3 | public Square() { 4 | super(1, 1, 50, 50); 5 | } 6 | public Square(double side, double x, double y) { 7 | super(side, side, x, y); 8 | } 9 | 10 | public double getSide() { return this.getBase(); } 11 | 12 | public void setSide(double s) { this.setBase(s); this.setHeight(s); } 13 | 14 | @Override 15 | public String toString() { 16 | return "Square centred at " 17 | + this.getCentre().toString() 18 | + " with sides of = " + this.getSide() + " m"; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /code/basic/Trace01.java: -------------------------------------------------------------------------------- 1 | public class Trace01 2 | { 3 | public static void main(String[] args) 4 | { 5 | int a = 12, b = 8, c = 6; 6 | System.out.println(a + " " + b + " " + c); 7 | a = c; 8 | System.out.println(a + " " + b + " " + c); 9 | c += b; 10 | System.out.println(a + " " + b + " " + c); 11 | a = b + c; 12 | System.out.println(a + " " + b + " " + c); 13 | a++; 14 | b++; 15 | System.out.println(a + " " + b + " " + c); 16 | c = a++ + ++b; 17 | System.out.println(a + " " + b + " " + c); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /examples/README.md: -------------------------------------------------------------------------------- 1 | # Self-contained examples 2 | 3 | The purpose of examples included in this folder is just to provide students with an overview of what a small application should look like, including the use of packages in some cases. 4 | 5 | ### _The examples contained here could be incomplete because are used in earlier stages of my course on Computing Programming_ 6 | 7 | * [First version of a personal agenda without contacts](agenda1) 8 | * [Use of COVID-19 data from most countries of the world to illustrate how to work with arrays ](covid_19) 9 | * [Medium-level version of a personal agenda with contacts](agenda2) 10 | -------------------------------------------------------------------------------- /code/arrays/Example1.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Example1 4 | { 5 | public static void main(String [] args) 6 | { 7 | int [] a = new int [2]; 8 | 9 | a[0] = 7; 10 | a[1] = 3; 11 | 12 | swap(a); 13 | 14 | print(a); 15 | } 16 | 17 | public static void swap(int [] a) 18 | { 19 | int temp = a[0]; 20 | a[0] = a[1]; 21 | a[1] = temp; 22 | } 23 | 24 | public static void print(int [] a) 25 | { 26 | for (int i = 0; i < a.length; i++) 27 | System.out.print(" " + a[i]); 28 | System.out.println(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /code/testing-final-grade.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | while [ true ] 4 | do 5 | a=$((${RANDOM} % 10 )) 6 | b=${RANDOM} 7 | #mg1="${a}.${b}" 8 | mg1="${a}" 9 | a=$((${RANDOM} % 10 )) 10 | b=${RANDOM} 11 | #mg2="${a}.${b}" 12 | mg2="${a}" 13 | a=$((${RANDOM} % 10 )) 14 | b=${RANDOM} 15 | #lg1="${a}.${b}" 16 | lg1="${a}" 17 | a=$((${RANDOM} % 10 )) 18 | b=${RANDOM} 19 | #lg2="${a}.${b}" 20 | lg2="${a}" 21 | 22 | echo ${mg1} ${mg2} ${lg1} ${lg2} 23 | echo ${mg1} ${mg2} ${lg1} ${lg2} | ./run-examples.sh FinalGrade 24 | if [ $? -ne 0 ] 25 | then 26 | exit 1 27 | fi 28 | done 29 | -------------------------------------------------------------------------------- /code/basic/IntegerDataTypes.java: -------------------------------------------------------------------------------- 1 | public class IntegerDataTypes 2 | { 3 | public static void main(String [] args) 4 | { 5 | System.out.printf("%-12s %20d %20d \n", 6 | "byte", Byte.MIN_VALUE, Byte.MAX_VALUE); 7 | System.out.printf("%-12s %20d %20d \n", 8 | "short", Short.MIN_VALUE, Short.MAX_VALUE); 9 | System.out.printf("%-12s %20d %20d \n", 10 | "int", Integer.MIN_VALUE, Integer.MAX_VALUE); 11 | System.out.printf("%-12s %20d %20d \n", 12 | "long", Long.MIN_VALUE, Long.MAX_VALUE); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /examples/agenda2/agenda2.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /code/basic/Rounding.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Rounding 4 | { 5 | public static void main(String [] args) 6 | { 7 | Scanner input = new Scanner(System.in).useLocale(Locale.US); 8 | 9 | System.out.print("\n Please, enter a double value:"); 10 | double x = input.nextDouble(); 11 | 12 | double y = myRound(x, 2); 13 | 14 | System.out.println(x); 15 | System.out.println(y); 16 | System.out.printf("%.2f\n", x); 17 | } 18 | public static double myRound(double x, int digits) 19 | { 20 | return Math.round(x * Math.pow(10, digits)) / Math.pow(10, digits); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /cpr/cpp/check_pf.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | 9 | typedef pair prime_factor; 10 | 11 | list * primeFactorization_v2(uint64_t n); 12 | 13 | int main(int argc, char * argv[]) 14 | { 15 | int n; 16 | 17 | while (cin >> n) 18 | { 19 | cout << n << endl; 20 | 21 | list *l = primeFactorization_v2(n); 22 | 23 | for (prime_factor pf : *l) 24 | cout << " " << pf.first << " " << pf.second << endl; 25 | 26 | cout << endl; 27 | } 28 | 29 | return EXIT_SUCCESS; 30 | } 31 | -------------------------------------------------------------------------------- /examples/agenda3/agenda3.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /examples/covid_19/covid_19.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /code/basic/RealDataTypes.java: -------------------------------------------------------------------------------- 1 | public class RealDataTypes 2 | { 3 | public static void main(String [] args) 4 | { 5 | float x = 2.0F / 7.0F; 6 | double y = 2.0 / 7.0; 7 | 8 | System.out.printf(" x = %22.17f %22.17e\n", x, x); 9 | System.out.printf(" y = %22.17f %22.17e\n", y, y); 10 | System.out.println(); 11 | System.out.printf(" Float: min = %22.15e max = %22.16e \n", 12 | Float.MIN_VALUE, Float.MAX_VALUE); 13 | System.out.printf(" Double: min = %22.15e max = %22.16e \n", 14 | Double.MIN_VALUE, Double.MAX_VALUE); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /code/inheritance/Person.java: -------------------------------------------------------------------------------- 1 | public class Person { 2 | private String name; 3 | private int age; 4 | 5 | public Person(String name, int age) { 6 | this.name = name; 7 | this.age = age; 8 | } 9 | 10 | public String getName() { 11 | return name; 12 | } 13 | 14 | public int getAge() { 15 | return age; 16 | } 17 | 18 | @Override 19 | public String toString() { 20 | return "Name: " + name + " Age: " + age; 21 | } 22 | 23 | // see how this method is reused in class NewStudent 24 | public static String toString(Person p) { 25 | return "Name: " + p.name + " Age: " + p.age; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /code/basic/ExampleOfStandardInputOutput.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class ExampleOfStandardInputOutput 4 | { 5 | private static Scanner input = new Scanner(System.in).useLocale(Locale.US); 6 | 7 | public static void main(String [] args) 8 | { 9 | while (input.hasNext()) { // Check if more values are available in the standard input 10 | int value = input.nextInt(); // Read next token in the standard input and convert it to an integer 11 | 12 | if ((value % 2) == 0) { 13 | System.out.println(value); 14 | } else { 15 | System.err.println(value); 16 | } 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /code/basic/Overflow.java: -------------------------------------------------------------------------------- 1 | public class Overflow 2 | { 3 | public static void main(String [] args) 4 | { 5 | byte b = 127; 6 | System.out.printf("byte %32d+1 = %d\n", b, ++b); 7 | short s = 32767; 8 | System.out.printf("short %32d+1 = %d\n", s, ++s); 9 | int i = 0x07fffffff; 10 | System.out.printf("int %32d+1 = %d\n", i, i + 1); 11 | long l = 0x07fffffffffffffffL; 12 | System.out.printf("long %32d+1 = %d\n", l, l + 1); 13 | 14 | i = 1000000; 15 | System.out.printf(" %d * %d = %d\n", i, i, i * i); 16 | l = 1000000; 17 | System.out.printf(" %d * %d = %d\n", l, l, l * l); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /code/basic/Test01.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | import java.io.*; 4 | 5 | 6 | public class Test01 7 | { 8 | private static Scanner input = new Scanner(System.in).useLocale(Locale.US); 9 | 10 | 11 | public static void main(String [] args) 12 | { 13 | double d1 = 2.0, d2 = 3.0 + d1; 14 | 15 | System.out.printf(" d1 = %f d2 = %f\n", d1, d2); 16 | 17 | int x1 = 5, x2 = 9; 18 | 19 | final int _X_ = x1 + x2; 20 | 21 | x1 += 2; 22 | x2 -= 3; 23 | 24 | // _X_ = x1 + x2; // uncomment this line to see the error shown by the compiler 25 | 26 | System.out.printf("x1 = %d x2 = %d _X_ = %d\n", x1, x2, _X_); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /code/files/TestFile.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | class TestFile 4 | { 5 | public static void main(String [] args) 6 | { 7 | File f = new File("/home/jon/file.txt"); 8 | //File f = new File("../test_dir/file4323.txt"); 9 | //File f = new File("/root/.bashrc"); 10 | 11 | if (f.exists()) 12 | System.out.println("File exists!"); 13 | else 14 | System.err.println("File doesn’t exist!"); 15 | 16 | System.err.println(); 17 | 18 | System.out.println(" getName(): " + f.getName()); 19 | System.out.println("getParent(): " + f.getParent()); 20 | System.out.println(" length(): " + f.length()); 21 | } 22 | } -------------------------------------------------------------------------------- /code/files/TestPrintWriter.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | public class TestPrintWriter 4 | { 5 | public static void main(String [] args) 6 | { 7 | String fileName = "file2.txt"; 8 | 9 | try { 10 | // Opens the file 11 | PrintWriter pw = new PrintWriter(new File(fileName)); 12 | 13 | pw.print("El veloz murciélago hindú"); 14 | pw.println(" comía feliz cardillo y kiwi"); 15 | pw.println(4.815162342); 16 | 17 | // Closes the file 18 | pw.close(); 19 | } 20 | catch (FileNotFoundException e) { 21 | System.err.println("Error opening or creating " + fileName); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /code/exceptions/ReadNumbersOriginal.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class ReadNumbersOriginal 4 | { 5 | private static Scanner input; 6 | 7 | public static void main(String [] args) 8 | { 9 | input = new Scanner(System.in); 10 | 11 | System.out.print("Enter an integer number from 1 up to 100, both included: "); 12 | int n = input.nextInt(); 13 | 14 | System.out.print("Enter a real number in the range 0..1: "); 15 | double x = input.nextDouble(); 16 | 17 | 18 | System.out.println(); 19 | System.out.println(); 20 | System.out.printf(" n = %d x = %f\n", n, x); 21 | System.out.println(); 22 | System.out.println(); 23 | } 24 | } -------------------------------------------------------------------------------- /cpr/java/ObjectComparator.java: -------------------------------------------------------------------------------- 1 | 2 | package es.upv.etsinf.sorting; 3 | 4 | import java.util.Comparator; 5 | 6 | 7 | public class ObjectComparator implements Comparator 8 | { 9 | public int compare(Object o1, Object o2) 10 | { 11 | if (o1 == null) throw new NullPointerException("First argument is null!"); 12 | if (o2 == null) throw new NullPointerException("Second argument is null!"); 13 | 14 | if ((o1 instanceof String && o2 instanceof String) == false) 15 | throw new ClassCastException("Objects are incompatible for comparison!"); 16 | 17 | 18 | String s1 = (String)o1; 19 | String s2 = (String)o2; 20 | 21 | return s1.compareTo(s2); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /examples/agenda1/agenda1.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /code/inheritance/TestStudent3.java: -------------------------------------------------------------------------------- 1 | public class TestStudent3 { 2 | public static void main(String[] args) { 3 | Student s = new Student("John Smith", 19); 4 | Person p = new Person("John Smith", 19); 5 | Person q = new Student("Patty Smith", 39); 6 | NewStudent ns = new NewStudent("Patty Smith", 39, 9.999F); 7 | 8 | System.out.println("Person----: " + p.toString()); 9 | System.out.println("Student---: " + s.toString()); 10 | System.out.println("----------: " + q.toString()); 11 | System.out.println("----------: " + q); 12 | System.out.println("NewStudent: " + ns); 13 | 14 | System.out.println(); 15 | ClassesForAnObject.listOfClasses(ns); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /code/recursion/Reverse.java: -------------------------------------------------------------------------------- 1 | 2 | public class Reverse 3 | { 4 | public static void main(String [] args) 5 | { 6 | int n = 12345678; 7 | 8 | for (int i = 0; i < args.length; i++) { 9 | if (args[i].equals("-n")) 10 | n = Integer.parseInt(args[i + 1]); 11 | } 12 | 13 | reverse(n); 14 | } 15 | 16 | /* 17 | print(n) if n < 10 18 | print(n % 10) ; reverse(n / 10) if n >= 0 19 | */ 20 | private static void reverse(int n) 21 | { 22 | if (n < 10) { 23 | System.out.println(n); 24 | } else { 25 | System.out.print(n % 10); // forward path 26 | reverse(n / 10); // recursive call 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /code/basic/TimeConversion.java: -------------------------------------------------------------------------------- 1 | public class TimeConversion 2 | { 3 | public static void main(String [] args) 4 | { 5 | final int SECONDS_PER_DAY = 24 * 60 * 60; 6 | 7 | long seconds = 765432; 8 | 9 | long days = seconds / SECONDS_PER_DAY; 10 | System.out.printf(" %d seconds are: \n %5d days\n", seconds, days); 11 | 12 | seconds = seconds % SECONDS_PER_DAY; 13 | 14 | long hours = seconds / (60 * 60); 15 | System.out.printf(" %5d hours\n", hours); 16 | 17 | seconds %= (60 * 60); 18 | 19 | long minutes = seconds / 60; 20 | System.out.printf(" %5d minutes\n", minutes); 21 | 22 | seconds %= 60; 23 | System.out.printf(" %5d seconds\n", seconds); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /code/basic/DataTypeConversions2.java: -------------------------------------------------------------------------------- 1 | public class DataTypeConversions2 2 | { 3 | public static void main(String [] args) 4 | { 5 | double minValue = 10.0, maxValue = 20.0; 6 | int numIntervals = 2; 7 | double value = 14.9; 8 | //value=15.0; 9 | 10 | double sizeInterval = (maxValue - minValue) / numIntervals; 11 | int indexInterval = (int)((value - minValue) / sizeInterval); 12 | 13 | System.out.printf("%.2f belongs to interval %d", 14 | value, indexInterval); 15 | 16 | double a = minValue + indexInterval * sizeInterval; 17 | double b = minValue + (indexInterval+1) * sizeInterval; 18 | 19 | System.out.printf(" which is [%.2f, %.2f[\n", a, b); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /code/methods/Methods1.java: -------------------------------------------------------------------------------- 1 | public class Methods1 2 | { 3 | public static void change(int j, int k) 4 | { 5 | int aux = j; 6 | j = k; 7 | k = aux; 8 | System.out.println("Inside: " + j + " " + k); 9 | } // end of change() 10 | 11 | public static void inc(int j, int k) 12 | { 13 | j++; 14 | k++; 15 | System.out.println("Inside: " + j + " " + k); 16 | } // end of inc() 17 | 18 | public static void main(String[] args) 19 | { 20 | int j = 1335; 21 | int k = 3672; 22 | 23 | System.out.println("Before: " + j + " " + k); 24 | change(j, k); 25 | inc(k, j); 26 | System.out.println("After: " + j + " " + k); 27 | } // end of main() 28 | } // end of class -------------------------------------------------------------------------------- /examples/covid_19/scripts/compile.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -eu 2 | 3 | # compiles the package covid19 4 | for file in src/Timestamp.java src/*.java 5 | do 6 | javac -cp classes -d classes ${file} 7 | done 8 | 9 | # creates the JAR file with the contents of the package 10 | jar_filename="lib/covid19.jar" 11 | rm -f ${jar_filename} 12 | jar cvf ${jar_filename} -C classes etsinf/prg/covid19/ 13 | 14 | # compiles the other source files for testing the classes of the package. 15 | # the JAR file is used in the class path to indicate the compiler that 16 | # classes of the package are inside the JAR file in this case. 17 | for file in test_src/TestingCovid19.java 18 | do 19 | javac -cp ${jar_filename} -d classes ${file} 20 | # javac -cp classes -d classes test_src/${file} # alternative 21 | done 22 | -------------------------------------------------------------------------------- /code/basic/Dice.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Dice 4 | { 5 | private static Scanner input = new Scanner(System.in).useLocale(Locale.US); 6 | 7 | public static void main(String [] args) 8 | { 9 | int dice = (int)(6 * Math.random()) + 1; 10 | 11 | System.out.println("The roll of the dice is: " + dice); 12 | 13 | //testing(); 14 | } 15 | 16 | private static void testing() 17 | { 18 | while (true) { 19 | double d = Math.random(); 20 | int d1 = (int)(6 * d) + 1; 21 | int d2 = (int)(6 * d + 1); 22 | 23 | System.out.printf("%d vs %d\n", d1, d2); 24 | 25 | if (d1 != d2) 26 | throw new RuntimeException("the impossible happened!"); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /examples/agenda1/scripts/compile.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -eu 2 | 3 | # compiles the package agenda1 4 | for file in Timestamp.java TimeDelta.java Event.java 5 | do 6 | javac -cp classes -d classes src/${file} 7 | done 8 | 9 | # creates the JAR file with the contents of the package 10 | jar_filename="lib/agenda1.jar" 11 | rm -f ${jar_filename} 12 | jar cvf ${jar_filename} -C classes etsinf/prg/agenda1/ 13 | 14 | # compiles the other source files for testing the classes of the package. 15 | # the JAR file is used in the class path to indicate the compiler that 16 | # classes of the package are inside the JAR file in this case. 17 | for file in TestingAgenda1.java 18 | do 19 | javac -cp ${jar_filename} -d classes test_src/${file} 20 | # javac -cp classes -d classes test_src/${file} # alternative 21 | done 22 | -------------------------------------------------------------------------------- /code/files/TestBinaryWriting.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | public class TestBinaryWriting 4 | { 5 | public static void main(String [] args) 6 | { 7 | try { 8 | 9 | File file = new File("file-for-testing-1.dat"); 10 | FileOutputStream fos = new FileOutputStream(file); 11 | ObjectOutputStream oos = new ObjectOutputStream(fos); 12 | 13 | oos.writeUTF("Hello crazy world!"); 14 | oos.writeInt(2016); 15 | oos.writeDouble(21.4); 16 | 17 | oos.close(); 18 | } 19 | catch (IOException e) 20 | { 21 | e.printStackTrace(System.err); 22 | } 23 | catch (Exception e) 24 | { 25 | e.printStackTrace(System.err); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /code/methods/TestingEquals.java: -------------------------------------------------------------------------------- 1 | public class TestingEquals 2 | { 3 | public static void main(String [] args) 4 | { 5 | Point p1 = new Point(3.0, 4.0); 6 | Point p2 = new Point(3.0, 4.0); 7 | Point p3 = p1; 8 | 9 | System.out.printf("%s and %s %s the same object\n", p1, p2, p1 == p2 ? "are" : "are not"); 10 | System.out.printf("%s and %s %s the same object\n", p1, p3, p1 == p3 ? "are" : "are not"); 11 | System.out.printf("%s and %s %s the same object\n", p2, p3, p2 == p3 ? "are" : "are not"); 12 | 13 | System.out.printf("%s and %s %s equal\n", p1, p2, p1.equals(p2) ? "are" : "are not"); 14 | System.out.printf("%s and %s %s equal\n", p1, p3, p1.equals(p3) ? "are" : "are not"); 15 | System.out.printf("%s and %s %s equal\n", p2, p3, p2.equals(p3) ? "are" : "are not"); 16 | } 17 | } -------------------------------------------------------------------------------- /cpr/java/StringHash.java: -------------------------------------------------------------------------------- 1 | package es.upv.etsinf.strings; 2 | 3 | public class StringHash 4 | { 5 | // hash function extracted from: 6 | // http://stackoverflow.com/questions/114085/fast-string-hashing-algorithm-with-low-collision-rates-with-32-bit-integer 7 | public static long hashCode( String s ) 8 | { 9 | long hash = 0; 10 | 11 | for( int i=0; i < s.length(); i++ ) { 12 | 13 | hash += s.charAt(i); 14 | hash += (hash << 10); 15 | hash ^= (hash >> 6); 16 | } 17 | 18 | hash += (hash << 3); 19 | hash ^= (hash >> 11); 20 | hash += (hash << 15); 21 | 22 | return hash; 23 | } 24 | public static long hashCode( String s, int hashSize ) 25 | { 26 | return hashCode( s ) % hashSize; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /code/basic/SphereExample1.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | import java.io.*; 4 | 5 | public class SphereExample1 6 | { 7 | private static Scanner input = new Scanner(System.in).useLocale(Locale.US); 8 | 9 | public static void main(String [] args) 10 | { 11 | System.out.print("\nPlease, enter a positive real value for the radius: "); 12 | double radius = input.nextDouble(); 13 | 14 | double area, volume1, volume2; 15 | 16 | area = 4 * Math.PI * radius * radius; 17 | volume1 = 4.0 / 3 * Math.PI * radius * radius * radius; 18 | volume2 = area * radius / 3; 19 | 20 | 21 | System.out.printf(" area = %30.20f\n", area); 22 | System.out.printf("volume1 = %30.20f\n", volume1); 23 | System.out.printf("volume2 = %30.20f\n", volume2); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /examples/agenda2/scripts/compile.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -eu 2 | 3 | # compiles the package agenda2 4 | for file in Timestamp.java TimeDelta.java Event.java Date.java Contact.java Agenda.java 5 | do 6 | javac -cp classes -d classes src/${file} 7 | done 8 | 9 | # creates the JAR file with the contents of the package 10 | jar_filename="lib/agenda2.jar" 11 | rm -f ${jar_filename} 12 | jar cvf ${jar_filename} -C classes etsinf/prg/agenda2/ 13 | 14 | # compiles the other source files for testing the classes of the package. 15 | # the JAR file is used in the class path to indicate the compiler that 16 | # classes of the package are inside the JAR file in this case. 17 | for file in TestingAgenda2.java 18 | do 19 | javac -cp ${jar_filename} -d classes test_src/${file} 20 | # javac -cp classes -d classes test_src/${file} # alternative 21 | done 22 | -------------------------------------------------------------------------------- /code/exams_from_previous_years/2019_2020/scripts/compile.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -eu 2 | 3 | # compiles the package agenda2 4 | for file in TimeInstant.java PieceOfNews.java BulletinBoard.java Exercises2and3.java 5 | do 6 | javac -cp classes -d classes src/${file} 7 | done 8 | 9 | # creates the JAR file with the contents of the package 10 | jar_filename="lib/exam2.jar" 11 | rm -f ${jar_filename} 12 | jar cvf ${jar_filename} -C classes etsinf/prg/exam2/ 13 | 14 | # compiles the other source files for testing the classes of the package. 15 | # the JAR file is used in the class path to indicate the compiler that 16 | # classes of the package are inside the JAR file in this case. 17 | for file in TestExam2.java 18 | do 19 | javac -cp ${jar_filename} -d classes test_src/${file} 20 | # javac -cp classes -d classes test_src/${file} # alternative 21 | done 22 | -------------------------------------------------------------------------------- /code/basic/CharExample1.java: -------------------------------------------------------------------------------- 1 | public class CharExample1 2 | { 3 | public static void main(String [] args) 4 | { 5 | char upperCaseA = 'A'; 6 | char lowerCaseZ = 'z'; 7 | char digit0 = '0'; 8 | char whiteSpace = ' '; 9 | char newLine = '\n'; 10 | char symbol = '?'; 11 | char tab = '\t'; 12 | 13 | System.out.printf(" |%c| %5d\n", upperCaseA, (int)upperCaseA); 14 | System.out.printf(" |%c| %5d\n", lowerCaseZ, (int)lowerCaseZ); 15 | System.out.printf(" |%c| %5d\n", digit0, (int)digit0); 16 | System.out.printf(" |%c| %5d\n", whiteSpace, (int)whiteSpace); 17 | System.out.printf(" |%c| %5d\n", newLine, (int)newLine); 18 | System.out.printf(" |%c| %5d\n", symbol, (int)symbol); 19 | System.out.printf(" |%c| %5d\n", tab, (int)tab); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /examples/agenda3/scripts/compile.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -eu 2 | 3 | # compiles the package agenda3 4 | for file in Timestamp.java TimeDelta.java Event.java NodeEvent.java Date.java Contact.java NodeContact.java Agenda.java 5 | do 6 | javac -cp classes -d classes src/${file} 7 | done 8 | 9 | # creates the JAR file with the contents of the package 10 | jar_filename="lib/agenda3.jar" 11 | rm -f ${jar_filename} 12 | jar cvf ${jar_filename} -C classes etsinf/prg/agenda3/ 13 | 14 | # compiles the other source files for testing the classes of the package. 15 | # the JAR file is used in the class path to indicate the compiler that 16 | # classes of the package are inside the JAR file in this case. 17 | for file in TestingAgenda3.java 18 | do 19 | javac -cp ${jar_filename} -d classes test_src/${file} 20 | # javac -cp classes -d classes test_src/${file} # alternative 21 | done 22 | -------------------------------------------------------------------------------- /code/inheritance/Student.java: -------------------------------------------------------------------------------- 1 | public class Student extends Person { 2 | private int ects; 3 | 4 | public Student(String name, int age) { 5 | super(name, age); 6 | this.ects = 60; 7 | } 8 | 9 | public int getECTS() { 10 | return ects; 11 | } 12 | 13 | @Override 14 | public String toString() { 15 | /* 16 | * option 1: complete override * 17 | * return this.getName() + " " 18 | * + this.getAge() 19 | * + " ECTS: " + ects; 20 | */ 21 | /* option 2: partial override -- the preferred one */ 22 | return super.toString() + " ECTS: " + ects; 23 | 24 | /* 25 | * option 3: partial override but 26 | * using an existing object 27 | * of the parent class * 28 | * return Person.toString(this) 29 | * + " ECTS: " + ects; 30 | */ 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /cpr/java/FindCycles.java: -------------------------------------------------------------------------------- 1 | package es.upv.etsinf.graphs; 2 | 3 | import java.util.*; 4 | 5 | public class FindCycles 6 | extends GraphOperations 7 | { 8 | public FindCycles(Graph g) 9 | { 10 | super(g); 11 | } 12 | 13 | public void processVertex(Vertex v) 14 | { 15 | } 16 | 17 | public void processEdge(Edge e) 18 | { 19 | if (parent[e.getDestination().getId()] != e.getOrigin()) { 20 | 21 | System.err.println("Cycle from " + e.getDestination() + " to " + e.getOrigin()); 22 | LinkedList path = findPath(e.getDestination().getId(), e.getOrigin().getId()); 23 | for (Vertex v : path) 24 | System.out.println(" --> " + v); 25 | finished = true; 26 | } 27 | } 28 | 29 | public void run() { 30 | initializeSearch(); 31 | 32 | dfs(g.getVertex(0)); 33 | } 34 | } -------------------------------------------------------------------------------- /cpr/java/ConnectedComponents.java: -------------------------------------------------------------------------------- 1 | package es.upv.etsinf.graphs; 2 | 3 | public class ConnectedComponents 4 | extends GraphOperations 5 | { 6 | public ConnectedComponents(Graph g) 7 | { 8 | super(g); 9 | } 10 | 11 | public void processVertex(Vertex v) 12 | { 13 | System.out.printf(" %d", v.getId()); 14 | } 15 | 16 | public void processEdge(Edge e) 17 | { 18 | } 19 | 20 | public void showConnectedComponents() 21 | { 22 | initializeSearch(); 23 | 24 | int c = 0; 25 | 26 | for (int i = 0; i < g.getNumVertices(); i++) { 27 | 28 | Vertex v = g.getVertex(i); 29 | 30 | if (!discovered[v.getId()]) { 31 | c = c + 1; 32 | System.out.printf("Component %d:", c); 33 | dfs(v); 34 | System.out.println(); 35 | } 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /code/arrays/ComputeAverage.java: -------------------------------------------------------------------------------- 1 | import java.util.Random; 2 | 3 | 4 | public class ComputeAverage 5 | { 6 | public static void main(String [] args) 7 | { 8 | double [] x = new double [1000000]; 9 | 10 | double mean = computeAverage(x); 11 | System.out.println("mean = " + mean); 12 | 13 | fillArray(x); 14 | 15 | mean = computeAverage(x); 16 | System.out.println("mean = " + mean); 17 | } 18 | 19 | public static void fillArray(double [] a) 20 | { 21 | Random r = new Random(); 22 | 23 | // fill the array with random values 24 | for (int i = 0; i < a.length; ++i) 25 | a[i] = 67 + 11 * r.nextGaussian(); 26 | } 27 | 28 | public static double computeAverage(double [] a) 29 | { 30 | double sum = 0.0; 31 | 32 | for (int i = 0; i < a.length; ++i) sum += a[i]; 33 | 34 | return sum / a.length; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /code/basic/ComparingPoints.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class ComparingPoints 4 | { 5 | private static Scanner input = new Scanner(System.in).useLocale(Locale.US); 6 | 7 | public static void main(String [] args) 8 | { 9 | Point p1 = new Point(100, 200); 10 | Point p2 = new Point(100, 200); 11 | Point p3 = p1; 12 | 13 | System.out.printf("p1 and p2 %s the same object\n", ((p1 == p2) ? "are" : "are not")); 14 | System.out.printf("p1 and p3 %s the same object\n", ((p1 == p3) ? "are" : "are not")); 15 | System.out.printf("p2 and p3 %s the same object\n", ((p2 == p3) ? "are" : "are not")); 16 | 17 | System.out.printf("p1 and p2 %s equal\n", (p1.equals(p2) ? "are" : "are not")); 18 | System.out.printf("p1 and p3 %s equal\n", (p1.equals(p3) ? "are" : "are not")); 19 | System.out.printf("p2 and p3 %s equal\n", (p2.equals(p3) ? "are" : "are not")); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /code/basic/ProblemsInClass.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.util.Locale; 3 | 4 | public class ProblemsInClass 5 | { 6 | public static void main(String [] args) 7 | { 8 | int h, m; 9 | 10 | Scanner input = new Scanner(System.in).useLocale(Locale.US); 11 | 12 | while (input.hasNext()) { 13 | System.out.print("Please, could you enter the hour of the day? "); 14 | h = input.nextInt(); 15 | System.out.print("Please, could you enter the minutes within the hour of the day? "); 16 | m = input.nextInt(); 17 | 18 | String s = "AM"; 19 | System.out.printf("%02d:%02d\n", h, m); 20 | 21 | if (0 <= h && h <= 11 || h % 24 == 0) s = "AM"; else s = "PM"; 22 | if (h % 24 == 0) h = 12; 23 | if (h > 12) h = h % 12; 24 | 25 | System.out.printf("%02d:%02d %s\n", h, m, s); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /code/exceptions/TestAskingForDate.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.util.Date; 3 | 4 | /** 5 | * Class for testing the use of objects of the class AskingForDate. 6 | * 7 | * @author Jon Ander Gómez (jon@dsic.upv.es) 8 | * @version 1.0 (March 2012) 9 | */ 10 | public class TestAskingForDate 11 | { 12 | /** friendly class variable for reading data from standard input */ 13 | static Scanner input = new Scanner(System.in); 14 | 15 | /** 16 | * main() method for testing the use of objects of other classes. 17 | * 18 | * @param args Array of objects of class String with the list of 19 | * command line arguments. 20 | */ 21 | public static void main(String [] args) 22 | { 23 | AskingForDate afd = new AskingForDate(input); 24 | 25 | Date d = afd.readDate("Birth date"); 26 | 27 | System.out.println("You were born " + d.toString()); 28 | } 29 | } -------------------------------------------------------------------------------- /code/exceptions/ExceptionHandling2.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class ExceptionHandling2 4 | { 5 | static Scanner input = new Scanner(System.in); 6 | public static void main(String [] args) 7 | { 8 | int [] A = { 6, 7, 8, 9, 10, 11, 1, 3, 2, 4 }; 9 | boolean valueOK; 10 | int index = 0; 11 | do { 12 | valueOK = true; 13 | try { 14 | System.out.print("Position in the array? "); 15 | index = input.nextInt(); 16 | showValue(A, index); 17 | } 18 | catch (ArrayIndexOutOfBoundsException aioobe) { 19 | System.out.printf("ERROR: %d is not a valid index!\n", index); 20 | valueOK = false; 21 | } 22 | } while (! valueOK); 23 | } 24 | public static void showValue(int [] A, int i) 25 | throws ArrayIndexOutOfBoundsException 26 | { 27 | System.out.println(A[i]); 28 | } 29 | } -------------------------------------------------------------------------------- /code/conditionals/TestingEquals.java: -------------------------------------------------------------------------------- 1 | 2 | public class TestingEquals 3 | { 4 | public static void main(String [] args) 5 | { 6 | String s1 = "Hello"; 7 | String s2 = new String("Hello"); 8 | String s3 = "Hello"; //s1; 9 | 10 | test_equality(s1, s2); 11 | test_equality(s1, s3); 12 | test_equality(s2, s3); 13 | test_equality_2(s1, s2); 14 | test_equality_2(s1, s3); 15 | test_equality_2(s2, s3); 16 | } 17 | public static void test_equality(String a, String b) 18 | { 19 | if (a == b) 20 | System.out.println(a + " is equal to " + b); 21 | else 22 | System.out.println(a + " is NOT equal to " + b); 23 | } 24 | public static void test_equality_2(String a, String b) 25 | { 26 | if (a.equals(b)) 27 | System.out.println(a + " is equal to " + b); 28 | else 29 | System.out.println(a + " is NOT equal to " + b); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /code/exams_from_previous_years/GameManager.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | import java.io.*; 4 | 5 | 6 | public class GameManager 7 | { 8 | public static void main(String [] args) 9 | { 10 | TimeInstant t = new TimeInstant(); 11 | 12 | SaveGame sg = new SaveGame("SCES", 50760, 1, t); 13 | 14 | System.out.println(sg.toHHMM()); 15 | 16 | System.out.println(t.toString()); 17 | 18 | // System.out.println(t.toString().compareTo(sg.toHHMM())); 19 | 20 | int rc = t.toString().compareTo(sg.toHHMM()); 21 | 22 | if (rc == 0) { 23 | System.out.printf("Both strings are equal! %s and %s\n", sg.toHHMM(), t.toString()); 24 | } else if (rc < 0) { 25 | System.out.printf("The strings are NOT equal! %s goes before %s\n", t.toString(), sg.toHHMM()); 26 | } else { 27 | System.out.printf("The strings are NOT equal! %s goes after %s\n", t.toString(), sg.toHHMM()); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /code/exceptions/ExceptionHandling.java: -------------------------------------------------------------------------------- 1 | import java.io.IOException; 2 | import java.util.InputMismatchException; 3 | import java.util.Scanner; 4 | 5 | public class ExceptionHandling 6 | { 7 | static Scanner input = new Scanner(System.in); 8 | 9 | public static void main(String [] args) 10 | { 11 | try { 12 | int minutes = getMinutes(); 13 | } 14 | catch (InputMismatchException ime) { /* Here the code. */ } 15 | catch (IOException ioe) { /* Here the code. */ } 16 | catch (Exception e) { /* Here the code. */ } 17 | finally { /* Code that will be executed always. */ } 18 | } 19 | public static int getMinutes() 20 | throws InputMismatchException, IOException 21 | { 22 | System.out.print("Minutes? "); 23 | int minutes = input.nextInt(); 24 | if (minutes < 0 || minutes >= 60) 25 | throw new InputMismatchException("Minutes out of range!"); 26 | 27 | return minutes; 28 | } 29 | } -------------------------------------------------------------------------------- /code/inheritance/NewStudent.java: -------------------------------------------------------------------------------- 1 | public class NewStudent extends Student { 2 | private float averageMark; 3 | 4 | public NewStudent(String name, int age, float averageMark) { 5 | super(name, age); 6 | this.averageMark = averageMark; 7 | } 8 | 9 | @Override 10 | public String toString() { 11 | // Typical and common reuse of the toString() method of the parent class 12 | // return super.toString() + " averageMark: " + averageMark; 13 | 14 | // Martingale to use a equivalent static toString() method from 15 | // the grant-parent class 16 | return Person.toString(this) + " averageMark: " + averageMark; 17 | 18 | // Useless martingale to use the toString() method from the 19 | // grant-parent class. This generates a stack overflow because 20 | // invoking the toString() this way is a inconditional recursive call 21 | // return ((Person)this).toString() + " averageMark: " + averageMark; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /code/basic/CheckingExpressions.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class CheckingExpressions 4 | { 5 | private static Scanner input = new Scanner(System.in).useLocale(Locale.US); 6 | public static void main(String [] args) 7 | { 8 | int a, b; 9 | 10 | System.out.print("\n enter a value for A: "); 11 | a = input.nextInt(); 12 | System.out.print("\n enter a value for B: "); 13 | b = input.nextInt(); 14 | 15 | int quotient = a / b; 16 | int remainder = a % b; 17 | boolean z = (a / b) * b + (a % b) == a; 18 | 19 | System.out.println(); 20 | System.out.println("quotient is " + quotient); 21 | System.out.println("remainder is " + remainder); 22 | System.out.println("quotient * b is " + (quotient * b)); 23 | System.out.println(); 24 | System.out.printf("(%d/%d)*%d + (%d%%%d) == %d --> %s\n\n", 25 | a, b, b, a, b, a, 26 | z ? "true" : "false"); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /code/basic/UserInteraction1.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class UserInteraction1 4 | { 5 | // This is to create a wrapper to interact with the standard input 6 | // by means of an object of the class Scanner we will study later. 7 | static Scanner input = new Scanner(System.in).useLocale(Locale.US); 8 | 9 | public static void main(String [] args) 10 | { 11 | String name, lastName, email; 12 | 13 | System.out.print("\n Please enter your name: "); 14 | name = input.nextLine(); 15 | 16 | System.out.print("\n Please enter your last name: "); 17 | lastName = input.nextLine(); 18 | 19 | System.out.print("\n Please enter your email address: "); 20 | email = input.nextLine(); 21 | 22 | 23 | System.out.println(); 24 | System.out.println(); 25 | System.out.println("Hello Mr/Ms/Mrs " + name 26 | + " " + lastName + " your email is " + email); 27 | System.out.println(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /code/files/TestScanner.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.Scanner; 3 | 4 | public class TestScanner 5 | { 6 | public static void main(String [] args) 7 | { 8 | System.out.println(); 9 | System.out.println(" We are going to read three integers and a text line."); 10 | System.out.println(); 11 | 12 | Scanner scanner = null; 13 | 14 | try{ 15 | scanner = new Scanner(new File("things.txt")); 16 | } 17 | catch (FileNotFoundException ex) { 18 | System.err.println("File doesn’t exist. " + ex.getMessage()); 19 | System.exit(0); 20 | } 21 | 22 | int n1 = scanner.nextInt(); 23 | int n2 = scanner.nextInt(); 24 | int n3 = scanner.nextInt(); 25 | scanner.nextLine(); 26 | 27 | String line = scanner.nextLine(); 28 | 29 | System.out.println("Numbers are: " + n1 + ", " + n2 + ", " + n3); 30 | System.out.println("Line is: " + line); 31 | scanner.close(); 32 | } 33 | } -------------------------------------------------------------------------------- /code/misc/p1.s: -------------------------------------------------------------------------------- 1 | .file "p1.c" 2 | .text 3 | .globl pow1 4 | .type pow1, @function 5 | pow1: 6 | .LFB0: 7 | .cfi_startproc 8 | endbr64 9 | pushq %rbp 10 | .cfi_def_cfa_offset 16 11 | .cfi_offset 6, -16 12 | movq %rsp, %rbp 13 | .cfi_def_cfa_register 6 14 | movl %edi, -20(%rbp) 15 | movl %esi, -24(%rbp) 16 | movl $1, -8(%rbp) 17 | movl $1, -4(%rbp) 18 | jmp .L2 19 | .L3: 20 | movl -8(%rbp), %eax 21 | imull -20(%rbp), %eax 22 | movl %eax, -8(%rbp) 23 | addl $1, -4(%rbp) 24 | .L2: 25 | movl -4(%rbp), %eax 26 | cmpl -24(%rbp), %eax 27 | jle .L3 28 | movl -8(%rbp), %eax 29 | popq %rbp 30 | .cfi_def_cfa 7, 8 31 | ret 32 | .cfi_endproc 33 | .LFE0: 34 | .size pow1, .-pow1 35 | .ident "GCC: (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0" 36 | .section .note.GNU-stack,"",@progbits 37 | .section .note.gnu.property,"a" 38 | .align 8 39 | .long 1f - 0f 40 | .long 4f - 1f 41 | .long 5 42 | 0: 43 | .string "GNU" 44 | 1: 45 | .align 8 46 | .long 0xc0000002 47 | .long 3f - 2f 48 | 2: 49 | .long 0x3 50 | 3: 51 | .align 8 52 | 4: 53 | -------------------------------------------------------------------------------- /code/misc/p2.s: -------------------------------------------------------------------------------- 1 | .file "p2.c" 2 | .text 3 | .globl pow2 4 | .type pow2, @function 5 | pow2: 6 | .LFB0: 7 | .cfi_startproc 8 | endbr64 9 | pushq %rbp 10 | .cfi_def_cfa_offset 16 11 | .cfi_offset 6, -16 12 | movq %rsp, %rbp 13 | .cfi_def_cfa_register 6 14 | movl %edi, -20(%rbp) 15 | movl %esi, -24(%rbp) 16 | movl $1, -8(%rbp) 17 | movl $1, -4(%rbp) 18 | jmp .L2 19 | .L3: 20 | movl -8(%rbp), %eax 21 | imull -20(%rbp), %eax 22 | movl %eax, -8(%rbp) 23 | addl $1, -4(%rbp) 24 | .L2: 25 | movl -4(%rbp), %eax 26 | cmpl -24(%rbp), %eax 27 | jle .L3 28 | movl -8(%rbp), %eax 29 | popq %rbp 30 | .cfi_def_cfa 7, 8 31 | ret 32 | .cfi_endproc 33 | .LFE0: 34 | .size pow2, .-pow2 35 | .ident "GCC: (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0" 36 | .section .note.GNU-stack,"",@progbits 37 | .section .note.gnu.property,"a" 38 | .align 8 39 | .long 1f - 0f 40 | .long 4f - 1f 41 | .long 5 42 | 0: 43 | .string "GNU" 44 | 1: 45 | .align 8 46 | .long 0xc0000002 47 | .long 3f - 2f 48 | 2: 49 | .long 0x3 50 | 3: 51 | .align 8 52 | 4: 53 | -------------------------------------------------------------------------------- /code/basic/DataTypeConversions.java: -------------------------------------------------------------------------------- 1 | public class DataTypeConversions 2 | { 3 | public static void main(String [] args) 4 | { 5 | long x, y, z; 6 | int j = 55, k, i, num = 6, den = 10; 7 | float f; 8 | double d = 123.67, q; 9 | 10 | x = 98; System.out.println("x = " + x); 11 | y = j; System.out.println("y = " + y); 12 | z = 9 * j; System.out.println("z = " + z); 13 | k = (int) 55L; System.out.println("k = " + k); 14 | j = (int) y; System.out.println("j = " + j); 15 | i = (int) d; System.out.println("i = " + i); 16 | f = (float) d; System.out.println("f = " + f); 17 | d = 3.40282347e+50; System.out.println("d = " + d); 18 | f = (float) d; System.out.println("f = " + f); 19 | q = num / den; System.out.println("q = " + q); 20 | q = (double)num / den; System.out.println("q = " + q); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /cpr/java/fsa/TestPrefixAcceptor.java: -------------------------------------------------------------------------------- 1 | package es.upv.etsinf.fsa; 2 | 3 | import java.util.*; 4 | 5 | public class TestPrefixAcceptor 6 | { 7 | public static void main(String [] args) 8 | { 9 | PrefixAcceptor pa1 = new PrefixAcceptor(); 10 | pa1.add("aa"); 11 | pa1.add("aaa"); 12 | pa1.add("aaaa"); 13 | pa1.compile(); 14 | 15 | System.out.println(); 16 | pa1.processText("aaaaaaaaaa"); 17 | pa1.printResults(); 18 | 19 | PrefixAcceptor pa2 = new PrefixAcceptor(); 20 | pa2.add("aab"); 21 | pa2.add("aabaab"); 22 | pa2.compile(); 23 | 24 | System.out.println(); 25 | pa2.processText("aabaabaabaab"); 26 | pa2.printResults(); 27 | 28 | PrefixAcceptor pa3 = new PrefixAcceptor(); 29 | pa3.add("ver"); 30 | pa3.add("server"); 31 | pa3.compile(); 32 | 33 | System.out.println(); 34 | pa3.processText("verserver"); 35 | pa3.printResults(); 36 | 37 | System.out.println(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /code/exams_from_previous_years/PolygonalNumbers.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | 4 | 5 | public class PolygonalNumbers 6 | { 7 | private static Scanner input = new Scanner(System.in).useLocale(Locale.US); 8 | 9 | 10 | public static void main(String [] args) 11 | { 12 | System.out.println(check(15, 3)); 13 | System.out.println(check(19, 3)); 14 | } 15 | 16 | public static boolean check(int k, int s) 17 | { 18 | int i = 1; 19 | int n; 20 | 21 | do { 22 | n = i * ((s - 2) * i - (s - 4)) / 2; 23 | i++; 24 | } while (n < k); 25 | 26 | return k == n; 27 | } 28 | 29 | 30 | public static int [] countValues(int [] edges, double [] values) 31 | { 32 | int [] counters = new int [edges.length]; 33 | 34 | for (int i = 0; i < edges.length; i++) { 35 | 36 | for (int j = 0; j < values.length; j++) { 37 | 38 | if (values[j] < edges[i]) counters[i]++; 39 | } 40 | } 41 | 42 | return counters; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /code/loops/N100.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | class N100 4 | { 5 | public static void main(String [] args) 6 | { 7 | Scanner input = new Scanner(System.in); 8 | int i, j; 9 | 10 | while (input.hasNext()) { 11 | i = input.nextInt(); 12 | j = input.nextInt(); 13 | 14 | long l = cycle_length(Math.min(i, j), Math.max(i, j)); 15 | 16 | System.out.printf("%d %d %d\n", i, j, l); 17 | } 18 | } 19 | public static long cycle_length(int a, int b) 20 | { 21 | long max_length = 0; 22 | 23 | for (int n = a; n <= b; n++) { 24 | long l = cycle(n); 25 | max_length = Math.max(l, max_length); 26 | } 27 | return max_length; 28 | } 29 | public static long cycle(int n) 30 | { 31 | int counter = 1; 32 | 33 | while (n != 1) { 34 | 35 | ++counter; 36 | 37 | if (n % 2 == 0) 38 | n /= 2; 39 | else 40 | n = 3 * n + 1; 41 | } 42 | 43 | return counter; 44 | } 45 | } -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | 2 | MIT License 3 | 4 | Copyright (c) 2019 The authors. 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy 7 | of this software and associated documentation files (the "Software"), to deal 8 | in the Software without restriction, including without limitation the rights 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the Software is 11 | furnished to do so, subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in all 14 | copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | SOFTWARE. 23 | -------------------------------------------------------------------------------- /code/conditionals/Grades1b.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Grades1b 4 | { 5 | public static void main(String [] args) 6 | { 7 | Scanner input = new Scanner(System.in).useLocale(Locale.US); 8 | double grade; 9 | 10 | System.out.print("\n\nPlease, enter you grade: " ); 11 | grade = input.nextDouble(); 12 | System.out.println(); 13 | 14 | if (grade < 0.0 || grade > 10.0) { 15 | System.out.println("Invalid grade: " + grade); 16 | } else if (grade == 10.0) { 17 | System.out.println("Honor Mention"); 18 | } else if (/* 10 > grade && */ grade >= 9.0) { 19 | System.out.println("Excellent"); 20 | } else if (/* 9 > grade && */ grade >= 7.0) { 21 | System.out.println("Notable"); 22 | } else if (/* 7 > grade && */grade >= 6.0) { 23 | System.out.println("Good"); 24 | } else if (/* 6 > grade && */grade >= 5.0) { 25 | System.out.println("Passed"); 26 | } else if (/* 5 > grade && */grade >= 3.0) { 27 | System.out.println("Failed"); 28 | } else { //if (/* 3 > grade && */grade >= 0.0) { 29 | System.out.println("Mega Failed"); 30 | } 31 | 32 | System.out.println(); 33 | System.out.println(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /examples/agenda2/agenda.bak: -------------------------------------------------------------------------------- 1 | 10 2 | Adderley 3 | Cannonball 4 | cannonball@bluenote.com 5 | 123456789 6 | 1028 09 15 7 | Armstrong 8 | Louis 9 | louis@bluenote.com 10 | 123456789 11 | 1901 08 04 12 | Chambers 13 | Paul L.D. 14 | chambers@bluenote.com 15 | 123456789 16 | 1935 04 22 17 | Coltrane 18 | John 19 | john.coltrane@bluenote.com 20 | 123456789 21 | 1926 09 23 22 | Davis 23 | Miles 24 | miles.davis@bluenote.com 25 | 123456789 26 | 1926 05 28 27 | Ellington 28 | Edward Kennedy 29 | duke@bluenote.com 30 | 123456789 31 | 1899 04 29 32 | Evans 33 | Willian John 34 | bill.evans@bluenote.com 35 | 123456789 36 | 1929 08 16 37 | Monk 38 | Thelonious S. 39 | t.s.monk@bluenote.com 40 | 123456789 41 | 1917 10 10 42 | Parker 43 | Charlie Christopher 44 | bird@bluenote.com 45 | 123456789 46 | 1920 08 29 47 | Pettiford 48 | Oscar 49 | pettiford@bluenote.com 50 | 123456789 51 | 1922 09 30 52 | #### 53 | 3 54 | Jazz concert 55 | Jimmy Glass 56 | 2019-10-11 22:00:00 57 | 2019-10-11 23:59:59 58 | 67 59 | Jazz concert 60 | Jimmy Glass 61 | 2019-12-04 22:00:00 62 | 2019-12-04 23:59:59 63 | 43 64 | Jazz concert 65 | Jimmy Glass 66 | 2021-02-14 20:00:00 67 | 2021-02-14 22:00:00 68 | 1 69 | -------------------------------------------------------------------------------- /examples/agenda3/agenda.bak: -------------------------------------------------------------------------------- 1 | 10 2 | Adderley 3 | Cannonball 4 | cannonball@bluenote.com 5 | 123456789 6 | 1028 09 15 7 | Armstrong 8 | Louis 9 | louis@bluenote.com 10 | 123456789 11 | 1901 08 04 12 | Chambers 13 | Paul L.D. 14 | chambers@bluenote.com 15 | 123456789 16 | 1935 04 22 17 | Coltrane 18 | John 19 | john.coltrane@bluenote.com 20 | 123456789 21 | 1926 09 23 22 | Davis 23 | Miles 24 | miles.davis@bluenote.com 25 | 123456789 26 | 1926 05 28 27 | Ellington 28 | Edward Kennedy 29 | duke@bluenote.com 30 | 123456789 31 | 1899 04 29 32 | Evans 33 | Willian John 34 | bill.evans@bluenote.com 35 | 123456789 36 | 1929 08 16 37 | Monk 38 | Thelonious S. 39 | t.s.monk@bluenote.com 40 | 123456789 41 | 1917 10 10 42 | Parker 43 | Charlie Christopher 44 | bird@bluenote.com 45 | 123456789 46 | 1920 08 29 47 | Pettiford 48 | Oscar 49 | pettiford@bluenote.com 50 | 123456789 51 | 1922 09 30 52 | #### 53 | 3 54 | Jazz concert 55 | Jimmy Glass 56 | 2019-10-11 22:00:00 57 | 2019-10-11 23:59:59 58 | 67 59 | Jazz concert 60 | Jimmy Glass 61 | 2019-12-04 22:00:00 62 | 2019-12-04 23:59:59 63 | 43 64 | Jazz concert 65 | Jimmy Glass 66 | 2021-02-14 20:00:00 67 | 2021-02-14 22:00:00 68 | 1 69 | -------------------------------------------------------------------------------- /code/arrays/Palindrome.java: -------------------------------------------------------------------------------- 1 | 2 | public class Palindrome 3 | { 4 | public static boolean palindrome(String s) 5 | { 6 | char [] v = s.toCharArray(); 7 | int n = v.length; 8 | 9 | for (int i = 0; i < n; /* i++ */) { 10 | if (v[i] == ' ') { 11 | n--; 12 | for (int j = i; j < n; j++) v[j] = v[j + 1]; 13 | } else { 14 | i++; 15 | } 16 | } 17 | 18 | int left = 0, right = n - 1; 19 | 20 | while (left < right && v[left] == v[right]) { 21 | left++; 22 | right--; 23 | } 24 | 25 | return left >= right; 26 | } 27 | 28 | public static void main(String [] args) 29 | { 30 | String s1 = "dabale arroz a la zorra el abad"; 31 | String s2 = "dabale arroz a la zorra el abad"; 32 | 33 | System.out.println(); 34 | System.out.printf("|%s| %s palindrome\n", s1, palindrome(s1) ? "is" : "is not"); 35 | System.out.println(); 36 | System.out.printf("|%s| %s palindrome\n", s2, palindrome(s2) ? "is" : "is not"); 37 | System.out.println(); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /code/files/TestBinaryReading.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | import java.io.*; 4 | 5 | public class TestBinaryReading 6 | { 7 | public static void main(String [] args) 8 | { 9 | try { 10 | 11 | File file = new File("file-for-testing-1.dat"); 12 | FileInputStream fis = new FileInputStream(file); 13 | BufferedInputStream bis = new BufferedInputStream(fis); 14 | ObjectInputStream ois = new ObjectInputStream(bis); 15 | 16 | String str = ois.readUTF(); 17 | int year = ois.readInt(); 18 | double deficit = ois.readDouble(); 19 | 20 | ois.close(); 21 | 22 | System.out.println(str); 23 | System.out.printf("The spanish deficit for %d is %f\n", year, deficit); 24 | } 25 | catch (IOException e) 26 | { 27 | System.err.println("Derived from IOException."); 28 | e.printStackTrace(System.err); 29 | } 30 | catch (Exception e) 31 | { 32 | System.err.println("Derived from Exception."); 33 | e.printStackTrace(System.err); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /code/conditionals/Grades1.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Grades1 4 | { 5 | private static Scanner input = new Scanner(System.in).useLocale(Locale.US); 6 | 7 | public static void main(String [] args) 8 | { 9 | System.out.print("\n\n Enter your grade: "); 10 | double grade = input.nextDouble(); 11 | 12 | if (0.0 <= grade && grade < 3.0) { 13 | System.out.println("\nGo home and never come back here!"); 14 | } else if (3.0 <= grade && grade < 4.0) { 15 | System.out.println("\nSee you next year!"); 16 | } else if (4.0 <= grade && grade < 5.0) { 17 | System.out.println("\nI will give you another opportunity!"); 18 | } else if (5.0 <= grade && grade < 7.0) { 19 | System.out.println("\nPassed!"); 20 | } else if (7.0 <= grade && grade < 9.0) { 21 | System.out.println("\nB"); 22 | } else if (9.0 <= grade && grade < 10.0) { 23 | System.out.println("\nA"); 24 | } else if (grade == 10.0) { 25 | System.out.println("\nExcellent!"); 26 | } else { 27 | System.out.println("\nThe grade is not a valid value!"); 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /code/loops/EuclidesGCD.java: -------------------------------------------------------------------------------- 1 | import java.util.Random; 2 | 3 | public class EuclidesGCD 4 | { 5 | public static void main(String [] args) 6 | { 7 | Random r = new Random(); 8 | boolean verbose = false; 9 | 10 | // Loop initialization begins 11 | int a = r.nextInt(100000000); 12 | int b = r.nextInt(100000000); 13 | // Loop initialization ends 14 | 15 | System.out.printf("gcd(%d, %d)= ", a, b); 16 | 17 | if (verbose) System.out.printf("\n B -- a = %15d b = %15d\n", a, b); 18 | 19 | //while (a != b && a != 0 && b != 0) // Loop guard 20 | while (a != 0 && b != 0) { // Loop guard 21 | // Loop body begins 22 | if (a > b) { 23 | a = a % b; 24 | } else { 25 | b = b % a; 26 | } 27 | if (verbose) System.out.printf(" I -- a = %15d b = %15d\n", a, b); 28 | // Loop body ends 29 | } 30 | if (verbose) System.out.printf(" A -- a = %15d b = %15d\n", a, b); 31 | 32 | if (a == 0 && b == 0) 33 | System.out.println(1); 34 | else 35 | System.out.println((a == 0) ? b : a); 36 | } 37 | } -------------------------------------------------------------------------------- /examples/agenda2/agenda.txt: -------------------------------------------------------------------------------- 1 | 11 2 | Adderley 3 | Cannonball 4 | cannonball@bluenote.com 5 | 123456789 6 | 1928 09 15 7 | Armstrong 8 | Louis 9 | louis@bluenote.com 10 | 123456789 11 | 1901 08 04 12 | Chambers 13 | Paul L.D. 14 | chambers@bluenote.com 15 | 123456789 16 | 1935 04 22 17 | Coltrane 18 | John 19 | john.coltrane@bluenote.com 20 | 123456789 21 | 1926 09 23 22 | Davis 23 | Miles 24 | miles.davis@bluenote.com 25 | 123456789 26 | 1926 05 28 27 | Ellington 28 | Edward Kennedy 29 | duke@bluenote.com 30 | 123456789 31 | 1899 04 29 32 | Evans 33 | Willian John 34 | bill.evans@bluenote.com 35 | 123456789 36 | 1929 08 16 37 | Monk 38 | Thelonious S. 39 | t.s.monk@bluenote.com 40 | 123456789 41 | 1917 10 10 42 | Morin 43 | Edgar 44 | emorin@cess.fr 45 | 842348234 46 | 1921 07 08 47 | Parker 48 | Charlie Christopher 49 | bird@bluenote.com 50 | 123456789 51 | 1920 08 29 52 | Pettiford 53 | Oscar 54 | pettiford@bluenote.com 55 | 123456789 56 | 1922 09 30 57 | #### 58 | 3 59 | Jazz concert 60 | Jimmy Glass 61 | 2019-10-11 22:00:00 62 | 2019-10-11 23:59:00 63 | 67 64 | Jazz concert 65 | Jimmy Glass 66 | 2019-12-04 22:00:00 67 | 2019-12-04 23:59:00 68 | 43 69 | Jazz concert 70 | Jimmy Glass 71 | 2021-02-14 20:00:00 72 | 2021-02-14 22:00:00 73 | 1 74 | -------------------------------------------------------------------------------- /code/recursion/GreatestCommonDivisor.java: -------------------------------------------------------------------------------- 1 | 2 | public class GreatestCommonDivisor 3 | { 4 | public static void main(String [] args) 5 | { 6 | int a = 71, b = 9; 7 | 8 | for (int i = 0; i < args.length; i++) { 9 | if (args[i].equals("-a")) 10 | a = Integer.parseInt(args[i+1]); 11 | else if (args[i].equals("-b")) 12 | b = Integer.parseInt(args[i+1]); 13 | } 14 | 15 | int g = gcd(a, b); 16 | System.out.printf("gcd(%d, %d) = %d\n", a, b, g); 17 | } 18 | 19 | /* 20 | gcd(a,b) = a if b == 0 21 | gcd(a,b) = b if a == 0 22 | gcd(a,b) = a if a == b 23 | gdc(a,b) = gcd(a % b, b) if a > b 24 | gdc(a,b) = gcd(a, b % a) if a < b 25 | 26 | the original Euclide's algorithm also returns x and y 27 | such that a * x + b * y = gcd(a, b) 28 | */ 29 | private static int gcd(int a, int b) 30 | { 31 | System.out.printf("gcd(): a = %d b = %d\n", a, b); 32 | 33 | if (b == 0) return a; 34 | else if (a == 0) return b; 35 | else if (a == b) return a; 36 | else if (a > b) return gcd(a % b, b); 37 | else return gcd(a, b %a); 38 | } 39 | } -------------------------------------------------------------------------------- /cpr/java/Vertex.java: -------------------------------------------------------------------------------- 1 | 2 | package es.upv.etsinf.graphs; 3 | 4 | import java.util.Vector; 5 | 6 | public class Vertex 7 | { 8 | protected int id; // Used as index inside the graph. 9 | protected String label; 10 | protected Vector edges; 11 | protected int inDegree; 12 | 13 | public Vertex(int id, String label) 14 | { 15 | this.id = id; 16 | this.label = label; 17 | this.edges = new Vector(); 18 | this.inDegree = 0; 19 | } 20 | 21 | public int getId() { return id; } 22 | public String getLabel() { return label; } 23 | 24 | public void setId(int id) { this.id = id; } 25 | 26 | public Edge getEdge(int i) { return edges.get(i); } 27 | 28 | public Vector getEdges() { return edges; } 29 | 30 | public void add(Edge e) 31 | { 32 | edges.add(e); 33 | e.getDestination().incrInDegree(); 34 | } 35 | 36 | public void incrInDegree() { inDegree++; } 37 | 38 | public int getOutDegree() { return edges.size(); } 39 | public int getInDegree() { return inDegree; } 40 | 41 | public String toString() 42 | { 43 | return String.format("(%d) <%s>", id, label != null ? label : "" ); 44 | } 45 | } -------------------------------------------------------------------------------- /examples/agenda3/agenda.txt: -------------------------------------------------------------------------------- 1 | 10 2 | Adderley 3 | Cannonball 4 | cannonball@bluenote.com 5 | 123456789 6 | 1928 09 15 7 | Armstrong 8 | Louis 9 | louis@bluenote.com 10 | 123456789 11 | 1901 08 04 12 | Chambers 13 | Paul L.D. 14 | chambers@bluenote.com 15 | 123456789 16 | 1935 04 22 17 | Coltrane 18 | John 19 | john.coltrane@bluenote.com 20 | 123456789 21 | 1926 09 23 22 | Davis 23 | Miles 24 | miles.davis@bluenote.com 25 | 123456789 26 | 1926 05 28 27 | Ellington 28 | Edward Kennedy 29 | duke@bluenote.com 30 | 123456789 31 | 1899 04 29 32 | Evans 33 | Willian John 34 | bill.evans@bluenote.com 35 | 123456789 36 | 1929 08 16 37 | Monk 38 | Thelonious S. 39 | t.s.monk@bluenote.com 40 | 123456789 41 | 1917 10 10 42 | Parker 43 | Charlie Christopher 44 | bird@bluenote.com 45 | 123456789 46 | 1920 08 29 47 | Pettiford 48 | Oscar 49 | pettiford@bluenote.com 50 | 123456789 51 | 1922 09 30 52 | #### 53 | 4 54 | Jazz concert 55 | Jimmy Glass 56 | 2019-10-11 22:00:00 57 | 2019-10-11 23:59:59 58 | 67 59 | Jazz concert 60 | Jimmy Glass 61 | 2019-12-04 22:00:00 62 | 2019-12-04 23:59:59 63 | 43 64 | Jazz concert 65 | Jimmy Glass 66 | 2021-02-14 20:00:00 67 | 2021-02-14 22:00:00 68 | 1 69 | Reopening Jazz Concert 70 | Jimmy Glass 71 | 2021-06-10 20:00:00 72 | 2021-06-10 23:00:00 73 | 1 74 | -------------------------------------------------------------------------------- /code/conditionals/Grades2.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Grades2 4 | { 5 | private static Scanner input = new Scanner(System.in).useLocale(Locale.US); 6 | 7 | public static void main(String [] args) 8 | { 9 | System.out.print("\n\n Enter your grade: "); 10 | double grade = input.nextDouble(); 11 | 12 | if (grade < 0.0 || grade > 10.0) { 13 | System.out.println("\nThe grade is not a valid value!"); 14 | } else if (/* 0.0 <= grade && */ grade < 3.0) { 15 | System.out.println("\nGo home and never come back here!"); 16 | } else if (/* 3.0 <= grade && */ grade < 4.0) { 17 | System.out.println("\nSee you next year!"); 18 | } else if (/* 4.0 <= grade && */ grade < 5.0) { 19 | System.out.println("\nI will give you another opportunity!"); 20 | } else if (/* 5.0 <= grade && */ grade < 7.0) { 21 | System.out.println("\nPassed!"); 22 | } else if (/* 7.0 <= grade && */ grade < 9.0) { 23 | System.out.println("\nB"); 24 | } else if (/* 9.0 <= grade && */ grade < 10.0) { 25 | System.out.println("\nA"); 26 | } else if (grade == 10.0) { 27 | System.out.println("\nExcellent!"); 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /code/recursion/Quotient.java: -------------------------------------------------------------------------------- 1 | 2 | public class Quotient 3 | { 4 | public static void main(String [] args) 5 | { 6 | int a = 71, b = 9; 7 | 8 | for (int i = 0; i < args.length; i++) { 9 | if (args[i].equals("-a")) 10 | a = Integer.parseInt(args[i+1]); 11 | else if (args[i].equals("-b")) 12 | b = Integer.parseInt(args[i+1]); 13 | } 14 | 15 | int q = quotient(a, b); 16 | System.out.printf("integer quotient of %d / %d is %d\n", a, b, q); 17 | 18 | int p = product(a, b); 19 | System.out.printf("product of %d * %d is %d\n", a, b, p); 20 | } 21 | 22 | /* precondition: a >= 0 and b > 0 23 | 24 | if a < b : return 0 25 | if a >= b : return quotient(a - b, b) + 1 26 | */ 27 | private static int quotient(int a, int b) 28 | { 29 | if (a < b) 30 | return 0; 31 | else 32 | return 1 + quotient(a - b, b); 33 | } 34 | 35 | /* 36 | a*b = 0 if b == 0 37 | a*b = a * (b-1) + a if b > 0 38 | */ 39 | private static int product(int a, int b) 40 | { 41 | if (b == 0) 42 | return 0; 43 | else 44 | return a + product(a, b - 1); 45 | } 46 | } -------------------------------------------------------------------------------- /code/conditionals/Plane.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Plane 4 | { 5 | private static Scanner input = new Scanner(System.in).useLocale(Locale.US); 6 | 7 | public static void main(String [] args) 8 | { 9 | double x, y; 10 | 11 | System.out.print("\n x: "); x = input.nextDouble(); 12 | System.out.print("\n y: "); y = input.nextDouble(); 13 | 14 | if (y > 0.0) { 15 | if (x > 0.0) { 16 | System.out.println("First quadrant."); 17 | } else if (x < 0.0) { 18 | System.out.println("Second quadrant."); 19 | } else { // x == 0.0 20 | System.out.println("Y axis."); 21 | } 22 | } else if (y < 0.0) { 23 | if (x > 0.0) { 24 | System.out.println("Fourth quadrant."); 25 | } else if (x < 0.0) { 26 | System.out.println("Third quadrant."); 27 | } else { // x == 0.0 28 | System.out.println("Y axis."); 29 | } 30 | } else { // y == 0.0 31 | if (x == 0.0) { 32 | System.out.println("Origin of coordinates."); 33 | } else { 34 | System.out.println("X axis."); 35 | } 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /code/basic/CheckingExpressionsWithFloats.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class CheckingExpressionsWithFloats 4 | { 5 | private static Scanner input = new Scanner(System.in).useLocale(Locale.US); 6 | public static void main(String [] args) 7 | { 8 | float a, b; 9 | 10 | System.out.print("\n enter a value for A: "); 11 | a = input.nextFloat(); 12 | System.out.print("\n enter a value for B: "); 13 | b = input.nextFloat(); 14 | 15 | float quotient = (int)(a / b); 16 | float remainder = a % b; 17 | //boolean z = (a / b) * b + (a % b) == a; 18 | boolean z = (int)(a / b) * b + (a % b) == a; 19 | 20 | System.out.println(); 21 | System.out.println("quotient is " + quotient); 22 | System.out.println("remainder is " + remainder); 23 | System.out.println("quotient * b is " + (quotient * b)); 24 | System.out.println(); 25 | System.out.printf("(%f / %f) * %f + (%f %% %f) == %f --> %s\n\n", 26 | a, b, b, a, b, a, 27 | z ? "true" : "false"); 28 | 29 | 30 | float lhs = (int)(a / b) * b + (a % b); 31 | float rhs = a; 32 | 33 | System.out.printf("lhs: %30.20f\n", lhs); 34 | System.out.printf("rhs: %30.20f\n", rhs); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /code/linear-data-structures/src/TestQueues.java: -------------------------------------------------------------------------------- 1 | package linear; 2 | 3 | import java.util.*; 4 | 5 | /** 6 | * Class for testing queues of integers. 7 | * 8 | * @author Jon Ander Gómez 9 | * @version 2020-04-28 10 | */ 11 | public class TestQueues 12 | { 13 | public static void main(String [] args) 14 | throws Exception 15 | { 16 | Random r = new Random(); 17 | 18 | QueueIntArray qa = new QueueIntArray(); 19 | QueueIntLinked ql = new QueueIntLinked(); 20 | 21 | for (int i = 0; i < 10; i++) { 22 | int value = r.nextInt(100); 23 | qa.push(value); 24 | ql.push(value); 25 | } 26 | 27 | System.out.println("\n"); 28 | 29 | System.out.println(qa); 30 | System.out.println(ql); 31 | 32 | System.out.println("\n"); 33 | 34 | QueueIntArray qa2 = qa.clone(); 35 | QueueIntLinked ql2 = ql.clone(); 36 | 37 | System.out.println(qa2); 38 | System.out.println(ql2); 39 | 40 | System.out.println("\n"); 41 | 42 | System.out.printf("qa and qa2 %s equal\n", qa.equals(qa2) ? "are" : "are not"); 43 | System.out.printf("ql and ql2 %s equal\n", ql.equals(ql2) ? "are" : "are not"); 44 | 45 | System.out.println("\n"); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /code/linear-data-structures/src/TestStacks.java: -------------------------------------------------------------------------------- 1 | package linear; 2 | 3 | import java.util.*; 4 | 5 | /** 6 | * Class for testing stacks of integers. 7 | * 8 | * @author Jon Ander Gómez 9 | * @version 2020-04-28 10 | */ 11 | public class TestStacks 12 | { 13 | public static void main(String [] args) 14 | throws Exception 15 | { 16 | Random r = new Random(); 17 | 18 | StackIntArray sa = new StackIntArray(); 19 | StackIntLinked sl = new StackIntLinked(); 20 | 21 | for (int i = 0; i < 10; i++) { 22 | int value = r.nextInt(100); 23 | sa.push(value); 24 | sl.push(value); 25 | } 26 | 27 | System.out.println("\n"); 28 | 29 | System.out.println(sa); 30 | System.out.println(sl); 31 | 32 | System.out.println("\n"); 33 | 34 | StackIntArray sa2 = sa.clone(); 35 | StackIntLinked sl2 = sl.clone(); 36 | 37 | System.out.println(sa2); 38 | System.out.println(sl2); 39 | 40 | System.out.println("\n"); 41 | 42 | System.out.printf("sa and sa2 %s equal\n", sa.equals(sa2) ? "are" : "are not"); 43 | System.out.printf("sl and sl2 %s equal\n", sl.equals(sl2) ? "are" : "are not"); 44 | 45 | System.out.println("\n"); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /code/files/TestEOFException.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.NoSuchElementException; 3 | import java.util.Scanner; 4 | 5 | public class TestEOFException 6 | { 7 | public static void main(String [] args) 8 | { 9 | String filename = null; 10 | 11 | for (int i = 0; i < args.length; i++) { 12 | if (args[i].equals("--file")) { 13 | filename = args[i + 1]; 14 | } 15 | } 16 | 17 | if (filename != null) { 18 | Scanner sf = null; 19 | try { 20 | sf = new Scanner(new File(filename)); 21 | 22 | while (true) { 23 | String line = sf.nextLine(); //.trim(); 24 | System.out.println(line); 25 | } 26 | 27 | } 28 | // catch (EOFException e) 29 | catch (NoSuchElementException e) 30 | { 31 | System.out.println("*** The end-of-file was reached as expected. All is OK!"); 32 | } 33 | catch (FileNotFoundException e) 34 | { 35 | e.printStackTrace(System.err); 36 | } 37 | finally { 38 | if (sf != null) 39 | sf.close(); 40 | } 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /cpr/java/Point3D.java: -------------------------------------------------------------------------------- 1 | 2 | package es.upv.etsinf.geometry; 3 | 4 | public class Point3D extends Point2D 5 | { 6 | private double z; 7 | 8 | public Point3D( double x, double y, double z ) 9 | { 10 | super( x, y ); 11 | this.z = z; 12 | } 13 | 14 | public double getZ() { return z; } 15 | 16 | public double distanceFrom( Point3D other ) 17 | { 18 | double dx = this.getX() - other.getX(); 19 | double dy = this.getY() - other.getY(); 20 | double dz = this.z - other.z; 21 | 22 | return Math.sqrt( dx*dx + dy*dy + dz*dz ); 23 | } 24 | 25 | @Override 26 | public boolean equals( Object o ) 27 | { 28 | if ( o instanceof Point3D ) { 29 | Point3D other = (Point3D)o; 30 | 31 | return ( super.equals( other ) 32 | && Math.abs( this.z - other.z ) <= EPSILON ); 33 | 34 | } else { 35 | return false; 36 | } 37 | } 38 | 39 | @Override 40 | public Object clone() 41 | { 42 | Point3D p = new Point3D( this.getX(), this.getY(), this.z ); 43 | 44 | return p; 45 | } 46 | 47 | @Override 48 | public String toString() 49 | { 50 | return String.format( java.util.Locale.US, "(%.3f,%.3f,%.3f)", getX(), getY(), z ); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /code/files/TextWritingReadingIntegers.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.Scanner; 3 | 4 | class TextWritingReadingIntegers 5 | { 6 | public static void main(String [] args) 7 | { 8 | String fileName = "file1.txt"; 9 | try { 10 | //PrintWriter pw = new PrintWriter(new File(fileName)); 11 | PrintWriter pw = new PrintWriter( 12 | new BufferedOutputStream( 13 | new FileOutputStream( 14 | new File(fileName)))); 15 | 16 | for (int i = 0; i < 10 ; i++) pw.println(" " + i); 17 | 18 | pw.close(); 19 | 20 | //Scanner scanner = new Scanner(new File(fileName)); 21 | Scanner scanner = new Scanner( 22 | new BufferedInputStream( 23 | new FileInputStream( 24 | new File(fileName)))); 25 | 26 | while (scanner.hasNext()) { 27 | System.out.println("Read value: " + scanner.nextInt()); 28 | } 29 | scanner.close(); 30 | 31 | } 32 | catch (FileNotFoundException e) { 33 | System.err.println(" ERROR when opening file: " + fileName); 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /code/recursion/PascalTriangle2.java: -------------------------------------------------------------------------------- 1 | 2 | public class PascalTriangle2 3 | { 4 | private long [][] pascalTriangle; 5 | 6 | public PascalTriangle2(int max_row) 7 | { 8 | pascalTriangle = new long [max_row + 1][max_row + 1]; 9 | 10 | pascalTriangle[1][1] = 1; 11 | for (int row = 2; row <= max_row; row++) { 12 | pascalTriangle[row][1] = 1; 13 | pascalTriangle[row][row] = 1; 14 | for (int col = 2; col < row; col++) 15 | pascalTriangle[row][col] = pascalTriangle[row - 1][col - 1] 16 | + pascalTriangle[row - 1][col]; 17 | } 18 | } 19 | 20 | public long get(int row, int col) 21 | { 22 | return pascalTriangle[row][col]; 23 | } 24 | 25 | public static void main(String [] args) 26 | { 27 | int n = 6; 28 | 29 | for (int i = 0; i < args.length; i++) { 30 | if (args[i].equals("-n")) 31 | n = Integer.parseInt(args[i+1]); 32 | } 33 | 34 | PascalTriangle2 pt = new PascalTriangle2(n); 35 | 36 | for (int row = 1; row <= n; row++) { 37 | for (int col = 1; col <= row; col++) 38 | System.out.printf(" %5d", pt.get(row, col)); 39 | System.out.println(); 40 | } 41 | } 42 | } -------------------------------------------------------------------------------- /code/methods/Swap4.java: -------------------------------------------------------------------------------- 1 | public class Swap4 2 | { 3 | public static final String UNITS = "cm"; 4 | 5 | public static void swap(Point p1, Point p2) 6 | { 7 | double temp; 8 | 9 | temp = p1.getX(); 10 | p1.setX(p2.getX()); 11 | p2.setX(temp); 12 | 13 | temp = p1.getY(); 14 | p1.setY(p2.getY()); 15 | p2.setY(temp); 16 | } 17 | public static void main(String [] args) 18 | { 19 | Point p1 = new Point(4, 3); 20 | Point p2 = new Point(30, 40); 21 | String s; 22 | double d; 23 | 24 | s = p1.toString(); 25 | d = p1.distanceFromOrigin(); 26 | System.out.println(s + " is at a distance of " 27 | + d + " " + Swap4.UNITS 28 | + " from the origin."); 29 | s = p2.toString(); 30 | d = p2.distanceFromOrigin(); 31 | System.out.println(s + " is at a distance of " 32 | + d + " " + Swap4.UNITS 33 | + " from the origin."); 34 | 35 | Swap4.swap(p1, p2); 36 | 37 | d = p1.distance(p2); 38 | 39 | System.out.println(p1 + " is at a distance of " 40 | + d + " " + Swap4.UNITS 41 | + " from " + p2); 42 | } 43 | } -------------------------------------------------------------------------------- /code/recursion/Powers.java: -------------------------------------------------------------------------------- 1 | 2 | public class Powers 3 | { 4 | /** 5 | * Recursive version of computing X raised N. 6 | * 7 | * @param x 8 | * @param n 9 | * @return x raised n 10 | */ 11 | public static long power_v1(int x, int n) 12 | { 13 | long p; 14 | if (n == 0) { 15 | p = 1; 16 | } else { 17 | p = power_v1(x, n / 2) * power_v1(x, n / 2); 18 | if (n % 2 == 1) p *= x; 19 | } 20 | return p; 21 | } 22 | /** 23 | * Improved recursive version of computing X raised N. 24 | * 25 | * @param x 26 | * @param n 27 | * @return x raised n 28 | */ 29 | public static long power_v2(int x, int n) 30 | { 31 | long p; 32 | if (n == 0) { 33 | p = 1; 34 | } else { 35 | p = power_v2(x, n / 2); 36 | p = p * p; 37 | if (n % 2 == 1) p *= x; 38 | } 39 | return p; 40 | } 41 | 42 | public static void main(String [] args) 43 | { 44 | int x = 3; 45 | int n = 10; 46 | 47 | long p1 = power_v1(x, n); 48 | long p2 = power_v2(x, n); 49 | 50 | System.out.printf("\n%d raised %d is %d, that should be equal to %d\n\n", 51 | x, n, p1, p2); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /code/exceptions/ExceptionHandling3.java: -------------------------------------------------------------------------------- 1 | import java.util.InputMismatchException; 2 | import java.util.Scanner; 3 | 4 | public class ExceptionHandling3 5 | { 6 | static Scanner input = new Scanner(System.in); 7 | public static void main(String [] args) 8 | { 9 | int [] A = { 6, 7, 8, 9, 10, 11, 1, 3, 2, 4 }; 10 | boolean valueOK; 11 | int index = 0; 12 | do { 13 | valueOK = true; 14 | try { 15 | System.out.print("Position in the array? "); 16 | index = input.nextInt(); 17 | showValue(A, index); 18 | } 19 | catch (InputMismatchException ime) { 20 | ime.printStackTrace(System.err); 21 | System.out.printf("The message is: %s\n", ime.getMessage()); 22 | valueOK = false; 23 | input.nextLine(); 24 | } 25 | catch (ArrayIndexOutOfBoundsException aioobe) { 26 | aioobe.printStackTrace(System.err); 27 | System.out.printf("ERROR: %d is not a valid index!\n", index); 28 | valueOK = false; 29 | } 30 | } while (! valueOK); 31 | } 32 | public static void showValue(int [] A, int i) 33 | throws ArrayIndexOutOfBoundsException 34 | { 35 | System.out.println(A[i]); 36 | } 37 | } -------------------------------------------------------------------------------- /code/loops/Figures2.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | 4 | public class Figures2 5 | { 6 | public static void main(String [] args) 7 | { 8 | int offset = 10; 9 | int h = 22; 10 | 11 | triangle(offset, h, '*', 'O', 0.20); 12 | 13 | int w = 13; 14 | rectangle(offset + h - 1 - w / 2, 6, 12, '#'); 15 | } 16 | 17 | public static void rectangle(int offset, int height, int width, char c) 18 | { 19 | for (int i = 0; i < height; i++) { 20 | line(offset, ' '); 21 | line(width, c); 22 | System.out.println(); 23 | } 24 | } 25 | public static void triangle(int offset, int height, char c1, char c2, double p) 26 | { 27 | // the width of the base of the triangle will be 2 * height + 1 28 | int w = 1, o = height - 1; 29 | for (int i = 0; i < height; i++) { 30 | line(offset + o, ' '); 31 | line(w, c1, c2, p); 32 | System.out.println(); 33 | o--; 34 | w += 2; 35 | } 36 | } 37 | 38 | 39 | public static void line(int n, char c) 40 | { 41 | while (--n >= 0 ) System.out.print(c); 42 | } 43 | public static void line(int n, char c1, char c2, double probability) 44 | { 45 | while (--n >= 0 ) System.out.print(Math.random() < probability ? c2 : c1); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /code/misc/mcd.s: -------------------------------------------------------------------------------- 1 | .file "mcd.c" 2 | .text 3 | .globl mcd 4 | .type mcd, @function 5 | mcd: 6 | .LFB0: 7 | .cfi_startproc 8 | endbr64 9 | pushq %rbp 10 | .cfi_def_cfa_offset 16 11 | .cfi_offset 6, -16 12 | movq %rsp, %rbp 13 | .cfi_def_cfa_register 6 14 | movl %edi, -4(%rbp) 15 | movl %esi, -8(%rbp) 16 | jmp .L2 17 | .L5: 18 | movl -4(%rbp), %eax 19 | cmpl -8(%rbp), %eax 20 | jle .L3 21 | movl -4(%rbp), %eax 22 | cltd 23 | idivl -8(%rbp) 24 | movl %edx, -4(%rbp) 25 | jmp .L2 26 | .L3: 27 | movl -8(%rbp), %eax 28 | cltd 29 | idivl -4(%rbp) 30 | movl %edx, -8(%rbp) 31 | .L2: 32 | movl -4(%rbp), %eax 33 | cmpl -8(%rbp), %eax 34 | je .L4 35 | cmpl $0, -4(%rbp) 36 | je .L4 37 | cmpl $0, -8(%rbp) 38 | jne .L5 39 | .L4: 40 | cmpl $0, -4(%rbp) 41 | je .L6 42 | movl -4(%rbp), %eax 43 | jmp .L7 44 | .L6: 45 | cmpl $0, -8(%rbp) 46 | je .L8 47 | movl -8(%rbp), %eax 48 | jmp .L7 49 | .L8: 50 | movl $1, %eax 51 | .L7: 52 | popq %rbp 53 | .cfi_def_cfa 7, 8 54 | ret 55 | .cfi_endproc 56 | .LFE0: 57 | .size mcd, .-mcd 58 | .ident "GCC: (Ubuntu 9.3.0-10ubuntu2) 9.3.0" 59 | .section .note.GNU-stack,"",@progbits 60 | .section .note.gnu.property,"a" 61 | .align 8 62 | .long 1f - 0f 63 | .long 4f - 1f 64 | .long 5 65 | 0: 66 | .string "GNU" 67 | 1: 68 | .align 8 69 | .long 0xc0000002 70 | .long 3f - 2f 71 | 2: 72 | .long 0x3 73 | 3: 74 | .align 8 75 | 4: 76 | -------------------------------------------------------------------------------- /code/conditionals/Grades3.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Grades3 4 | { 5 | private static Scanner input = new Scanner(System.in).useLocale(Locale.US); 6 | 7 | public static void main(String [] args) 8 | { 9 | System.out.print("\n\n Enter your grade: "); 10 | double grade = input.nextDouble(); 11 | 12 | switch ((int)grade) { 13 | case 0 : 14 | case 1 : 15 | case 2 : 16 | System.out.println("\nGo home and never come back here!"); 17 | break; 18 | case 3 : 19 | System.out.println("\nSee you next year!"); 20 | break; 21 | case 4 : 22 | System.out.println("\nI will give you another opportunity!"); 23 | break; 24 | case 5 : 25 | case 6 : 26 | System.out.println("\nPassed!"); 27 | break; 28 | case 7 : 29 | case 8 : 30 | System.out.println("\nB"); 31 | break; 32 | case 9 : 33 | System.out.println("\nA"); 34 | break; 35 | case 10 : 36 | System.out.println("\nExcellent!"); 37 | break; 38 | default: 39 | System.out.println("\nThe grade is not a valid value!"); 40 | } 41 | } 42 | } -------------------------------------------------------------------------------- /examples/agenda3/src/NodeEvent.java: -------------------------------------------------------------------------------- 1 | package etsinf.prg.agenda3; 2 | 3 | import java.util.*; 4 | 5 | public class NodeEvent 6 | { 7 | private Event event; 8 | private NodeEvent next; 9 | private NodeEvent previous; 10 | 11 | public NodeEvent(NodeEvent previous, Event event, NodeEvent next) 12 | { 13 | this.previous = previous; 14 | this.event = event; 15 | this.next = next; 16 | } 17 | public NodeEvent(Event event, NodeEvent next) 18 | { 19 | this(null, event, next); 20 | } 21 | public NodeEvent(Event event) 22 | { 23 | this(null, event, null); 24 | } 25 | public Event getEvent() { return event; } 26 | public void setEvent(Event e) { event = e; } 27 | 28 | public NodeEvent getNext() { return next; } 29 | public void setNext(NodeEvent next) { this.next = next; } 30 | 31 | public NodeEvent getPrevious() { return previous; } 32 | public void setPrevious(NodeEvent previous) { this.previous = previous; } 33 | 34 | @Override 35 | public String toString() 36 | { 37 | return "<" + event.toString() + ">"; 38 | } 39 | 40 | @Override 41 | public boolean equals(Object o) 42 | { 43 | if (o instanceof NodeEvent) { 44 | 45 | NodeEvent other = (NodeEvent)o; 46 | 47 | return other.event.equals(this.event); 48 | } 49 | return false; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /code/files/TestBuffers.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.NoSuchElementException; 3 | import java.util.Scanner; 4 | 5 | public class TestBuffers 6 | { 7 | public static void main(String [] args) 8 | { 9 | String filename = null; 10 | 11 | for (int i = 0; i < args.length; i++) { 12 | if (args[i].equals("--file")) { 13 | filename = args[i + 1]; 14 | } 15 | } 16 | 17 | if (filename != null) { 18 | Scanner sf = null; 19 | try { 20 | sf = new Scanner( 21 | new BufferedInputStream( 22 | new FileInputStream( 23 | new File(filename)))); 24 | 25 | while (true) { 26 | String line = sf.nextLine(); //.trim(); 27 | System.out.println(line); 28 | } 29 | 30 | } 31 | // catch (EOFException e) 32 | catch (NoSuchElementException e) 33 | { 34 | System.out.println("*** The end-of-file was reached as expected. All is OK!"); 35 | } 36 | catch (FileNotFoundException e) 37 | { 38 | e.printStackTrace(System.err); 39 | } 40 | finally { 41 | if (sf != null) 42 | sf.close(); 43 | } 44 | } 45 | } 46 | } -------------------------------------------------------------------------------- /code/basic/RealDataTypes2.java: -------------------------------------------------------------------------------- 1 | public class RealDataTypes2 2 | { 3 | public static void main(String [] args) 4 | { 5 | float x = 2.0F / 7.0F; 6 | double y = 2.0 / 7.0; 7 | 8 | System.out.println(); 9 | System.out.println(); 10 | System.out.printf(" x = %22.17f %22.17e\n", x, x); 11 | System.out.printf(" y = %22.17f %22.17e\n", y, y); 12 | System.out.println(); 13 | System.out.println(); 14 | System.out.printf(" Float: min = %22.15e max = %22.16e \n", 15 | Float.MIN_VALUE, Float.MAX_VALUE); 16 | System.out.printf(" Double: min = %22.15e max = %22.16e \n", 17 | Double.MIN_VALUE, Double.MAX_VALUE); 18 | 19 | System.out.println(); 20 | System.out.println(); 21 | 22 | x = 1.2345670e+10F; 23 | System.out.printf("x = %.30f\n", x); 24 | for (int i = 0; i < 100000; i++) x++; 25 | System.out.printf("x = %.30f\n", x); 26 | x += 100000; 27 | System.out.printf("x = %.30f\n", x); 28 | 29 | System.out.println(); 30 | System.out.println(); 31 | 32 | y = 1.2345670e+10; 33 | System.out.printf("y = %.30f\n", y); 34 | for (int i = 0; i < 100000; i++) y++; 35 | System.out.printf("y = %.30f\n", y); 36 | y += 100000; 37 | System.out.printf("y = %.30f\n", y); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /code/loops/PrimeFactors.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.util.Random; 3 | 4 | 5 | public class PrimeFactors 6 | { 7 | public static void main(String [] args) { 8 | 9 | computeAndShow(2); 10 | computeAndShow(3); 11 | computeAndShow(10); 12 | computeAndShow(100); 13 | computeAndShow(512); 14 | computeAndShow(5417); 15 | computeAndShow(5147); 16 | 17 | Random r = new Random(); 18 | 19 | computeAndShow(Math.abs(r.nextInt())); 20 | } 21 | 22 | 23 | private static void computeAndShow(int n) { 24 | 25 | boolean debug = true; 26 | 27 | System.out.println("\n Prime factor decomposition of integer " + n); 28 | int e = 0; 29 | while (n > 0 && (n % 2) == 0) { 30 | e++; 31 | n /= 2; 32 | if (debug) System.out.printf("f = %d n = %d e = %d\n", 2, n, e); 33 | } 34 | if (e > 0) { 35 | System.out.printf("%12d^%d\n", 2, e); 36 | } 37 | 38 | int f = 3; 39 | do { 40 | e = 0; 41 | while (n > 0 && (n % f) == 0) { 42 | e++; 43 | n /= f; 44 | if (debug) System.out.printf("f = %d n = %d e = %d\n", f, n, e); 45 | } 46 | if (e > 0) { 47 | System.out.printf("%12d^%d\n", f, e); 48 | } 49 | f += 2; 50 | } while (n >= f); 51 | } 52 | } -------------------------------------------------------------------------------- /code/recursion/FibonacciWithMemoization.java: -------------------------------------------------------------------------------- 1 | 2 | public class FibonacciWithMemoization 3 | { 4 | private long [] temporaryComputations; 5 | 6 | public FibonacciWithMemoization() 7 | { 8 | temporaryComputations = new long [1000]; 9 | } 10 | 11 | private long fibonacci_r(int n) 12 | { 13 | if (n == 0) 14 | return 0; 15 | else if (n == 1) 16 | return 1; 17 | else if (n < temporaryComputations.length && temporaryComputations[n] > 0) 18 | return temporaryComputations[n]; 19 | else { 20 | temporaryComputations[n] = fibonacci_r(n - 1) + fibonacci_r(n - 2); 21 | return temporaryComputations[n]; 22 | } 23 | } 24 | 25 | public long fibonacci(int n) 26 | { 27 | if (n > temporaryComputations.length) { 28 | temporaryComputations = new long [n + 1]; 29 | } 30 | 31 | return fibonacci_r(n); 32 | } 33 | 34 | 35 | 36 | public static void main(String [] args) 37 | { 38 | FibonacciWithMemoization fwm = new FibonacciWithMemoization(); 39 | 40 | int n = 50; 41 | 42 | if (args.length > 0) n = Integer.parseInt(args[0]); 43 | 44 | long ms = System.currentTimeMillis(); 45 | long f = fwm.fibonacci(n); 46 | ms = System.currentTimeMillis() - ms; 47 | System.out.printf("Recursive with memoization version computed f(%d) = %d and needed %.6f seconds\n", n, f, ms / 1.0e+3); 48 | } 49 | } -------------------------------------------------------------------------------- /examples/agenda3/src/NodeContact.java: -------------------------------------------------------------------------------- 1 | package etsinf.prg.agenda3; 2 | 3 | import java.util.*; 4 | 5 | public class NodeContact 6 | { 7 | private Contact contact; 8 | private NodeContact next; 9 | private NodeContact previous; 10 | 11 | public NodeContact(NodeContact previous, Contact contact, NodeContact next) 12 | { 13 | this.previous = previous; 14 | this.contact = contact; 15 | this.next = next; 16 | } 17 | public NodeContact(Contact contact, NodeContact next) 18 | { 19 | this(null, contact, next); 20 | } 21 | public NodeContact(Contact contact) 22 | { 23 | this(null, contact, null); 24 | } 25 | public Contact getContact() { return contact; } 26 | public void setContact(Contact c) { contact = c; } 27 | 28 | public NodeContact getNext() { return next; } 29 | public void setNext(NodeContact next) { this.next = next; } 30 | 31 | public NodeContact getPrevious() { return previous; } 32 | public void setPrevious(NodeContact previous) { this.previous = previous; } 33 | 34 | @Override 35 | public String toString() 36 | { 37 | return "<" + contact.toString() + ">"; 38 | } 39 | 40 | @Override 41 | public boolean equals(Object o) 42 | { 43 | if (o instanceof NodeContact) { 44 | 45 | NodeContact other = (NodeContact)o; 46 | 47 | return other.contact.equals(this.contact); 48 | } 49 | return false; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /code/recursion/PascalTriangle.java: -------------------------------------------------------------------------------- 1 | 2 | public class PascalTriangle 3 | { 4 | public static void main(String [] args) 5 | { 6 | int n = 6; 7 | 8 | for (int i = 0; i < args.length; i++) { 9 | if (args[i].equals("-n")) 10 | n = Integer.parseInt(args[i+1]); 11 | } 12 | 13 | for (int row = 1; row <= n; row++) { 14 | for (int col = 1; col <= row; col++) 15 | System.out.printf(" %5d", pascalTriangle(row, col)); 16 | System.out.println(); 17 | } 18 | 19 | int [][] matrix = new int [n + 1][n + 1]; 20 | for (int row = 1; row <= n; row++) { 21 | for (int col = 1; col <= row; col++) 22 | matrix[row][col] = pascalTriangle(row, col); 23 | 24 | for (int row = 1; row <= n; row++) { 25 | for (int col = 1; col <= row; col++) 26 | if (col == 1 || col == row) 27 | matrix[row][col] = 1; 28 | else 29 | matrix[row][col] = matrix[row - 1][col -1] + matrix[row -1][col]; 30 | } 31 | 32 | /* 33 | pt(r, c) = 1 if c == 1 or c == r 34 | pt(r, c) = pt(r-1, c-1) + pt(r-1, c) otherwise 35 | */ 36 | private static int pascalTriangle(int row, int col) 37 | { 38 | if (col == 1 || col == row) { 39 | return 1; 40 | } else { 41 | return pascalTriangle(row - 1, col - 1) + pascalTriangle(row - 1, col); 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /code/exceptions/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.Calendar; 2 | import java.util.Date; 3 | import java.util.InputMismatchException; 4 | 5 | /** 6 | * Class for testing the use of objects of the class ClassesForAnObject. 7 | * To compile and run this class you need the class ClassesForAnObject 8 | * to be previously compiled. Use the scripts compile-examples.sh 9 | * and run-examples.sh to compile the class ClassesForAnObject 10 | * before compiling this class. Then, run it to see the result. 11 | * 12 | * @author Jon Ander Gómez (jon@dsic.upv.es) 13 | * @version 1.0 (March 2012) 14 | */ 15 | 16 | public class Main 17 | { 18 | /** 19 | * main() method for testing the use of objects of other classes. 20 | * 21 | * @param args Array of objects of class String with the list of command line arguments. 22 | */ 23 | public static void main(String [] args) 24 | { 25 | AskingForDate afd = new AskingForDate(null); 26 | Date d = Calendar.getInstance().getTime(); 27 | 28 | IllegalDateException ide = new IllegalDateException("A test"); 29 | InputMismatchException ime = new InputMismatchException("A test"); 30 | 31 | System.out.println(); 32 | ClassesForAnObject.listOfClasses(afd); 33 | ClassesForAnObject.listOfClasses(d); 34 | ClassesForAnObject.listOfClasses(Calendar.getInstance()); 35 | ClassesForAnObject.listOfClasses(ide); 36 | ClassesForAnObject.listOfClasses(ime); 37 | } 38 | } -------------------------------------------------------------------------------- /code/basic/Triangle.java: -------------------------------------------------------------------------------- 1 | import javax.swing.event.TableColumnModelListener; 2 | 3 | public class Triangle { 4 | private Point A, B, C; 5 | 6 | public Triangle() { 7 | A = new Point(-1, 0); 8 | B = new Point(1, 0); 9 | C = new Point(0, 1); 10 | } 11 | 12 | public Triangle(Point A, Point B, Point C) { 13 | this.A = A; 14 | this.B = B; 15 | this.C = C; 16 | } 17 | 18 | public Point getA() { return A; } 19 | public Point getB() { return B; } 20 | public Point getC() { return C; } 21 | 22 | public void setA(Point other) { A = other; } 23 | public void setB(Point other) { B = other; } 24 | public void setC(Point other) { C = other; } 25 | 26 | @Override 27 | public String toString() { 28 | return "Triangle formed by points: " + A + " and " + B + " and " + C; 29 | } 30 | 31 | @Override 32 | public boolean equals(Object o) { 33 | if (o instanceof Triangle) { 34 | Triangle other = (Triangle)o; 35 | 36 | // This is wrong, will fail in most of cases 37 | return this.A.equals(other.A) 38 | && this.B.equals(other.B) 39 | && this.C.equals(other.C); 40 | } else { 41 | return false; 42 | } 43 | } 44 | 45 | public double area() { 46 | double area = A.getX() * B.getY() - A.getY() * B.getX() 47 | - B.getX() * C.getY() + B.getY() * C.getX() 48 | + C.getX() * A.getY() - C.getY() * A.getX(); 49 | 50 | return Math.abs(area) / 2.0; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /code/basic/TestCircle.java: -------------------------------------------------------------------------------- 1 | import java.util.*; // With this line, we instruct the compiler to import all 2 | // the classes in subpackage "util" of the package "java" 3 | 4 | public class TestCircle 5 | { 6 | public static void main(String [] args) 7 | { 8 | Circle c1 = new Circle(); 9 | Circle c2 = new Circle(5.7, "turquoise", 157, 52); 10 | Circle c3 = c1; // c3 points/references to the same object referenced by c1 11 | 12 | System.out.println(c1.toString()); 13 | System.out.println(c2.toString()); 14 | 15 | c1.setCentre(7,6); 16 | System.out.println("Radius " + c1.getRadius()); 17 | System.out.println("Colour " + c1.getColour()); 18 | System.out.println("CenterX " + c1.getCentreX()); 19 | System.out.println("CenterY " + c1.getCentreY()); 20 | System.out.println(c1.toString()); 21 | c3 = null; // c3 is not referencing a valid object, next line will throw 22 | // an exeception of the class NullPointerException 23 | System.out.println(c3.toString()); 24 | 25 | /* The following lines will raise a compiler error 26 | because they try to access private attributes. 27 | 28 | System.out.println("Radius " + c1.radius); 29 | System.out.println("Colour " + c1.colour); 30 | System.out.println("CenterX " + c1.centreX); 31 | System.out.println("CenterY " + c1.centreY); 32 | */ 33 | 34 | System.out.println(); 35 | 36 | System.out.println(Math.E); 37 | System.out.println(Math.PI); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /code/files/SeeDirectory.java: -------------------------------------------------------------------------------- 1 | 2 | import java.io.*; 3 | 4 | class SeeDirectory 5 | { 6 | public static void main(String [] args) 7 | { 8 | File d = new File("."); 9 | 10 | if (d.exists()) 11 | System.out.println("File exists!"); 12 | else 13 | System.err.println("File doesn’t exist!"); 14 | 15 | System.err.println(); 16 | 17 | System.out.println(" getName(): " + d.getName()); 18 | System.out.println("getParent(): " + d.getParent()); 19 | System.out.println(" length(): " + d.length()); 20 | 21 | if (d.isDirectory()) { 22 | System.out.println("--------------------------------"); 23 | for (File f : d.listFiles()) { 24 | System.out.println(f); 25 | } 26 | System.out.println("--------------------------------"); 27 | } 28 | 29 | wipeFiles("../../.."); 30 | } 31 | 32 | public static void wipeFiles(String dirname) 33 | { 34 | File file = new File(dirname); 35 | 36 | if (file.exists()) { 37 | if (file.isDirectory()) { 38 | for (File f : file.listFiles()) { 39 | wipeFiles(f.getParent() + "/" + f.getName()); 40 | } 41 | } else { 42 | // This is very dangerous because this will wipe all files it encounters 43 | // Don't try it please, this is just an example. 44 | //PrintWriter pw = new PrintWriter(file); 45 | //pw.close(); 46 | System.out.println(file); 47 | } 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /examples/agenda2/src/Date.java: -------------------------------------------------------------------------------- 1 | package etsinf.prg.agenda2; 2 | 3 | /** 4 | * Simple class for represeting a date with year, month and day. 5 | * Used in the class Contact for attributed birth date. 6 | */ 7 | 8 | public class Date 9 | { 10 | private int year, month, day; 11 | 12 | public Date(int d, int m, int y) 13 | { 14 | year = y; 15 | month = m; 16 | day = d; 17 | } 18 | 19 | public int getYear() { return year; } 20 | public int getMonth() { return month; } 21 | public int getDay() { return day; } 22 | 23 | @Override 24 | public String toString() 25 | { 26 | return String.format("%04d-%02d-%02d", year, month, day); 27 | } 28 | @Override 29 | public boolean equals(Object o) 30 | { 31 | if (o instanceof Date) { 32 | Date other = (Date)o; 33 | 34 | return this.year == other.year 35 | && this.month == other.month 36 | && this.day == other.day; 37 | } 38 | return false; 39 | } 40 | public int compareTo(Date other) 41 | { 42 | return this.toInt() - other.toInt(); 43 | } 44 | public int toInt() 45 | { 46 | return year * 10000 + month * 100 + day; 47 | } 48 | 49 | public Date clone() 50 | { 51 | return new Date(day, month, year); 52 | } 53 | 54 | public int getAge(Date reference) 55 | { 56 | int age = reference.year - this.year; 57 | 58 | if (this.month * 100 + this.day > reference.month * 100 + reference.day) 59 | age--; 60 | 61 | return age; 62 | } 63 | } -------------------------------------------------------------------------------- /examples/agenda3/src/Date.java: -------------------------------------------------------------------------------- 1 | package etsinf.prg.agenda3; 2 | 3 | /** 4 | * Simple class for represeting a date with year, month and day. 5 | * Used in the class Contact for attributed birth date. 6 | */ 7 | 8 | public class Date 9 | { 10 | private int year, month, day; 11 | 12 | public Date(int d, int m, int y) 13 | { 14 | year = y; 15 | month = m; 16 | day = d; 17 | } 18 | 19 | public int getYear() { return year; } 20 | public int getMonth() { return month; } 21 | public int getDay() { return day; } 22 | 23 | @Override 24 | public String toString() 25 | { 26 | return String.format("%04d-%02d-%02d", year, month, day); 27 | } 28 | @Override 29 | public boolean equals(Object o) 30 | { 31 | if (o instanceof Date) { 32 | Date other = (Date)o; 33 | 34 | return this.year == other.year 35 | && this.month == other.month 36 | && this.day == other.day; 37 | } 38 | return false; 39 | } 40 | public int compareTo(Date other) 41 | { 42 | return this.toInt() - other.toInt(); 43 | } 44 | public int toInt() 45 | { 46 | return year * 10000 + month * 100 + day; 47 | } 48 | 49 | public Date clone() 50 | { 51 | return new Date(day, month, year); 52 | } 53 | 54 | public int getAge(Date reference) 55 | { 56 | int age = reference.year - this.year; 57 | 58 | if (this.month * 100 + this.day < reference.month * 100 + reference.day) 59 | age--; 60 | 61 | return age; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /cpr/python/point2d.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import math 4 | 5 | class Point2d: 6 | ''' 7 | Class for represeting points in the plane (two-dimensional space) 8 | ''' 9 | epsilon = 1.0e-5 10 | 11 | def __init__( self, x=0.0, y=0.0 ): 12 | self.x = float(x) 13 | self.y = float(y) 14 | #self.epsilon = 1.0e-5 15 | 16 | def distance( self, other=None ): 17 | if other is None: other = Point2d() 18 | 19 | dx = self.x - other.x 20 | dy = self.y - other.y 21 | 22 | return math.sqrt( dx*dx + dy*dy ) 23 | 24 | 25 | def __lt__( self, other ): 26 | return self.y < other.y or (self.y == other.y and self.x < other.x) 27 | 28 | def __le__( self, other ): 29 | return self.y < other.y or (self.y == other.y and self.x <= other.x) 30 | 31 | def __eq__( self, other ): 32 | return abs(self.y - other.y) < self.epsilon and abs(self.x - other.x) < self.epsilon 33 | 34 | def __ne__( self, other ): 35 | return abs(self.y - other.y) > self.epsilon or abs(self.x - other.x) >= self.epsilon 36 | 37 | def __ge__( self, other ): 38 | return self.y > other.y or (self.y == other.y and self.x >= other.x) 39 | 40 | def __gt__( self, other ): 41 | return self.y > other.y or (self.y == other.y and self.x > other.x) 42 | 43 | def __str__( self ): 44 | return f"({self.x},{self.y})" 45 | 46 | 47 | 48 | if __name__ == '__main__': 49 | 50 | p0 = Point2d() 51 | p1 = Point2d( x=1, y=2 ) 52 | 53 | print( f"p0 {p0}" ) 54 | print( f"p1 {p1}" ) 55 | print( "%s and %s %s equal" % (p0,p1, "are" if p0==p1 else "are NOT" ) ) 56 | -------------------------------------------------------------------------------- /code/loops/Fibonacci.java: -------------------------------------------------------------------------------- 1 | import java.util.Locale; 2 | import java.util.Scanner; 3 | 4 | /* 5 | More info in the following link: 6 | 7 | https://en.wikipedia.org/wiki/Fibonacci_number 8 | */ 9 | 10 | public class Fibonacci 11 | { 12 | private static Scanner input = new Scanner(System.in).useLocale(Locale.US); 13 | 14 | public static void main(String [] args) 15 | { 16 | for (int n = 0; n < 20; n++) { 17 | System.out.printf("%4d %20d %20d\n", n, fib(n), fib2(n)); 18 | } 19 | } 20 | 21 | public static long fib(int n) 22 | { 23 | long fib = 1, fib_ant = -1; 24 | 25 | for (int i = 0; i <= n; i++) { 26 | fib = fib + fib_ant; 27 | fib_ant = fib - fib_ant; 28 | } 29 | 30 | return fib; 31 | } 32 | public static long fib2(int n) 33 | { 34 | long fib = 1, fib_ant = -1; 35 | 36 | do { 37 | fib = fib + fib_ant; 38 | fib_ant = fib - fib_ant; 39 | } while (--n >= 0); 40 | 41 | return fib; 42 | } 43 | } 44 | /* 45 | fib fib_ant n 46 | ================================== 47 | 1 -1 5 48 | 0 1 4 49 | 1 0 3 50 | 1 1 2 51 | 2 1 1 52 | 3 2 0 53 | 5 3 -1 54 | */ 55 | 56 | /* 57 | ++n; 58 | fib_ant = fib - fib_ant; 59 | fib = fib - fib_ant; 60 | 1 -1 5 61 | 0 1 4 62 | 1 0 3 63 | 1 1 2 64 | 2 1 1 65 | 3 2 0 66 | 5 3 -1 67 | */ -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Programming 2 | 3 | ### Purpose 4 | This repository contains code written by Jon Ander Gómez as examples for students 5 | during his classes of Computer Programming at the [**Technical University of Valencia (UPV)**](https://www.upv.es/). 6 | All corresponds to the first academic year of the Bachelor's Degree in Computer Engineering of the 7 | [**School of Informatics (ETSINF)**](https://www.etsinf.upv.es/) of the UPV. 8 | 9 | The Bachelor's Degre in Computer Engineering is know in Spanish as ***Grado en Ingeniería Informática (GII)***. 10 | 11 | The School of Informatics is know in Spanish as ***Escuela Técnica Superior de Ingeniería Informática (ETSINF)***. 12 | 13 | ### The subjects related to this repository are **IIP** and **PRG** 14 | 15 | * IIP is the acronym of the first semester subject and stands for Spanish title _**Introducción a la Informática y la Programación**_ 16 | * PRG is the acronym of the second semester subject and stands for Spanish title _**Programación**_ 17 | 18 | The next figure shows where both subjects are in the context of the Bachelor's Degree in Computer Engineering. 19 | 20 | ![Here](images/Computer-programming-in-the-GII.png) 21 | 22 | 23 | ### Folders with code are organised by topics 24 | 25 | In some cases you will find examples in one folder covering topics assigned to another folder, please, accept my apologies if this confuses you. 26 | 27 | * [code](code) 28 | 29 | 30 | ### Distribution of the contents of Computer Programming 31 | The following figure shows the distribution of *Computer Programming* as a matter tought in several subjects along the Degree in Computer Engineering. 32 | 33 | ![Compute Programming contents](images/Computer-Programming-contents.png) 34 | 35 | 36 | -------------------------------------------------------------------------------- /cpr/java/Edge.java: -------------------------------------------------------------------------------- 1 | 2 | package es.upv.etsinf.graphs; 3 | 4 | public class Edge 5 | { 6 | protected Vertex origin; 7 | protected Vertex destination; 8 | 9 | protected String label; 10 | 11 | protected double weight; 12 | 13 | protected double capacity; 14 | protected double flow; 15 | protected double residual; 16 | 17 | public Edge(Vertex origin, Vertex destination) 18 | { 19 | this.origin = origin; 20 | this.destination = destination; 21 | this.label = null; 22 | reset(); 23 | } 24 | public Edge(Vertex origin, Vertex destination, String label) 25 | { 26 | this.origin = origin; 27 | this.destination = destination; 28 | this.label = label; 29 | reset(); 30 | } 31 | 32 | public void reset() 33 | { 34 | weight = 1.0; 35 | capacity = 1.0; 36 | flow = 0.0; 37 | residual = 0.0; 38 | } 39 | 40 | public Vertex getOrigin() { return origin; } 41 | public Vertex getDestination() { return destination; } 42 | public String getLabel() { return label; } 43 | 44 | public double getWeight() { return weight; } 45 | 46 | public void setWeight(double w) { weight=w; } 47 | 48 | public double getCapacity() { return capacity; } 49 | public double getFlow() { return flow; } 50 | public double getResidual() { return residual; } 51 | 52 | 53 | public void setCapacity(double c) { capacity = c; } 54 | public void setFlow(double f) { flow = f; } 55 | public void setResidual(double r) { residual = r; } 56 | 57 | 58 | public String toString() 59 | { 60 | return origin.toString() + " --> " + destination.toString(); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /code/methods/Program02.java: -------------------------------------------------------------------------------- 1 | public class Program02 2 | { 3 | public static void main(String [] args) 4 | { 5 | Point p1 = new Point( 2.5, 3.0); 6 | Point p2 = new Point( 2.5, -1.2); 7 | Point p3 = new Point(-1.5, 1.4); 8 | 9 | System.out.println("Triangle with vertex at points:"); 10 | //System.out.printf("\t (%.2f, %.2f) \n", p1.getX(), p1.getY()); 11 | //System.out.printf("\t (%.2f, %.2f) \n", p2.getX(), p2.getY()); 12 | //System.out.printf("\t (%.2f, %.2f) \n", p3.getX(), p3.getY()); 13 | System.out.printf("\t %s \n", p1); 14 | System.out.printf("\t %s \n", p2); 15 | System.out.printf("\t %s \n", p3); 16 | 17 | //double sideLength12 = distance(p1.getX(), p1.getY(), p2.getX(), p2.getY()); 18 | //double sideLength23 = distance(p2.getX(), p2.getY(), p3.getX(), p3.getY()); 19 | //double sideLength31 = distance(p3.getX(), p3.getY(), p1.getX(), p1.getY()); 20 | /* 21 | double sideLength12 = distance(p1, p2); 22 | double sideLength23 = distance(p2, p3); 23 | double sideLength31 = distance(p3, p1); 24 | double perimeter = sideLength12 + sideLength23 + sideLength31; 25 | */ 26 | double perimeter = p1.distance(p2) + p2.distance(p3) + p3.distance(p1); 27 | System.out.println("Perimeter = " + perimeter); 28 | } 29 | 30 | public static double distance(double x1, double y1, double x2, double y2) 31 | { 32 | double dx = x1 - x2, dy = y1 - y2; 33 | return Math.sqrt(dx * dx + dy * dy); 34 | } 35 | public static double distance(Point p, Point q) 36 | { 37 | double dx = p.getX() - q.getX(), dy = p.getY() - q.getY(); 38 | return Math.sqrt(dx * dx + dy * dy); 39 | } 40 | } -------------------------------------------------------------------------------- /code/exams_from_previous_years/2018-2019/WorkWithFiles2.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | 4 | public class WorkWithFiles2 5 | { 6 | public static void main(String [] args) 7 | throws FileNotFoundException 8 | { 9 | checkTable("atp.in", "errors_found.txt"); 10 | } 11 | 12 | public static void checkTable(String fileIn, String fileOut) 13 | throws FileNotFoundException 14 | { 15 | Scanner input = new Scanner(new File(fileIn)); 16 | PrintWriter output = new PrintWriter(fileOut); 17 | 18 | int counter = 0; 19 | while (input.hasNext()) { 20 | try { 21 | String line = input.nextLine(); 22 | String [] tokens = line.split("([ \t])+"); 23 | ++counter; 24 | 25 | if (tokens.length != 4) { 26 | throw new Exception(String.format("Error line %d: Unexpected number of columns.", counter)); 27 | } else { 28 | String lastName = tokens[0]; 29 | int age = Integer.parseInt(tokens[1]); 30 | if (age <= 0) 31 | throw new Exception(String.format("Error line %d: Negative value.", counter)); 32 | int points = Integer.parseInt(tokens[2]); 33 | int championships = Integer.parseInt(tokens[3]); 34 | } 35 | } 36 | catch (NumberFormatException e) { 37 | output.printf("Error line %d: Invalid format for an integer.\n", counter); 38 | } 39 | catch (Exception e) { 40 | output.println(e.getMessage()); 41 | } 42 | } 43 | input.close(); 44 | output.close(); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /code/conditionals/FinalGrade.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class FinalGrade 4 | { 5 | private static Scanner input = new Scanner(System.in).useLocale(Locale.US); 6 | 7 | public static void main(String [] args) 8 | { 9 | System.out.print("\n MG1: "); double mg1 = input.nextDouble(); 10 | System.out.print("\n MG2: "); double mg2 = input.nextDouble(); 11 | System.out.print("\n LG1: "); double lg1 = input.nextDouble(); 12 | System.out.print("\n LG2: "); double lg2 = input.nextDouble(); 13 | System.out.print("\n attendance [0,1]: "); double attendance = input.nextDouble(); 14 | 15 | double fg = finalGrade(mg1, mg2, lg1, lg2, attendance); 16 | 17 | System.out.printf("\n The final grade is %.1f\n", fg); 18 | } 19 | 20 | static double updateGrade1(double g1, double g2) 21 | { 22 | if (g2 >= 6) { 23 | g1 = (g2 > g1) ? g2 : g1; // Math.max(g1, g2); 24 | } else if (g2 >= 4) { 25 | double temp = (g1 + g2) / 2.0; 26 | g1 = (temp > g1) ? temp : g1; 27 | } 28 | return g1; 29 | } 30 | static double finalGrade(double mg1, double mg2, double lg1, double lg2, double attendance) 31 | { 32 | /* 33 | mg1 = (4 <= mg2 && mg2 < 6) ? (mg1 + mg2)/2 : ((mg2 >= 6) ? mg2 : mg1); 34 | 35 | if (lg2 >= 6) { 36 | lg1 = lg2; 37 | } else if (lg2 >= 4) { 38 | lg1 = (lg1 + lg2) / 2; 39 | } 40 | */ 41 | mg1 = updateGrade1(mg1, mg2); 42 | lg1 = updateGrade1(lg1, lg2); 43 | 44 | double mwg = 0.5 * mg1 + 0.5 * mg2; 45 | double lwg = 0.5 * lg1 + 0.5 * lg2; 46 | lwg = (attendance >= 0.8) ? lwg : 0; 47 | 48 | return 0.75 * mwg + 0.25 * lwg; 49 | } 50 | } -------------------------------------------------------------------------------- /cpr/java/AllSubsets2.java: -------------------------------------------------------------------------------- 1 | 2 | package es.upv.etsinf.backtraking; 3 | 4 | class AllSubsets2 5 | { 6 | private boolean completed; // In this example is not used because all permutations should be generated. 7 | private boolean [] solution; 8 | private int n; 9 | 10 | private boolean isSolution(int k) 11 | { 12 | return (k == 0); 13 | } 14 | private boolean [] buildCandidates() 15 | { 16 | boolean [] c = new boolean [2]; 17 | 18 | c[0] = false; 19 | c[1] = true; 20 | 21 | return c; 22 | } 23 | private void processSolution() 24 | { 25 | System.out.print("{"); 26 | for (int i = 1; i <= n; i++) { 27 | if (solution[i]) System.out.print(" " + i); 28 | } 29 | System.out.println(" }"); 30 | } 31 | 32 | private void backtrack(int k) 33 | { 34 | if (isSolution(k)) { 35 | 36 | processSolution(); 37 | 38 | } else { 39 | 40 | boolean [] candidates = buildCandidates(); 41 | for (int i = 0; i < candidates.length; i++) { 42 | solution[k] = candidates[i]; 43 | backtrack(k - 1); 44 | solution[k] = false; 45 | 46 | if (completed) return; 47 | } 48 | } 49 | } 50 | 51 | public void generateSubsets(int n) 52 | { 53 | this.completed = false; 54 | this.n = n; 55 | this.solution = new boolean [n+1]; 56 | 57 | backtrack(n); 58 | } 59 | 60 | public static void main(String [] args) 61 | { 62 | AllSubsets2 as = new AllSubsets2(); 63 | 64 | int n = 3; 65 | 66 | if (args.length > 0) n = Integer.parseInt(args[0]); 67 | 68 | as.generateSubsets(n); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /cpr/java/AllSubsets.java: -------------------------------------------------------------------------------- 1 | 2 | package es.upv.etsinf.backtraking; 3 | 4 | class AllSubsets 5 | { 6 | private boolean completed; // In this example is not used because all permutations should be generated. 7 | private boolean [] solution; 8 | private int n; 9 | 10 | private boolean isSolution(int k) 11 | { 12 | return (k == n); 13 | } 14 | private boolean [] buildCandidates() 15 | { 16 | boolean [] c = new boolean [2]; 17 | 18 | c[0] = false; 19 | c[1] = true; 20 | 21 | return c; 22 | } 23 | private void processSolution() 24 | { 25 | System.out.print("{"); 26 | for (int i = 1; i <= n; i++) { 27 | if (solution[i]) System.out.print(" " + i); 28 | } 29 | System.out.println(" }"); 30 | } 31 | 32 | private void backtrack(int k) 33 | { 34 | if (isSolution(k)) { 35 | 36 | processSolution(); 37 | 38 | } else { 39 | 40 | k++; 41 | boolean [] candidates = buildCandidates(); 42 | for (int i = 0; i < candidates.length; i++) { 43 | solution[k] = candidates[i]; 44 | backtrack(k); 45 | solution[k] = false; 46 | 47 | if (completed) return; 48 | } 49 | } 50 | } 51 | 52 | public void generateSubsets(int n) 53 | { 54 | this.completed = false; 55 | this.n = n; 56 | this.solution = new boolean [n+1]; 57 | 58 | backtrack(0); 59 | } 60 | 61 | public static void main(String [] args) 62 | { 63 | AllSubsets as = new AllSubsets(); 64 | 65 | int n = 3; 66 | 67 | if (args.length > 0) n = Integer.parseInt(args[0]); 68 | 69 | as.generateSubsets(n); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /code/recursion/Exam20190418.java: -------------------------------------------------------------------------------- 1 | 2 | public class Exam20190418 3 | { 4 | public static void main(String [] args) 5 | { 6 | String [] array = {"ship", "bus", "train", "moto", "bicycle", "aircraft"}; 7 | 8 | System.out.println("contents of the array:"); 9 | for (String s : array) System.out.print(" " + s); 10 | System.out.println(); 11 | System.out.println(); 12 | 13 | for (int n = 3; n <= 10; n++) { 14 | System.out.printf("%3d words of length %3d were found in the array.\n", 15 | countWordsOfLengthN(array, n), n); 16 | } 17 | } 18 | 19 | /* 20 | preconditions: 21 | v != null 22 | n >= 0 23 | 0 <= index < v.length 24 | 25 | point (b) 26 | trivial case: 27 | when index is less than zero, what means the array is empty 28 | 29 | return 0 30 | 31 | general case: 32 | index >= 0 :: that indicates the size of the subarray pending 33 | to be explored is (index+1) 34 | 35 | cwofn(v, n, index): 36 | 1 + cwofn(v, n, index-1) if len(a[index]) == n 37 | cwofn(v, n, index - 1) otherwise 38 | */ 39 | private static int countWordsOfLengthN(String [] v, int n, int index) // point (a) 40 | { 41 | // point (c) 42 | if (index < 0) 43 | return 0; 44 | else if (v[index].length() == n) 45 | return 1 + countWordsOfLengthN(v, n, index - 1); 46 | else 47 | return countWordsOfLengthN(v, n, index - 1); 48 | } 49 | 50 | // wrapper method 51 | private static int countWordsOfLengthN(String [] v, int n) 52 | { 53 | return countWordsOfLengthN(v, n, v.length - 1); // point (d) 54 | } 55 | } -------------------------------------------------------------------------------- /code/exceptions/ReadNumbers2.java: -------------------------------------------------------------------------------- 1 | import java.util.InputMismatchException; 2 | import java.util.Scanner; 3 | 4 | public class ReadNumbers2 5 | { 6 | private static Scanner input; 7 | 8 | public static void main(String [] args) 9 | { 10 | input = new Scanner(System.in); 11 | boolean correct; 12 | int n = 0; 13 | double x = 0.0; 14 | 15 | do { 16 | correct = true; 17 | try { 18 | System.out.print("Enter an integer number from 1 up to 100, both included: "); 19 | n = input.nextInt(); 20 | if (n < 0 || n > 100) throw new InputMismatchException("Out of range!"); 21 | } 22 | catch (InputMismatchException ime) { 23 | correct = false; 24 | System.err.println("ERROR: " + ime.getMessage()); 25 | } 26 | finally 27 | { 28 | input.nextLine(); 29 | } 30 | } while (! correct); 31 | 32 | do { 33 | correct = true; 34 | try { 35 | System.out.print("Enter a real number in the range 0..1: "); 36 | x = input.nextDouble(); 37 | if (x < 0.0 || x > 1.0) throw new InputMismatchException("Out of range!"); 38 | } 39 | catch (InputMismatchException ime) { 40 | correct = false; 41 | System.err.println("ERROR: " + ime.getMessage()); 42 | } 43 | finally 44 | { 45 | input.nextLine(); 46 | } 47 | } while (! correct); 48 | 49 | 50 | System.out.println(); 51 | System.out.println(); 52 | System.out.printf(" n = %d x = %f\n", n, x); 53 | System.out.println(); 54 | System.out.println(); 55 | } 56 | } -------------------------------------------------------------------------------- /code/basic/PrintfExamples.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class PrintfExamples 4 | { 5 | public static void main(String [] args) 6 | { 7 | boolean b = true; 8 | char c = '€'; 9 | int i = 7845; 10 | float f = 235.123F; 11 | double d = 435.4235255; 12 | String s = "abcdefghijklmnopqrstuvwxyz"; 13 | 14 | System.out.printf("b = %b\n", b); 15 | System.out.printf("c = %c\n", c); 16 | 17 | System.out.printf("i = %07d\n", i); 18 | System.out.printf("i = %7d\n", i); 19 | System.out.printf("i = %6d\n", i); 20 | System.out.printf("i = %5d\n", i); 21 | System.out.printf("i = %4d\n", i); 22 | System.out.printf("i = %3d\n", i); 23 | System.out.printf("i = %2d\n", i); 24 | System.out.printf("i = %d\n", i); 25 | System.out.printf("i = %o\n", i); 26 | System.out.printf("i = %x\n", i); 27 | 28 | System.out.printf("f = %20.5f\n", f); 29 | System.out.printf("f = %20.4f\n", f); 30 | System.out.printf("f = %20.3f\n", f); 31 | System.out.printf("f = %20.2f\n", f); 32 | System.out.printf("f = %20.1f\n", f); 33 | System.out.printf("f = %20.0f\n", f); 34 | System.out.printf("f = %.9e\n", f); 35 | 36 | System.out.printf("d = %20.5f\n", d); 37 | System.out.printf("d = %20.4f\n", d); 38 | System.out.printf("d = %20.3f\n", d); 39 | System.out.printf("d = %20.2f\n", d); 40 | System.out.printf("d = %20.1f\n", d); 41 | System.out.printf("d = %20.0f\n", d); 42 | System.out.printf("d = %.9e\n", d); 43 | 44 | System.out.printf("s = %s\n", s); 45 | System.out.printf("s = %.10s\n", s); 46 | System.out.printf("s = %30.10s\n", s); 47 | System.out.printf("s = %-30.10s\n", s); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /code/conditionals/SecondDegreeEquations.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | 4 | public class SecondDegreeEquations 5 | { 6 | private static Scanner input = new Scanner(System.in).useLocale(Locale.US); 7 | 8 | public static void main(String [] args) 9 | { 10 | double a, b, c; 11 | 12 | System.out.print("\n Enter the values for A, B and C: "); 13 | a = input.nextDouble(); 14 | b = input.nextDouble(); 15 | c = input.nextDouble(); 16 | 17 | if (a == 0.0) { 18 | if (b == 0.0) { 19 | if (c == 0.0) { 20 | System.out.printf("There are infinite solutions!\n"); 21 | } else { 22 | System.out.printf("ERROR!\n"); 23 | } 24 | } else { 25 | System.out.printf("One degree equation x = %.6f\n", -c / b); 26 | } 27 | } else { 28 | if (b * b >= 4 * a * c) { 29 | if (b * b == 4 * a * c) { 30 | double x = -b / (2 * a); 31 | System.out.printf("Double solution x = %.6f\n", x); 32 | } else { 33 | double sqrt = Math.sqrt(b * b - 4 * a * c); 34 | double x1 = (-b + sqrt) / (2 * a); 35 | double x2 = (-b - sqrt) / (2 * a); 36 | System.out.printf("x1 = %.6f\n", x1); 37 | System.out.printf("x2 = %.6f\n", x2); 38 | } 39 | } else { 40 | double sqrt = Math.sqrt(4 * a * c - b * b); 41 | double real = -b / (2 * a); 42 | double imag = sqrt / (2 * a); 43 | System.out.printf("x1 = %.6f%+.6fi\n", real, imag); 44 | System.out.printf("x2 = %.6f%+.6fi\n", real, -imag); 45 | } 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /code/recursion/KeyPalindrome.java: -------------------------------------------------------------------------------- 1 | 2 | public class KeyPalindrome 3 | { 4 | public static void main(String [] args) 5 | { 6 | int [] a = {20, 15, 14, 32, 10, 7, 22}; 7 | 8 | int k = a.length + 3; 9 | if (keyPalindrome(a, k)) { 10 | System.out.printf("it is keyPalindrome(%d)\n", k); 11 | } else { 12 | System.out.printf("it is NOT keyPalindrome(%d)\n", k); 13 | } 14 | k = a.length + 1; 15 | if (keyPalindrome(a, k)) { 16 | System.out.printf("it is keyPalindrome(%d)\n", k); 17 | } else { 18 | System.out.printf("it is NOT keyPalindrome(%d)\n", k); 19 | } 20 | k = 22; 21 | if (keyPalindrome(a, k)) { 22 | System.out.printf("it is keyPalindrome(%d)\n", k); 23 | } else { 24 | System.out.printf("it is NOT keyPalindrome(%d)\n", k); 25 | } 26 | } 27 | 28 | /* 29 | k >= a.length 30 | 0 <= i <= a.length/2 31 | 32 | trivial cases: 33 | return true if i > a.length / 2 34 | return false if k < a.length 35 | 36 | general cases: 37 | i <= a.length / 2: 38 | return false if abs(a[i] - a[a.length-i-1]) >= k-i 39 | return keyPalindrome(a, k, i+1) otherwise 40 | */ 41 | public static boolean keyPalindrome(int [] a, int k) 42 | { 43 | return keyPalindrome(a, k, 0); 44 | } 45 | public static boolean keyPalindrome(int [] a, int k, int i) 46 | { 47 | if (k < a.length) 48 | return false; 49 | else if (i > a.length / 2) 50 | return true; 51 | else if (Math.abs(a[i] - a[a.length - i - 1]) >= k - i) 52 | return false; 53 | else 54 | return keyPalindrome(a, k, i + 1); 55 | } 56 | } -------------------------------------------------------------------------------- /cpr/cpp/primeFactorization.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | list * primeFactorization(int n) 7 | { 8 | list *factors = new list(); 9 | int i, ii; 10 | 11 | while ((n % 2) == 0) 12 | { 13 | factors->push_back(2); 14 | n /= 2; 15 | } 16 | 17 | i = 3; 18 | ii = i * i; 19 | while (ii <= n) 20 | { 21 | if ((n % i) == 0) 22 | { 23 | factors->push_back(i); 24 | n /= i; 25 | } 26 | else 27 | { 28 | ii += (i << 2) + 4; 29 | i += 2; 30 | } 31 | } 32 | 33 | if (n > 1) 34 | factors->push_back(n); 35 | 36 | return factors; 37 | } 38 | /* 39 | (i+2)*(i+2) = i*i + 2*i + 2*i + 4 = i*i + 4*i + 4 40 | 3*3 = 9 41 | 5*5 = 25 = 9 + 4*3 + 4 = 9+12+4 = 25 42 | 7*7 = 49 = 25 + 4*5 + 4 = 25+20+4 = 49 43 | 44 | c += i+i+i+i+4; 45 | c += i<<2 + 4; 46 | */ 47 | 48 | typedef pair prime_factor; 49 | 50 | list * primeFactorization_v2(u_int64_t n) 51 | { 52 | list *factors = new list(); 53 | u_int64_t i, ii; 54 | 55 | prime_factor pf(2, 0); 56 | while ((n % 2) == 0) 57 | { 58 | n /= 2; 59 | pf.second++; 60 | } 61 | if (pf.second > 0) 62 | factors->push_back(pf); 63 | 64 | i = 3; 65 | ii = i * i; 66 | while (ii <= n) 67 | { 68 | 69 | pf.first = i; 70 | pf.second = 0; 71 | 72 | while ((n % i) == 0) 73 | { 74 | pf.second++; 75 | n /= i; 76 | } 77 | if (pf.second > 0) 78 | factors->push_back(pf); 79 | 80 | ii += (i << 2) + 4; 81 | i += 2; 82 | } 83 | 84 | if (n > 1) 85 | factors->push_back(prime_factor(n, 1)); 86 | 87 | return factors; 88 | } -------------------------------------------------------------------------------- /code/exams_from_previous_years/2019_2020/src/Exercises2and3.java: -------------------------------------------------------------------------------- 1 | package etsinf.prg.exam2; 2 | /** 3 | * Exercises 2 and 3 - Second mid term exam 4 | * 5 | * @author IIP professors 6 | * @version Academic year 19/20 7 | */ 8 | public class Exercises2and3 9 | { 10 | /** Hidden method */ 11 | private Exercises2and3() { } 12 | 13 | /** 14 | * Given an array of positive integers, 15 | * returns the value of the first repeated element 16 | * in any other position of the array, 17 | * otherwise returns -1 for indicating 18 | * no repeated elements exist in the array. 19 | */ 20 | /** Precondition: v is an array of positive integers. */ 21 | public static int firstRepeatedElement(int[] v) 22 | { 23 | int i = 0, j; 24 | boolean found = false; 25 | while (i < v.length - 1 && !found) { 26 | j = i + 1; 27 | while (j < v.length && !found) { 28 | found = v[i] == v[j]; 29 | j++; 30 | } 31 | i++; 32 | } 33 | return (found) ? v[i - 1] : -1; 34 | 35 | /* Alternative code 36 | for (int i = 0; i < v.length-1; i++) { 37 | for (int j = i+1; j < v.length; j++) { 38 | if (v[i] == v[j]) return v[i]; 39 | } 40 | } 41 | return -1; 42 | */ 43 | } 44 | 45 | /** Precondition: 0 <= epsilon < 1 */ 46 | public static int numTerms(double x, double epsilon) 47 | { 48 | if (x <= 0) return -1; 49 | 50 | double previousC = x; // C_1 51 | double currentC = previousC * 2; // C_2 = C_1 * 2 52 | int n = 2; 53 | while (1 / (currentC - previousC) > epsilon) { 54 | n++; 55 | previousC = currentC; 56 | currentC = currentC * n; // previousC * n 57 | } 58 | return n; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /examples/agenda1/README.md: -------------------------------------------------------------------------------- 1 | # Simple version of an agenda without contacts 2 | 3 | This example is focused on the class 4 | [**Event**](src/Event.java) 5 | that will use objects of the class 6 | [**Timestamp**](src/Timestamp.java) 7 | as attributes, and will use them to create objects 8 | of the class 9 | [**TimeDelta**](src/TimeDelta.java) 10 | to compute the duration of an event. 11 | 12 | 13 | * [**Timestamp**](src/Timestamp.java) is a class for representing a time instant as an absolute reference using year, month, day of month, hour, minutes and seconds. 14 | * [**TimeDelta**](src/TimeDelta.java) is a class for representing a lapse of time; useful for representing the duration of an event. 15 | * [**Event**](src/Event.java) is a class for representing an event as the ones we can have in our agendas, with starting and ending times, title or description and location. For simplifying this example will not include the list of expected attendants to an event. 16 | 17 | In order to illustrate the use of packages, the above ***data*** classes will be included in a package named **etsinf.prg.agenda1**. The main program for testing these classes will be outside the package, 18 | in the class 19 | [**TestingAgenda1**](test_src/TestingAgenda1.java), 20 | hence you will have the opportunity of seeing an example of how to import a package not provided by the JDK. 21 | 22 | Additionally, the package will be integrated in a JAR file, and it will be provided the example of how to run a Java program including packages available in JAR files. 23 | 24 | The scripts to compile and run the example illustrate how 25 | to create a JAR file and how to reference JAR files to 26 | compile classes which use the package, and how to invoke 27 | the JVM to use packages stored in JAR files. 28 | 29 | Scripts to compile and run examples, and to generate 30 | the documentation and clean all the stuff, 31 | can be found [here](scripts). 32 | -------------------------------------------------------------------------------- /code/loops/Triangles.java: -------------------------------------------------------------------------------- 1 | import java.util.Locale; 2 | import java.util.Scanner; 3 | 4 | public class Triangles 5 | { 6 | private static Scanner input = new Scanner(System.in).useLocale(Locale.US); 7 | 8 | public static void main(String [] args) 9 | { 10 | int height = 10; 11 | int offset = 0; 12 | 13 | for (int i = 0; i < args.length; i++) { 14 | if (args[i].equals("-h")) { 15 | height = Integer.parseInt(args[i+1]); 16 | } else if (args[i].equals("-o")) { 17 | offset = Integer.parseInt(args[i+1]); 18 | } 19 | } 20 | 21 | triangle_a(height, offset); 22 | triangle_b(height, offset); 23 | triangle_up(height, offset); 24 | triangle_down(height - 1, offset + 1); 25 | } 26 | 27 | public static void line(int n, char symbol) 28 | { 29 | while (--n >= 0) System.out.print(symbol); 30 | } 31 | public static void triangle_a(int h, int o) 32 | { 33 | for (int row = 1; row <= h; row++) { 34 | line(o + h - row, ' '); 35 | line(row, '*'); 36 | System.out.println(); 37 | } 38 | } 39 | public static void triangle_b(int h, int o) 40 | { 41 | for (int row = 1; row <= h; row++) { 42 | line(o, ' '); 43 | line(row, '*'); 44 | System.out.println(); 45 | } 46 | } 47 | public static void triangle_up(int h, int o) 48 | { 49 | for (int row = 1; row <= h; row++) { 50 | line(o + h - row, ' '); 51 | line(2 * row - 1, '*'); 52 | System.out.println(); 53 | } 54 | } 55 | public static void triangle_down(int h, int o) 56 | { 57 | for (int row = h; row >= 1; row--) { 58 | line(o + h - row, ' '); 59 | line(2 * row - 1, '*'); 60 | System.out.println(); 61 | } 62 | } 63 | } -------------------------------------------------------------------------------- /code/inheritance/Point2D.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Class to represent points in the 2-dimensional space. 3 | * 4 | * @author jon@upv.es 5 | * @version 2021-04 6 | */ 7 | 8 | public class Point2D { 9 | /** 10 | * Static constant (final variable) indicating the dimensionality 11 | * of the objects of this class. 12 | */ 13 | public final static int DIMENSION = 2; 14 | 15 | /* attributes of this class (instance variables) */ 16 | /** Coordinate for X-axis or abscissas. */ 17 | private double x; 18 | /** Coordinate for Y-axis or ordinates. */ 19 | private double y; 20 | 21 | /** 22 | * Default constructor. 23 | * Creates an object corresponding to origin of coordinates in the plane. 24 | */ 25 | public Point2D() { 26 | } 27 | 28 | /** 29 | * Generic constructor. 30 | * Creates an object for representing the point in the plane specified 31 | * by the parameters. 32 | * 33 | * @param x Value for the abscissas. 34 | * @param y Value for the ordinates. 35 | */ 36 | public Point2D(double x, double y) { 37 | this.x = x; 38 | this.y = y; 39 | } 40 | 41 | /** 42 | * Gets the value of the attribute x. 43 | * 44 | * @return The value of x. 45 | */ 46 | public double getX() { 47 | return x; 48 | } 49 | 50 | /** 51 | * Gets the value of the attribute y. 52 | * 53 | * @return The value of y. 54 | */ 55 | public double getY() { 56 | return y; 57 | } 58 | 59 | /** 60 | * Returns an String as representation of the object. 61 | * 62 | * @return The representation of this object. 63 | */ 64 | public String toString() { 65 | return String.format("(%.3f, %.3f)", x, y); 66 | } 67 | 68 | public double r() { 69 | return Math.sqrt(x * x + y * y); 70 | } 71 | 72 | public double atan() { 73 | return Math.atan2(y, x); 74 | } 75 | } -------------------------------------------------------------------------------- /code/recursion/NaturalNumbers.java: -------------------------------------------------------------------------------- 1 | 2 | public class NaturalNumbers 3 | { 4 | public static void main(String [] args) 5 | { 6 | int n = 10; 7 | 8 | for (int i = 0; i < args.length; i++) { 9 | if (args[i].equals("-n")) 10 | n = Integer.parseInt(args[i+1]); 11 | } 12 | 13 | naturalNumbers(n); 14 | System.out.println(); 15 | reverseNaturalNumbers(n); 16 | System.out.println(); 17 | symmetricSequence(n); 18 | System.out.println(); 19 | } 20 | 21 | /* 22 | if n == 1: print(1) 23 | if n > 1: naturalNumbers(n - 1); print(n) 24 | */ 25 | private static void naturalNumbers(int n) 26 | { 27 | if (n == 1) { // trivial case 28 | System.out.print(1); 29 | } else { 30 | // general case 31 | naturalNumbers(n - 1); // recursive call 32 | System.out.print(" " + n); // backward path 33 | } 34 | } 35 | 36 | /* 37 | if n == 1: print(1) 38 | if n > 1: print(n); reverseNaturalNumbers(n - 1) 39 | */ 40 | private static void reverseNaturalNumbers(int n) 41 | { 42 | if (n == 1) { // trivial case 43 | System.out.print(1); 44 | } else { 45 | // general case 46 | System.out.print(n + " "); // forward path 47 | reverseNaturalNumbers(n - 1); // recursive call 48 | } 49 | } 50 | 51 | /* 52 | if n == 0: print(0) 53 | if n > 0: print(n); symmetricSequence(n - 1); print(n) 54 | */ 55 | private static void symmetricSequence(int n) 56 | { 57 | if (n == 0) { // trivial case 58 | System.out.print(0); 59 | } else { 60 | // general case 61 | System.out.print(n + " "); // forward path 62 | symmetricSequence(n - 1); // recursive call 63 | System.out.print(" " + n); // backward path 64 | } 65 | } 66 | } -------------------------------------------------------------------------------- /cpr/cpp/greatestCommonDivisor.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | /* 5 | Euclides algorithm for computing gcd(a,b) and x,y such that a*x + b*y = gcd(a, b) 6 | */ 7 | #define LOCAL_DEBUG 8 | 9 | #if defined( LOCAL_DEBUG ) 10 | #include 11 | #endif 12 | 13 | int gcd(int a, int b, int *x, int *y) 14 | { 15 | int g, x1, y1; 16 | 17 | #if defined(LOCAL_DEBUG) 18 | printf("=> gcd( %d, %d )\n", a, b); 19 | #endif 20 | 21 | if (b > a) 22 | return gcd(b, a, y, x); 23 | 24 | if (b == 0) 25 | { 26 | *x = 1; 27 | *y = 0; 28 | #if defined(LOCAL_DEBUG) 29 | printf("<= x = %d y = %d \n", *x, *y); 30 | #endif 31 | return a; 32 | } 33 | 34 | g = gcd(b, a % b, &x1, &y1); 35 | 36 | *x = y1; 37 | *y = (x1 - std::floor(a / b) * y1); 38 | 39 | #if defined(LOCAL_DEBUG) 40 | printf("<= x = %d y = %d \n", *x, *y); 41 | #endif 42 | 43 | return g; 44 | } 45 | 46 | /* 47 | a b *x *y x' y' g 48 | ------------------------------------------- 49 | 4 6 -1 1 -- -- 50 | 6 4 1 -1 0 1 2 51 | 4 2 0 1 1 0 2 52 | 2 0 1 0 -- -- 2 53 | 54 | a b *x *y x' y' g 55 | ------------------------------------------- 56 | 17 14 5 -6 -1 5 1 57 | 14 3 -1 5 1 -1 1 58 | 3 2 1 -1 0 1 1 59 | 2 1 0 1 1 0 1 60 | 1 0 1 0 -- -- 1 61 | */ 62 | 63 | /* 64 | a * x + b * y = gcd(a, b) 65 | b * x1 + a' * y1 = gcd(a, b) 66 | 67 | a * x + b * y = b * x1 + a' * y1 68 | 69 | - De la llamada recursiva tenemos calculados x1 e y1 70 | - Sabemos que a' = a mod b, 71 | - Sabemos que x = y1, entonces 72 | 73 | a * y1 + b * y = b * x1 + (a - b * floor(a / b) * y1 74 | 75 | - Dividimos por b 76 | 77 | a / b * y1 + y = x1 + (a / b - floor(a / b)) * y1 78 | y = x1 + (a/b - floor(a / b)) * y1 - a / b * y1 79 | y = x1 - floor(a / b) * y1 80 | */ -------------------------------------------------------------------------------- /cpr/java/Point2D.java: -------------------------------------------------------------------------------- 1 | 2 | package es.upv.etsinf.geometry; 3 | 4 | public class Point2D 5 | implements Comparable 6 | { 7 | final public static double EPSILON = 1.0e-5; 8 | 9 | final private double x, y; 10 | 11 | public Point2D( double x, double y ) 12 | { 13 | this.x = x; 14 | this.y = y; 15 | } 16 | 17 | public double getX() { return x; } 18 | public double getY() { return y; } 19 | 20 | public double distanceFrom( Point2D other ) 21 | { 22 | double dx = this.x - other.x; 23 | double dy = this.y - other.y; 24 | 25 | return Math.sqrt( dx*dx + dy*dy ); 26 | } 27 | 28 | public boolean isInferior( Point2D other ) 29 | { 30 | return this.y < other.y 31 | || ( this.y == other.y && this.x < other.x ); 32 | // || ( Math.abs( this.y - other.y ) <= EPSILON && this.x < other.x ); 33 | } 34 | 35 | public int compareTo( Object o ) 36 | { 37 | if ( o instanceof Point2D ) { 38 | 39 | Point2D other = (Point2D)o; 40 | if ( this.x < other.x ) return -1; 41 | if ( this.x > other.x ) return 1; 42 | if ( this.y < other.y ) return -1; 43 | if ( this.y > other.y ) return 1; 44 | return 0; 45 | } 46 | 47 | return -1; 48 | } 49 | 50 | @Override 51 | public boolean equals( Object o ) 52 | { 53 | if ( o instanceof Point2D ) { 54 | Point2D other = (Point2D)o; 55 | 56 | return ( Math.abs( this.x - other.x ) <= EPSILON 57 | && Math.abs( this.y - other.y ) <= EPSILON ); 58 | 59 | } else { 60 | return false; 61 | } 62 | } 63 | 64 | @Override 65 | public Object clone() 66 | { 67 | Point2D p = new Point2D( this.x, this.y ); 68 | 69 | return p; 70 | } 71 | 72 | @Override 73 | public String toString() 74 | { 75 | return String.format( java.util.Locale.US, "(%.3f,%.3f)", x, y ); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /code/conditionals/NewSDE.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class NewSDE 4 | { 5 | public static void main(String [] args) 6 | { 7 | Scanner input = new Scanner(System.in).useLocale(Locale.US); 8 | 9 | System.out.print("\n Type the value for A: " ); double a = input.nextDouble(); 10 | System.out.print("\n Type the value for B: " ); double b = input.nextDouble(); 11 | System.out.print("\n Type the value for C: " ); double c = input.nextDouble(); 12 | System.out.println("\n"); 13 | 14 | if (a == 0) { 15 | if (b == 0) { 16 | if (c == 0) { 17 | // a == 0 && b == 0 && c == 0 18 | System.out.println("Infinite solutions: any value of the unknown satisfies the equation."); 19 | } else { 20 | // a == 0 && b == 0 && c != 0 21 | System.out.println("Absurd: no valid values of coefficients."); 22 | } 23 | } else { 24 | // a == 0 && b != 0 25 | double x = -c / b; 26 | if (Math.abs(x) < 1.0e-7) x = Math.abs(x); 27 | System.out.printf(Locale.US, "It is a first degree equation whose solution is x = %.4f\n", x); 28 | } 29 | } else { 30 | double sqrt_argument = b * b - 4 * a * c; 31 | if (sqrt_argument > 0.0) { 32 | // two real solutions 33 | 34 | double sqrt = Math.sqrt(sqrt_argument); 35 | double x1 = (-b + sqrt) / (2 * a); 36 | double x2 = (-b - sqrt) / (2 * a); 37 | System.out.printf(Locale.US, "Values for x are: %.4f and %.4f\n", x1, x2); 38 | 39 | } else if (Math.abs(sqrt_argument) < 1.0e-7) { 40 | // a double real solution 41 | 42 | double x = (-b) / (2 * a); 43 | System.out.printf(Locale.US, "Double real solution: value for x is: %.4f\n", x); 44 | 45 | } else { 46 | // two complex solutions 47 | double sqrt = Math.sqrt(-sqrt_argument); 48 | double real = (-b) / (2 * a); 49 | double imag = Math.abs((sqrt) / (2 * a)); 50 | 51 | System.out.printf("Two complex solutions:\n"); 52 | System.out.printf(Locale.US, "\t %.4f + %.4fi\n", real, imag); 53 | System.out.printf(Locale.US, "\t %.4f - %.4fi\n", real, imag); 54 | } 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /cpr/java/AllPermutations.java: -------------------------------------------------------------------------------- 1 | 2 | package es.upv.etsinf.backtraking; 3 | 4 | import java.util.Vector; 5 | 6 | class AllPermutations 7 | { 8 | private boolean completed; // In this example is not used because all permutations should be generated. 9 | private boolean [] used; 10 | private int n; 11 | private int [] solution; 12 | 13 | private boolean isSolution(int k) 14 | { 15 | return (k == n); 16 | } 17 | private Vector buildCandidates(int k) 18 | { 19 | Vector candidates = new Vector(); 20 | 21 | for (int i = 1; i <= n; i++) { 22 | if (! used[i]) candidates.add(i); 23 | } 24 | 25 | return candidates; 26 | } 27 | private void processSolution(int k) 28 | { 29 | System.out.print("{"); 30 | for (int i = 1; i <= k; i++) { 31 | System.out.print(" " + solution[i]); 32 | } 33 | System.out.println(" }"); 34 | } 35 | 36 | private void backtrack(int k) 37 | { 38 | if (isSolution(k)) { 39 | 40 | processSolution(k); 41 | 42 | } else { 43 | 44 | k++; 45 | Vector candidates = buildCandidates(k); 46 | for(int value : candidates) { 47 | solution[k] = value; 48 | used[value] = true; 49 | backtrack(k); 50 | used[value] = false; 51 | if (completed) return; 52 | } 53 | solution[k] = 0; 54 | } 55 | } 56 | 57 | public void generatePermutations(int n) 58 | { 59 | this.n = n; 60 | this.completed = false; 61 | this.used = new boolean [n + 1]; 62 | this.solution = new int [n + 1]; 63 | 64 | backtrack(0); 65 | } 66 | 67 | public static void main(String [] args) 68 | { 69 | AllPermutations ap = new AllPermutations(); 70 | 71 | int n = 3; 72 | 73 | if (args.length > 0) n = Integer.parseInt(args[0]); 74 | 75 | ap.generatePermutations(n); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /code/conditionals/PaperStoneScissors.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class PaperStoneScissors 4 | { 5 | public static void main(String [] args) 6 | { 7 | Scanner input = new Scanner(System.in); 8 | 9 | System.out.print("Please, provide your option: "); 10 | String userOption = input.nextLine().trim().toLowerCase(); 11 | String computerOption = generateComputerOption().toLowerCase(); 12 | 13 | String result = null; 14 | switch (userOption) { 15 | case "paper": 16 | switch (computerOption) { 17 | case "paper": result = "tied!!!"; break; 18 | case "stone": result = "User wins!!!"; break; 19 | case "scissors": result = "Computer wins!"; break; 20 | } 21 | break; 22 | case "stone": 23 | switch (computerOption) { 24 | case "paper": result = "Computer wins!"; break; 25 | case "stone": result = "tied!!!"; break; 26 | case "scissors": result = "User wins!!!"; break; 27 | } 28 | break; 29 | case "scissors": 30 | switch (computerOption) { 31 | case "paper": result = "User wins!!!"; break; 32 | case "stone": result = "Computer wins!"; break; 33 | case "scissors": result = "tied!!!"; break; 34 | } 35 | break; 36 | default: 37 | System.out.println("You entered an invalid option!"); 38 | } 39 | if (result != null) System.out.println(result); 40 | } 41 | 42 | public static String generateComputerOption() 43 | { 44 | String option = null; 45 | 46 | switch ((int)(3 * Math.random())) { 47 | case 0: option = "Scissors"; break; 48 | case 1: option = "Paper"; break; 49 | case 2: option = "Stone"; break; 50 | default: System.out.println("IMPOSSIBLE!"); 51 | System.exit(1); 52 | } 53 | return option; 54 | } 55 | } -------------------------------------------------------------------------------- /code/exams_from_previous_years/SaveArea.java: -------------------------------------------------------------------------------- 1 | 2 | public class SaveArea 3 | { 4 | public static final int MAX_STORED = 100; 5 | 6 | private int size; 7 | private SaveGame [] storedGames; 8 | 9 | 10 | public SaveArea() 11 | { 12 | size = 0; 13 | storedGames = new SaveGame[MAX_STORED]; 14 | } 15 | 16 | public void removeTheOldestOne() 17 | { 18 | storedGames[0].setPosition(-1); 19 | 20 | for (int i = 1; i < size; i++) { 21 | 22 | storedGames[i-1] = storedGames[i]; 23 | storedGames[i-1].setPosition(i - 1); 24 | } 25 | //storedGames[--size] = null; 26 | size--; 27 | storedGames[size] = null; 28 | } 29 | 30 | public boolean withAProgressGreaterThanOrEqualTo(SaveGame sg) 31 | { 32 | boolean found = false; 33 | 34 | for (int i = 0; i < size && !found; i++) { 35 | if (storedGames[i].getIdentifier == sg.getIdentifier()) { 36 | if (storedGames[i].getProgress() > sg.getProgress()) { 37 | found = true; 38 | } 39 | } 40 | } 41 | 42 | return found; 43 | } 44 | 45 | public boolean save(SaveGame sg) 46 | { 47 | if (! withAProgressGreaterThanOrEqualTo(sg)) { 48 | 49 | if (size == storedGames.length) removeTheOldestOne(); 50 | 51 | sg.setPosition(size); 52 | 53 | storedGames[size++] = sg; 54 | 55 | return true; 56 | 57 | } else { 58 | 59 | return false; 60 | } 61 | } 62 | 63 | public SaveGame [] filterByRegion(String region) 64 | { 65 | int counter = 0; 66 | for (int i = 0; i < size; i++) { 67 | 68 | if (storedGames[i].getRegion().equals(region)) counter++; 69 | } 70 | 71 | SaveGame [] result = new SaveGame [counter]; 72 | int k = 0; 73 | 74 | for (int i = 0; i < size; i++) { 75 | 76 | if (storedGames[i].getRegion().equals(region)) 77 | result[k++] = storedGames[i]; 78 | } 79 | 80 | return result; 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /cpr/java/NQueens.java: -------------------------------------------------------------------------------- 1 | 2 | package es.upv.etsinf.backtraking; 3 | 4 | class NQueens 5 | { 6 | private boolean completed; // not used here because the goal is to count valid solutions 7 | private int n; 8 | private int numSolutions; 9 | private int [] solution; 10 | 11 | public NQueens() 12 | { 13 | numSolutions = 0; 14 | } 15 | 16 | private boolean isSolution(int k) 17 | { 18 | return (k == n); 19 | } 20 | /* 21 | This method performs the bound implicitly by checking which cells are 22 | free to set a queen. 23 | 24 | This method returns the valid positions in the k-th row. 25 | */ 26 | private void buildCandidates(int k, boolean [] possibleNextSteps) 27 | { 28 | for (int i = 0; i < n; i++) { 29 | 30 | boolean legal = true; 31 | 32 | for (int j = 0; j < k && legal; j++) { 33 | if (i == solution[j]) legal = false; 34 | if (Math.abs(k - j) == Math.abs(i - solution[j])) legal = false; 35 | } 36 | possibleNextSteps[i] = legal; 37 | } 38 | } 39 | private void processSolution() 40 | { 41 | numSolutions++; 42 | } 43 | 44 | private void backtrack(int k) 45 | { 46 | if (isSolution(k)) { 47 | 48 | processSolution(); 49 | 50 | } else { 51 | 52 | boolean [] possibleNextSteps = new boolean [n]; 53 | 54 | buildCandidates(k, possibleNextSteps); 55 | for (int i = 0; i < possibleNextSteps.length; i++) { 56 | if (possibleNextSteps[i]) { 57 | solution[k] = i; 58 | backtrack(k + 1); 59 | solution[k] = -1; 60 | } 61 | if (completed) return; 62 | } 63 | } 64 | } 65 | 66 | public void computeSolutions(int n) 67 | { 68 | this.n = n; 69 | this.completed = false; 70 | this.numSolutions = 0; 71 | this.solution = new int [n]; 72 | 73 | backtrack(0); 74 | } 75 | public int numSolutions() 76 | { 77 | return numSolutions; 78 | } 79 | 80 | public static void main(String [] args) 81 | { 82 | NQueens chessBoard = new NQueens(); 83 | 84 | int n = 8; 85 | 86 | if (args.length > 0) n = Integer.parseInt(args[0]); 87 | 88 | chessBoard.computeSolutions(n); 89 | 90 | System.out.println(chessBoard.numSolutions()); 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /examples/covid_19/test_src/TestingCovid19.java: -------------------------------------------------------------------------------- 1 | import etsinf.prg.covid19.*; 2 | 3 | /** 4 | * Class for testing the different functionalities provided by the classes 5 | * included in the package agenda1. 6 | */ 7 | public class TestingCovid19 8 | { 9 | public static void main(String [] args) 10 | { 11 | Timestamp now = new Timestamp(); 12 | System.out.println(); 13 | System.out.println("Current time is " + now); 14 | System.out.println(); 15 | 16 | Dataset dataset = new Dataset("data/owid-covid-data.csv"); 17 | 18 | System.out.println("Loaded " + dataset.getSize() + " days."); 19 | 20 | System.out.println(); 21 | 22 | Dataset spain = dataset.filterByCountry("ESP"); 23 | Dataset france = dataset.filterByCountry("FRA"); 24 | Dataset germany = dataset.filterByCountry("DEU"); 25 | 26 | System.out.println("Spanish dataset contains " + spain.getSize() + " days."); 27 | System.out.println("French dataset contains " + france.getSize() + " days."); 28 | System.out.println("German dataset contains " + germany.getSize() + " days."); 29 | 30 | System.out.println(); 31 | 32 | Day d = dataset.maxCases(); 33 | System.out.println("Day with most cases.: " + d); 34 | d = dataset.maxDeaths(); 35 | System.out.println("Day with most deaths: " + d); 36 | 37 | System.out.println(); 38 | 39 | d = spain.maxCases(); 40 | System.out.println("Day with most cases in Spain: " + d); 41 | d = spain.maxDeaths(); 42 | System.out.println("Day with most deaths in Spain: " + d); 43 | 44 | System.out.println(); 45 | 46 | d = france.maxCases(); 47 | System.out.println("Day with most cases in France: " + d); 48 | d = france.maxDeaths(); 49 | System.out.println("Day with most deaths in France: " + d); 50 | 51 | System.out.println(); 52 | 53 | d = germany.maxCases(); 54 | System.out.println("Day with most cases in Germany: " + d); 55 | d = germany.maxDeaths(); 56 | System.out.println("Day with most deaths in Germany: " + d); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /code/inheritance/Point3D.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | /** 4 | Class to represent points in the 3-dimensional space extending 5 | the Point2D class. 6 | 7 | @author jon@upv.es 8 | @version 2021-04 9 | */ 10 | 11 | public class Point3D extends Point2D 12 | { 13 | /** 14 | Static constant (final variable) indicating the dimensionality 15 | of the objects of this class. 16 | */ 17 | public final static int DIMENSION = 3; 18 | 19 | /* attributes of this class (instance variables) */ 20 | /** Coordinate for Z-axis or abscissas. */ 21 | private double z; 22 | 23 | /** 24 | Default constructor. 25 | Creates an object corresponding to origin of coordinates in the plane. 26 | */ 27 | public Point3D() 28 | { 29 | super(); 30 | } 31 | 32 | /** 33 | Generic constructor. 34 | Creates an object for representing the point in the plane specified 35 | by the parameters. 36 | 37 | @param x Value for the x axis. 38 | @param y Value for the y axis. 39 | @param z Value for the z axis. 40 | */ 41 | public Point3D(double x, double y, double z) 42 | { 43 | super(x, y); 44 | this.z = z; 45 | } 46 | 47 | /** Gets the value of the attribute z. 48 | @return The value of z. 49 | */ 50 | public double getZ() { return this.z; } 51 | 52 | /** Returns an String as representation of the object. 53 | @return The representation of this object. 54 | */ 55 | @Override 56 | public String toString() 57 | { 58 | return String.format("(%.3f, %.3f, %.3f)", 59 | this.getX(), 60 | this.getY(), 61 | z); 62 | } 63 | 64 | @Override 65 | public double r() 66 | { 67 | return Math.sqrt(super.getX() * super.getX() 68 | + super.getY() * super.getY() 69 | + z * z); 70 | } 71 | /* 72 | This method must be used from the parent class with caution. 73 | public double atan() 74 | { 75 | return Math.atan2(y, x); 76 | } 77 | */ 78 | } 79 | -------------------------------------------------------------------------------- /cpr/java/NetworkFlow.java: -------------------------------------------------------------------------------- 1 | package es.upv.etsinf.graphs; 2 | 3 | import java.util.*; 4 | 5 | public class NetworkFlow 6 | extends GraphOperations 7 | { 8 | public NetworkFlow(Graph g) 9 | { 10 | super(g); 11 | } 12 | 13 | public void processVertex(Vertex v) 14 | { 15 | } 16 | 17 | public void processEdge(Edge e) 18 | { 19 | } 20 | 21 | // Net Flow 22 | public void run(Vertex source, Vertex sink) 23 | { 24 | addResidualEdges(); 25 | 26 | initializeSearch(); 27 | bfs(source); 28 | 29 | if (g.adjacency == null) 30 | g.generateAdjacencyMatrix(); 31 | 32 | double volume = pathVolume(source, sink); 33 | 34 | while (volume > 0.0) { 35 | augmentPath(source, sink, volume); 36 | initializeSearch(); 37 | bfs(source); 38 | volume = pathVolume(source, sink); 39 | } 40 | 41 | // For the problem of robots, a bipartite matching problem, 42 | // the result should be the sum of the flow of each edge from source 43 | } 44 | 45 | public void addResidualEdges() 46 | { 47 | } 48 | 49 | public boolean validEdge(Edge e) 50 | { 51 | return e != null && e.getResidual() > 0.0; 52 | } 53 | 54 | public double pathVolume(Vertex start, Vertex end) 55 | { 56 | if (parent[end.getId()] == null) 57 | return 0.0; 58 | 59 | Edge e = g.findEdge(parent[end.getId()], end); 60 | 61 | if (start == parent[end.getId()]) 62 | return e.getResidual(); 63 | else 64 | return Math.min(pathVolume(start, parent[end.getId()]), e.getResidual()); 65 | } 66 | 67 | public void augmentPath(Vertex start, Vertex end, double volume) 68 | { 69 | if (start != end) { 70 | 71 | Edge e = g.findEdge(parent[end.getId()], end); 72 | 73 | e.setFlow(e.getFlow() + volume); 74 | e.setResidual(e.getResidual() - volume); 75 | 76 | e = g.findEdge(end, parent[end.getId()]); 77 | e.setResidual(e.getResidual() + volume); 78 | 79 | augmentPath(start, parent[end.getId()], volume); 80 | } 81 | } 82 | } -------------------------------------------------------------------------------- /code/basic/Rectangle.java: -------------------------------------------------------------------------------- 1 | import org.w3c.dom.css.Rect; 2 | 3 | public class Rectangle { 4 | 5 | private Point centre; 6 | private double height, base; 7 | 8 | public Rectangle() { 9 | height = base = 1; 10 | centre = new Point(50, 50); 11 | } 12 | 13 | public Rectangle(double h, double b, double x, double y) { 14 | height = h; 15 | base = b; 16 | centre = new Point(x, y); 17 | } 18 | 19 | public Rectangle(Point llc, Point urc) { 20 | height = Math.abs(urc.getY() - llc.getY()); 21 | base = Math.abs(urc.getX() - llc.getX()); 22 | centre = new Point((llc.getX() + urc.getX()) / 2.0, (llc.getY() + urc.getY()) / 2.0); 23 | } 24 | 25 | public Point getCentre() { return centre; } 26 | public double getHeight() { return height; } 27 | public double getBase() { return base; } 28 | 29 | public void setCentre(double x, double y) { 30 | centre = new Point(x, y); 31 | } 32 | public void setHeight(double h) { height = h; } 33 | public void setBase(double b) { base = b; } 34 | 35 | public double getArea() { return base * height; } 36 | 37 | public Point getLowerLeftCorner() { 38 | return new Point(centre.getX() - base / 2, centre.getY() - height / 2); 39 | } 40 | public Point getUpperRightCorner() { 41 | return new Point(centre.getX() + base / 2, centre.getY() + height / 2); 42 | } 43 | 44 | @Override 45 | public String toString() { 46 | return "Rectangle centred at " 47 | + centre.toString() 48 | + " with base = " + base + " m" 49 | + " and height " + height + " m"; 50 | } 51 | 52 | @Override 53 | public boolean equals(Object o) { 54 | if (o instanceof Rectangle) { // Check o is an object of the class Rectangle 55 | Rectangle other = (Rectangle)o; // Refer to it as an object of the class Rectangle 56 | 57 | return this.centre.equals(other.centre) 58 | && Math.abs(this.base - other.base) <= Point.EPSILON 59 | && Math.abs(this.height - other.height) <= Point.EPSILON; 60 | } else { 61 | return false; 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /code/recursion/Exam20180619.java: -------------------------------------------------------------------------------- 1 | 2 | public class Exam20180619 3 | { 4 | public static void main(String [] args) 5 | { 6 | double [] a = {-7.4, -1.3, 0.0, 1.8, 2.3, 3.6}; 7 | double [] b = {-7.4, -1.3, 1.8, 2.6, 3.6}; 8 | 9 | System.out.print("contents of array 'a':"); 10 | for (double d : a) System.out.print(" " + d); 11 | System.out.println(); 12 | System.out.print("contents of array 'a':"); 13 | for (double d : b) System.out.print(" " + d); 14 | System.out.println(); 15 | System.out.println(); 16 | 17 | int pos = findIntercept(a); 18 | if (pos >= 0) 19 | System.out.printf("Intercept found at position %3d in array a.\n", pos); 20 | else 21 | System.out.printf("Intercept NOT found within array a.\n", pos); 22 | pos = findIntercept(b); 23 | if (pos >= 0) 24 | System.out.printf("Intercept found at position %3d in array b.\n", pos); 25 | else 26 | System.out.printf("Intercept NOT found within array b.\n", pos); 27 | } 28 | 29 | /* 30 | preconditions: 31 | array sorted in ascending order 32 | initial value for left it is assumed to be zero 33 | initial value for right it is assumed to be v.length -1 34 | 35 | trivial case: 36 | with the slice of the array defined by left and right is empty, 37 | i.e., right - left + 1 == 0 38 | 39 | general case: 40 | left <= right 41 | */ 42 | private static int findIntercept(double [] v, int left, int right) 43 | { 44 | if (left > right) 45 | return -1; 46 | else { 47 | int k = (left + right) / 2; 48 | if (v[k] == 0.0) { // Math.abs(v[k] - x) < epsilon :: epsilon can be 1.0e-9 49 | return k; 50 | } else if (v[k] < 0.0) { 51 | return findIntercept(v, k + 1, right); 52 | } else { 53 | return findIntercept(v, left, k - 1); 54 | } 55 | } 56 | } 57 | // wrapper method 58 | private static int findIntercept(double [] v) 59 | { 60 | return findIntercept(v, 0, v.length - 1); 61 | } 62 | } -------------------------------------------------------------------------------- /cpr/java/fsa/Vertex.java: -------------------------------------------------------------------------------- 1 | package es.upv.etsinf.fsa; 2 | 3 | import java.util.*; 4 | 5 | public class Vertex 6 | { 7 | /** Subsequence of symbols to reach this vertex from the root. 8 | * It should be null for root vertex of the tree. 9 | */ 10 | private String w; 11 | 12 | /** Linked list of completed patterns when this vertex is reached. */ 13 | private LinkedList reached; 14 | 15 | /** Hash table with the reachable vertices from the current one. */ 16 | private Hashtable edges; 17 | 18 | /** Creates a new vertex given an string. 19 | * 20 | * @param w The subsequence of symbols reaching this vertex. 21 | */ 22 | public Vertex(String w) 23 | { 24 | this.w = w; 25 | this.edges = new Hashtable(); 26 | this.reached = new LinkedList(); 27 | } 28 | 29 | /** Returns the subsequence of the current vertex. 30 | * 31 | * @return An object of the class String. 32 | */ 33 | public String getSubsequence() 34 | { 35 | return w; 36 | } 37 | 38 | public LinkedList getReached() 39 | { 40 | return this.reached; 41 | } 42 | 43 | public boolean isTerminal() { return reached.size() > 0; } 44 | public void add(Object p) { reached.add(p); } 45 | 46 | /** Connects the current vertex with another one using the symbol. 47 | * 48 | * @param symbol The symbol used to reach the next vertex from this one. 49 | * @param next The vertex reached from this one after consuming the symbol. 50 | */ 51 | public void connect(char symbol, Vertex next) 52 | { 53 | if (this.edges.containsKey(symbol)) 54 | throw new RuntimeException("Trying to add a new edge using an existing symbol " + symbol); 55 | 56 | this.edges.put(symbol, next); 57 | } 58 | 59 | /** Returns the vertex reached from the current one consuming the symbol. 60 | * If the symbol is not a valid key in edges null is returned. 61 | * 62 | * @return An object of the class Vertex. 63 | */ 64 | public Vertex getNext(char symbol) 65 | { 66 | return this.edges.get(symbol); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /code/linear-data-structures/src/LinkedSequences.java: -------------------------------------------------------------------------------- 1 | package linear; 2 | 3 | public class LinkedSequences 4 | { 5 | public static NodeInt insert(int value, NodeInt first, NodeInt previous) 6 | { 7 | if (first == null) { 8 | first = new NodeInt(value); 9 | } else if (previous != null) { 10 | previous.setNext(new NodeInt(value, previous.getNext())); 11 | } else { 12 | return new NodeInt(value, first); 13 | } 14 | return first; 15 | } 16 | public static NodeInt append(int value, NodeInt first) 17 | { 18 | if (first == null) 19 | return new NodeInt(value); 20 | else { 21 | NodeInt previous = first; 22 | NodeInt current = previous.getNext(); 23 | while (current != null) { 24 | previous = current; 25 | current = current.getNext(); 26 | } 27 | previous.setNext(new NodeInt(value)); 28 | return first; 29 | } 30 | } 31 | 32 | public static NodeInt remove(NodeInt first, NodeInt previous) 33 | { 34 | if (first == null) throw new Error("Patan, eres un patan"); 35 | 36 | if (previous != null) { 37 | if (previous.getNext() != null) 38 | previous.setNext(previous.getNext().getNext()); 39 | } else { 40 | first = first.getNext(); 41 | } 42 | 43 | return first; 44 | } 45 | 46 | public static NodeInt removeLastOne(NodeInt first) 47 | { 48 | if (first == null) throw new Error("Patan, eres un patan"); 49 | 50 | NodeInt previous = null; 51 | NodeInt current = first; 52 | while (current != null && current.getNext() != null) { 53 | previous = current; 54 | current = current.getNext(); 55 | } 56 | if (previous != null) previous.setNext(null); 57 | else first = null; 58 | 59 | return first; 60 | } 61 | 62 | public static void main(String [] args) 63 | { 64 | NodeInt first = null; 65 | 66 | first = LinkedSequences.insert(5, first, null); 67 | first = LinkedSequences.append(5, first); 68 | first = LinkedSequences.insert(5, null, first); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /code/arrays/Contact.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | 4 | public class Contact 5 | implements Serializable,Comparable // You have to believe this is correct! 6 | { 7 | private String lastname; 8 | private String name; 9 | private String email; 10 | private String phoneNumber; 11 | private Date birthDate; 12 | 13 | public Contact(String lastname, String name, String email, 14 | String phoneNumber, Date birthDate) 15 | { 16 | this.lastname = lastname; 17 | this.name = name; 18 | this.email = email; 19 | this.phoneNumber = phoneNumber; 20 | this.birthDate = birthDate.clone(); 21 | } 22 | 23 | public String getCanonicalName() 24 | { 25 | return lastname + ", " + name; 26 | } 27 | public String getLastName() { return lastname; } 28 | public String getName() { return name; } 29 | public String getEMail() { return email; } 30 | public String getPhoneNumber() { return phoneNumber; } 31 | public String getBirthDate() { return birthDate.toString(); } 32 | public int getAge(Date reference) { return birthDate.getAge(reference); } 33 | 34 | public Date getDateOfBirth() { return birthDate; } 35 | 36 | public int getMonthOfBirth() { return birthDate.getMonth(); } 37 | 38 | @Override 39 | public boolean equals(Object o) 40 | { 41 | if (o instanceof Contact) { 42 | Contact other = (Contact)o; 43 | 44 | return this.lastname.equals(other.lastname) 45 | && this.name.equals(other.name) 46 | // && this.email.equals(other.email) 47 | // && this.phoneNumber.equals(other.phoneNumber) 48 | && this.birthDate.equals(other.birthDate); 49 | } 50 | return false; 51 | } 52 | 53 | public int compareTo(Contact other) 54 | { 55 | return this.getCanonicalName().compareTo(other.getCanonicalName()); 56 | } 57 | 58 | @Override 59 | public String toString() 60 | { 61 | return String.format("%s %-30.30s %-20.20s %s", 62 | birthDate.toString(), 63 | getCanonicalName(), 64 | email, 65 | phoneNumber); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /code/exams_from_previous_years/2018-2019/WorkWithFiles1.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | 4 | 5 | public class WorkWithFiles1 6 | { 7 | public static void main(String [] args) 8 | throws FileNotFoundException 9 | { 10 | sumInt_v2("integers.in", "integers.out"); 11 | } 12 | 13 | 14 | public static void sumInt(String fileIn, String fileOut) 15 | throws FileNotFoundException 16 | { 17 | Scanner input = new Scanner(new File(fileIn)); 18 | PrintWriter output = new PrintWriter( 19 | new BufferedOutputStream( 20 | new FileOutputStream( 21 | new File(fileOut)))); 22 | int sum = 0; 23 | while (input.hasNext()) { 24 | try { 25 | int value = input.nextInt(); 26 | output.println(value); 27 | sum += value; 28 | } 29 | catch (InputMismatchException e) { 30 | output.printf("(Error: %s)\n", input.next()); 31 | } 32 | } 33 | output.println("Sum: " + sum); 34 | 35 | input.close(); 36 | output.close(); 37 | } 38 | 39 | public static void sumInt_v2(String fileIn, String fileOut) 40 | { 41 | Scanner input = null; 42 | PrintWriter output = null; 43 | try { 44 | input = new Scanner(new File(fileIn)); 45 | output = new PrintWriter(fileOut); 46 | int sum = 0; 47 | while (input.hasNext()) { 48 | try { 49 | int value = input.nextInt(); 50 | output.println(value); 51 | sum += value; 52 | } 53 | catch (InputMismatchException e) { 54 | output.printf("(Error: %s)\n", input.next()); 55 | } 56 | } 57 | output.println("Sum: " + sum); 58 | } 59 | catch (FileNotFoundException e) 60 | { 61 | System.err.println("Impossible to open a file. Maybe it does not exist!"); 62 | e.printStackTrace(System.err); 63 | } 64 | finally { 65 | if (input != null) input.close(); 66 | if (output != null) output.close(); 67 | } 68 | } 69 | } 70 | --------------------------------------------------------------------------------