diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..560aa4f2b --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,10 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" # See documentation for possible values + directory: "/" # Location of package manifests + schedule: + interval: "weekly" + - package-ecosystem: "gradle" + directory: "/" + schedule: + interval: "weekly" diff --git a/.github/workflows/code-formatting.yml b/.github/workflows/code-formatting.yml deleted file mode 100644 index c74863c7c..000000000 --- a/.github/workflows/code-formatting.yml +++ /dev/null @@ -1,28 +0,0 @@ -# This workflow checks that the code in the repo is formatted according to the -# Google Java Style Guide - -name: Code Formatting Check - -on: - push: - branches: [ master ] - pull_request: - branches: [ master ] - -jobs: - build: - - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v2 - - name: Set up JDK 1.8 - uses: actions/setup-java@v1 - with: - java-version: 1.8 - - name: Grant execute permission for gradlew - run: chmod +x gradlew - - name: Verify all Java files are formatted correctly according to the Google Java Style Guide - run: | - ./gradlew verifyGoogleJavaFormat - echo "Run the command './gradlew goJF' to fix Java formatting if this workflow fails" diff --git a/.github/workflows/gradle.yml b/.github/workflows/gradle.yml index ec6c6f2a5..ffd13a1b5 100644 --- a/.github/workflows/gradle.yml +++ b/.github/workflows/gradle.yml @@ -9,18 +9,56 @@ on: pull_request: branches: [ master ] +permissions: + checks: write + jobs: - build: + test: + name: Test + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - name: Set up JDK 11 + uses: actions/setup-java@v4 + with: + java-version: 11 + distribution: 'temurin' + - name: Validate Gradle Wrapper + uses: gradle/wrapper-validation-action@v3 + - name: Setup and execute tests via Gradle + uses: gradle/gradle-build-action@v3 + with: + gradle-version: wrapper + arguments: test + - name: Publish Test Results + if: ${{ always() }} + uses: mikepenz/action-junit-report@v3 + with: + report_paths: "**/TEST-*.xml" + exclude_sources: build/ + annotate_only: ${{ github.event_name == 'pull_request' }} + style-check: + name: Code Formatting Check runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - name: Set up JDK 1.8 - uses: actions/setup-java@v1 + - uses: actions/checkout@v3 + - name: Set up JDK 11 + uses: actions/setup-java@v4 + with: + java-version: 11 + distribution: 'temurin' + - name: Validate Gradle Wrapper + uses: gradle/wrapper-validation-action@v3 + - name: Verify all Java files are formatted correctly according to the Google Java Style Guide using Gradle + uses: gradle/gradle-build-action@v3 + id: verifygooglejavaformat with: - java-version: 1.8 - - name: Grant execute permission for gradlew - run: chmod +x gradlew - - name: Build with Gradle - run: ./gradlew test + gradle-version: wrapper + arguments: spotlessJavaCheck + - name: Create summary if format check failed + if: ${{ steps.verifygooglejavaformat.outcome == 'failure' }} + run: | + echo "Run the command `./gradlew spotlessApply` to fix Java formatting." >> $GITHUB_STEP_SUMMARY diff --git a/.github/workflows/readme-url-checker.yml b/.github/workflows/readme-url-checker.yml index 8b4784833..548349949 100644 --- a/.github/workflows/readme-url-checker.yml +++ b/.github/workflows/readme-url-checker.yml @@ -1,21 +1,20 @@ # Use awesome bot to verify that all URLs in the README are valid. - name: README URL Checker on: push: branches: [ master ] pull_request: branches: [ master ] - jobs: build: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v3 - name: Set up Ruby 2.6 - uses: actions/setup-ruby@v1 + uses: ruby/setup-ruby@v1 with: - ruby-version: 2.6.x + ruby-version: 3.0 + - name: Install Awesome Bot run: gem install awesome_bot - name: Run Awesome Bot diff --git a/.gitignore b/.gitignore index 105d695af..68c3443af 100644 --- a/.gitignore +++ b/.gitignore @@ -23,3 +23,6 @@ bin/ # Mac files .DS_Store .idea/ + +# Kotlin folder? +*/META-INF/* diff --git a/README.md b/README.md index 799730d1b..a42be2f99 100644 --- a/README.md +++ b/README.md @@ -9,11 +9,11 @@ Algorithms and data structures are fundamental to efficient code and good softwa # Contributing -This repository is contribution friendly :smiley:. If you'd like to add or improve an algorithm, your contribution is welcome! Please be sure to checkout the [Wiki](https://github.com/williamfiset/Algorithms/wiki) for instructions. +This repository is contribution friendly :smiley:. If you'd like to add or improve an algorithm, your contribution is welcome! Please be sure to check out the [Wiki](https://github.com/williamfiset/Algorithms/wiki) for instructions. ### Other programming languages? -This repository provides algorithm implementations in Java, however there are other forks that provide implementations in other languages, most notably: +This repository provides algorithm implementations in Java, however, there are other forks that provide implementations in other languages, most notably: * **C++/Python**: https://github.com/akzare/Algorithms * **Rust**: https://github.com/TianyiShi2001/Algorithms @@ -24,7 +24,7 @@ To compile and run any of the algorithms here, you need at least JDK version 8. ## Running with Gradle (recommended) -This project supports the [Gradle Wrapper](https://docs.gradle.org/current/userguide/gradle_wrapper.html). The Gradle wrapper automatically downloads Gradle at the first time it runs, so expect a delay when running the first command below. +This project supports the [Gradle Wrapper](https://docs.gradle.org/current/userguide/gradle_wrapper.html). The Gradle wrapper automatically downloads Gradle the first time it runs, so expect a delay when running the first command below. If you are on Windows, use `gradlew.bat` instead of `./gradlew` below. @@ -90,7 +90,6 @@ $ java -cp classes com.williamfiset.algorithms.search.BinarySearch - [Splay Tree](src/main/java/com/williamfiset/algorithms/datastructures/binarysearchtree/SplayTree.java) - [:movie_camera:](https://www.youtube.com/watch?v=PEnFFiQe1pM) [Dynamic Array](src/main/java/com/williamfiset/algorithms/datastructures/dynamicarray) - [Dynamic array (integer only, fast)](src/main/java/com/williamfiset/algorithms/datastructures/dynamicarray/IntArray.java) - - [Dynamic array (generic)](src/main/java/com/williamfiset/algorithms/datastructures/dynamicarray/DynamicArray.java) - [:movie_camera:](https://www.youtube.com/watch?v=RgITNht_f4Q) [Fenwick Tree](src/main/java/com/williamfiset/algorithms/datastructures/fenwicktree) - [Fenwick Tree (range query, point updates)](src/main/java/com/williamfiset/algorithms/datastructures/fenwicktree/FenwickTreeRangeQueryPointUpdate.java) - [Fenwick Tree (range update, point query)](src/main/java/com/williamfiset/algorithms/datastructures/fenwicktree/FenwickTreeRangeUpdatePointQuery.java) @@ -294,7 +293,7 @@ $ java -cp classes com.williamfiset.algorithms.search.BinarySearch - [Counting sort](src/main/java/com/williamfiset/algorithms/sorting/CountingSort.java) **- O(n + k)** - [Heapsort](src/main/java/com/williamfiset/algorithms/sorting/Heapsort.java) **- O(nlog(n))** - [Insertion sort](src/main/java/com/williamfiset/algorithms/sorting/InsertionSort.java) **- O(n2)** -- [Mergesort](src/main/java/com/williamfiset/algorithms/sorting/MergeSort.java) **- O(nlog(n))** +- [:movie_camera:](https://www.youtube.com/watch?v=-3u1C1URNZY) [Mergesort](src/main/java/com/williamfiset/algorithms/sorting/MergeSort.java) **- O(nlog(n))** - [Quicksort (in-place, Hoare partitioning)](src/main/java/com/williamfiset/algorithms/sorting/QuickSort.java) **- Θ(nlog(n))** - [Quicksort3 (Dutch National Flag algorithm)](src/main/java/com/williamfiset/algorithms/sorting/QuickSort3.java) **- Θ(nlog(n))** - [Selection sort](src/main/java/com/williamfiset/algorithms/sorting/SelectionSort.java) **- O(n2)** diff --git a/build.gradle b/build.gradle index 9f11cbb00..2c69fb357 100644 --- a/build.gradle +++ b/build.gradle @@ -1,24 +1,20 @@ -apply plugin: 'java' -apply plugin: "com.github.sherter.google-java-format" -apply plugin: 'application' - -mainClassName = findProperty("main") ?: "com.williamfiset.algorithms.${findProperty("algorithm") ?: 'missingPackage.missingClass'}" - buildscript { repositories { maven { url "https://plugins.gradle.org/m2/" } } - dependencies { - // https://github.com/sherter/google-java-format-gradle-plugin - classpath "gradle.plugin.com.github.sherter.google-java-format:google-java-format-gradle-plugin:0.8" - } } -// Require Java 8 -sourceCompatibility = 1.8 -targetCompatibility = 1.8 +plugins { + // https://github.com/diffplug/spotless + id("com.diffplug.spotless") version "6.25.0" +} + +apply plugin: 'java' +apply plugin: 'application' + +mainClassName = findProperty("main") ?: "com.williamfiset.algorithms.${findProperty("algorithm") ?: 'missingPackage.missingClass'}" repositories { mavenLocal() @@ -29,23 +25,27 @@ repositories { // 'compile' for project dependencies. dependencies { // Apache commons lang - testCompile 'org.apache.commons:commons-lang3:3.6' - - // JUnit framework - testCompile 'junit:junit:4.+' + testImplementation 'org.apache.commons:commons-lang3:3.14.0' // JUnit 5 / Jupiter - testImplementation('org.junit.jupiter:junit-jupiter-api:5.4.2') - + testImplementation('org.junit.jupiter:junit-jupiter:5.10.0') + testRuntimeOnly('org.junit.jupiter:junit-jupiter-engine:5.10.0') + // Google Guava lib - testCompile group: 'com.google.guava', name: 'guava', version: '22.0' + testImplementation group: 'com.google.guava', name: 'guava', version: '33.3.1-jre' // Google Truth test framework // https://mvnrepository.com/artifact/com.google.truth/truth - testCompile group: 'com.google.truth', name: 'truth', version: '1.0' + testImplementation group: 'com.google.truth', name: 'truth', version: '1.1.5' // Test mocking framework - testCompile "org.mockito:mockito-core:1.+" + testImplementation "org.mockito:mockito-core:5.+" +} + +spotless { + java { + googleJavaFormat() + } } test { @@ -53,6 +53,10 @@ test { testLogging.showStandardStreams = true } +tasks.named('test', Test) { + useJUnitPlatform() +} + tasks.withType(JavaCompile) { options.encoding = 'UTF-8' options.compilerArgs += [ @@ -71,6 +75,6 @@ compileTestJava { } task buildDependenciesFolder(type: Copy) { - from configurations.compile + from configurations.implementation into './dependencies' } diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 9c314338c..e9795fa9d 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ -#Fri May 08 22:17:46 PDT 2020 -distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip +#Sun Aug 14 11:49:58 CEST 2022 +distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-all.zip distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStorePath=wrapper/dists diff --git a/slides/datastructures/sparse_table/sparse_table.key b/slides/datastructures/sparse_table/sparse_table.key index fdabe35bd..b16d88dbd 100755 Binary files a/slides/datastructures/sparse_table/sparse_table.key and b/slides/datastructures/sparse_table/sparse_table.key differ diff --git a/slides/dynamicprogramming/coin_change.key b/slides/dynamicprogramming/coin_change.key new file mode 100755 index 000000000..aa7da884e Binary files /dev/null and b/slides/dynamicprogramming/coin_change.key differ diff --git a/slides/dynamicprogramming/dp_overview.key b/slides/dynamicprogramming/dp_overview.key index 8f628b217..defce7f05 100755 Binary files a/slides/dynamicprogramming/dp_overview.key and b/slides/dynamicprogramming/dp_overview.key differ diff --git a/slides/dynamicprogramming/dynamicprogramming.key b/slides/dynamicprogramming/dynamicprogramming.key index 24bf90754..32842b650 100644 Binary files a/slides/dynamicprogramming/dynamicprogramming.key and b/slides/dynamicprogramming/dynamicprogramming.key differ diff --git a/slides/dynamicprogramming/template.key b/slides/dynamicprogramming/template.key index e3cdbb834..4395412f7 100755 Binary files a/slides/dynamicprogramming/template.key and b/slides/dynamicprogramming/template.key differ diff --git a/slides/dynamicprogramming/tiling_problems_part2.key b/slides/dynamicprogramming/tiling_problems_part2.key index 365608b24..5b6a25e40 100755 Binary files a/slides/dynamicprogramming/tiling_problems_part2.key and b/slides/dynamicprogramming/tiling_problems_part2.key differ diff --git a/slides/dynamicprogramming/weighted_maximum_cardinality_matching.key b/slides/dynamicprogramming/weighted_maximum_cardinality_matching.key index 7c114ab8c..98ac83519 100755 Binary files a/slides/dynamicprogramming/weighted_maximum_cardinality_matching.key and b/slides/dynamicprogramming/weighted_maximum_cardinality_matching.key differ diff --git a/slides/graphtheory/graph_theory_algorithms.key b/slides/graphtheory/graph_theory_algorithms.key index 001614dd4..72368fe0e 100644 Binary files a/slides/graphtheory/graph_theory_algorithms.key and b/slides/graphtheory/graph_theory_algorithms.key differ diff --git a/slides/graphtheory/graph_theory_algorithms.pdf b/slides/graphtheory/graph_theory_algorithms.pdf index f44ab4d24..8fc52422d 100644 Binary files a/slides/graphtheory/graph_theory_algorithms.pdf and b/slides/graphtheory/graph_theory_algorithms.pdf differ diff --git a/slides/graphtheory/tree_algorithm_slides.key b/slides/graphtheory/tree_algorithm_slides.key index 61520e8da..a47604a0b 100755 Binary files a/slides/graphtheory/tree_algorithm_slides.key and b/slides/graphtheory/tree_algorithm_slides.key differ diff --git a/slides/graphtheory/tree_algorithm_slides.pdf b/slides/graphtheory/tree_algorithm_slides.pdf index 1e1a87d9b..6aed18b26 100644 Binary files a/slides/graphtheory/tree_algorithm_slides.pdf and b/slides/graphtheory/tree_algorithm_slides.pdf differ diff --git a/slides/other/Recursion_I.key b/slides/other/Recursion_I.key deleted file mode 100755 index 4840ff873..000000000 Binary files a/slides/other/Recursion_I.key and /dev/null differ diff --git a/slides/other/recursion/FloodFill.kt b/slides/other/recursion/FloodFill.kt new file mode 100644 index 000000000..f07a5953c --- /dev/null +++ b/slides/other/recursion/FloodFill.kt @@ -0,0 +1,39 @@ +val R = 7 +val C = 10 +var matrix: Array = arrayOf( + intArrayOf(0,0,0,0,0,0,0,0,0,0), + intArrayOf(1,0,0,1,1,1,0,1,0,0), + intArrayOf(0,1,0,0,0,0,1,1,0,0), + intArrayOf(0,0,1,1,1,0,0,0,0,0), + intArrayOf(0,0,1,0,1,1,0,1,1,1), + intArrayOf(0,0,1,1,0,0,1,1,0,0), + intArrayOf(0,0,1,0,0,0,0,1,0,0), +); + +fun fill(r: Int, c: Int) { + if (r < 0 || r >= R || c < 0 || c >= C) { + return + } + if (matrix[r][c] > 0) { + return + } + // Mark cell as visited + matrix[r][c] = 2; + fill(r-1, c) + fill(r+1, c) + fill(r, c-1) + fill(r, c+1) +} + +fun main() { + var components = 0 + for (r in 0..R-1) { + for (c in 0..C-1) { + if (matrix[r][c] == 0) { + components++ + fill(r, c) + } + } + } + println("Components = $components") +} diff --git a/slides/other/recursion/Multiplication.kt b/slides/other/recursion/Multiplication.kt new file mode 100644 index 000000000..9af879862 --- /dev/null +++ b/slides/other/recursion/Multiplication.kt @@ -0,0 +1,36 @@ +import kotlin.math.* + +// Best way to do multiplication: +fun mul(a: Int, b : Int): Int { + if (a == 0) { + return 0 + } + if (a < 0) { + return mul(a + 1, b) - b + } + return mul(a - 1, b) + b; +} + +fun mul2(a: Int, b: Int): Int { + // Assumes a >= 0 + fun mul3(a: Int, b: Int): Int { + if (a == 0) { + return 0; + } + return mul3(a - 1, b) + b; + } + + if (a < 0 && b >= 0 || a >= 0 && b < 0) { + return -mul3(abs(a), abs(b)) + } else { + return mul3(abs(a), abs(b)) + } +} + +fun main() { + for (i in -3..3) { + for (j in -3..3) { + println(i*j == mul2(i,j)) + } + } +} diff --git a/slides/other/recursion/RecursionExamples.kt b/slides/other/recursion/RecursionExamples.kt new file mode 100644 index 000000000..a9f41700a --- /dev/null +++ b/slides/other/recursion/RecursionExamples.kt @@ -0,0 +1,42 @@ + +fun f1(count: Int) { + if (count > 5) { + return + } + println("Hello World!") + f1(count + 1) +} + +fun countingDownToZero(n: Int) { + if (n <= 0) { + println("Done counting down") + return + } + println("At $n") + countingDownToZero(n - 1) +} + +// Assignment? +fun countingUp(n: Int, maxValue: Int) { + if (n >= maxValue) { + println("Done counting up. At or past $maxValue") + return + } + println(n) + countingUp(n+1, maxValue) +} + +// Prints all the even numbers in the range [i, j] +fun printEvenNumbers(i:Int, j:Int) { + if (i > j) { + return + } + if (i % 2 == 0) { + println("$i is even!") + } + printEvenNumbers(i+1, j) +} + +fun main() { + printEvenNumbers(5, 12) +} diff --git a/slides/other/recursion/SumList.kt b/slides/other/recursion/SumList.kt new file mode 100644 index 000000000..01340a871 --- /dev/null +++ b/slides/other/recursion/SumList.kt @@ -0,0 +1,35 @@ + + +fun sum(ar: IntArray): Int { + return sum(0, ar) +} + +fun sum(i: Int, ar: IntArray): Int { + if (i >= ar.size) { + return 0; + } + return ar[i] + sum(i+1, ar) +} + +fun divideAndConquer(ar: List): Int { + if (ar.size == 0) { + return 0 + } + return divideAndConquer(0, ar.size - 1, ar) +} + +fun divideAndConquer(i:Int, j:Int, ar: List): Int { + if (i == j) { + return ar[i] + } + val mid = (i+j) / 2 + return divideAndConquer(i, mid, ar) + divideAndConquer(mid+1, j, ar) +} + +fun main() { + for (n in 0..20) { + val ar = List(n, {1}) + println(ar) + println(divideAndConquer(ar)) + } +} diff --git a/slides/other/recursion/recursion.key b/slides/other/recursion/recursion.key new file mode 100644 index 000000000..701393c96 Binary files /dev/null and b/slides/other/recursion/recursion.key differ diff --git a/src/main/java/com/williamfiset/algorithms/ai/GeneticAlgorithm_textSearch.java b/src/main/java/com/williamfiset/algorithms/ai/GeneticAlgorithm_textSearch.java index b32f8ae63..3d2489760 100644 --- a/src/main/java/com/williamfiset/algorithms/ai/GeneticAlgorithm_textSearch.java +++ b/src/main/java/com/williamfiset/algorithms/ai/GeneticAlgorithm_textSearch.java @@ -12,7 +12,8 @@ public class GeneticAlgorithm_textSearch { // Target sentence static final String TARGET = "to be or not to be that is the question"; - static final char[] ALPHA = " abcdefghijklmnopqrstuvwxyz".toCharArray();; + static final char[] ALPHA = " abcdefghijklmnopqrstuvwxyz".toCharArray(); + ; static final int TL = TARGET.length(); static final Random RANDOM = new Random(); diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/balancedtree/AVLTreeRecursive.java b/src/main/java/com/williamfiset/algorithms/datastructures/balancedtree/AVLTreeRecursive.java index c2f7589b3..03b034538 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/balancedtree/AVLTreeRecursive.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/balancedtree/AVLTreeRecursive.java @@ -253,7 +253,7 @@ private Node remove(Node node, T elem) { // successor of the node being removed can either be the largest // value in the left subtree or the smallest value in the right // subtree. As a heuristic, I will remove from the subtree with - // the greatest hieght in hopes that this may help with balancing. + // the greatest height in hopes that this may help with balancing. } else { // Choose to remove from left subtree diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/balancedtree/TreapTree.java b/src/main/java/com/williamfiset/algorithms/datastructures/balancedtree/TreapTree.java index 0a5514d22..8bf8da810 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/balancedtree/TreapTree.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/balancedtree/TreapTree.java @@ -57,6 +57,7 @@ public String getText() { return value.toString(); } } + // The root node of the Treap tree. public Node root; diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/bloomfilter/AnagramSet.java b/src/main/java/com/williamfiset/algorithms/datastructures/bloomfilter/AnagramSet.java index e8febacd3..c20007f93 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/bloomfilter/AnagramSet.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/bloomfilter/AnagramSet.java @@ -53,9 +53,9 @@ public AnagramSet(int[] mods) { // // Assuming all mods are primes each mod value will have a modular inverse for (int i = 0; i < N_HASHES; i++) { - java.math.BigInteger mod = new java.math.BigInteger(String.valueOf(MODS[i])); + java.math.BigInteger mod = java.math.BigInteger.valueOf(MODS[i]); for (int j = 0; j < PRIMES.length; j++) { - java.math.BigInteger prime = new java.math.BigInteger(String.valueOf(PRIMES[j])); + java.math.BigInteger prime = java.math.BigInteger.valueOf(PRIMES[j]); MOD_INVERSES[i][j] = prime.modInverse(mod).intValue(); } } diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/bloomfilter/StringSet.java b/src/main/java/com/williamfiset/algorithms/datastructures/bloomfilter/StringSet.java index f9b978628..29ae01f13 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/bloomfilter/StringSet.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/bloomfilter/StringSet.java @@ -53,11 +53,11 @@ public StringSet(int[] mods, int maxLen) { rollingHashes = new long[N_HASHES]; bloomFilter = new BloomFilter(mods); - java.math.BigInteger bigAlpha = new java.math.BigInteger(String.valueOf(ALPHABET_SZ)); + java.math.BigInteger bigAlpha = java.math.BigInteger.valueOf(ALPHABET_SZ); // Assuming all mods are primes each mod value will have a modular inverse for (int i = 0; i < N_HASHES; i++) { - java.math.BigInteger mod = new java.math.BigInteger(String.valueOf(MODS[i])); + java.math.BigInteger mod = java.math.BigInteger.valueOf(MODS[i]); MOD_INVERSES[i] = bigAlpha.modInverse(mod).intValue(); } diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/dynamicarray/DynamicArray.java b/src/main/java/com/williamfiset/algorithms/datastructures/dynamicarray/DynamicArray.java deleted file mode 100644 index 576f8c219..000000000 --- a/src/main/java/com/williamfiset/algorithms/datastructures/dynamicarray/DynamicArray.java +++ /dev/null @@ -1,129 +0,0 @@ -/** - * A generic dynamic array implementation - * - * @author William Fiset, william.alexandre.fiset@gmail.com - */ -package com.williamfiset.algorithms.datastructures.dynamicarray; - -@SuppressWarnings("unchecked") -public class DynamicArray implements Iterable { - - private T[] arr; - private int len = 0; // length user thinks array is - private int capacity = 0; // Actual array size - - public DynamicArray() { - this(16); - } - - public DynamicArray(int capacity) { - if (capacity < 0) throw new IllegalArgumentException("Illegal Capacity: " + capacity); - this.capacity = capacity; - arr = (T[]) new Object[capacity]; - } - - public int size() { - return len; - } - - public boolean isEmpty() { - return size() == 0; - } - - public T get(int index) { - if (index >= len || index < 0) throw new IndexOutOfBoundsException(); - return arr[index]; - } - - public void set(int index, T elem) { - if (index >= len || index < 0) throw new IndexOutOfBoundsException(); - arr[index] = elem; - } - - public void clear() { - for (int i = 0; i < len; i++) arr[i] = null; - len = 0; - } - - public void add(T elem) { - - // Time to resize! - if (len + 1 >= capacity) { - if (capacity == 0) capacity = 1; - else capacity *= 2; // double the size - T[] new_arr = (T[]) new Object[capacity]; - for (int i = 0; i < len; i++) new_arr[i] = arr[i]; - arr = new_arr; // arr has extra nulls padded - } - - arr[len++] = elem; - } - - // Removes an element at the specified index in this array. - public T removeAt(int rm_index) { - if (rm_index >= len || rm_index < 0) throw new IndexOutOfBoundsException(); - T data = arr[rm_index]; - T[] new_arr = (T[]) new Object[len - 1]; - for (int i = 0, j = 0; i < len; i++, j++) - if (i == rm_index) j--; // Skip over rm_index by fixing j temporarily - else new_arr[j] = arr[i]; - arr = new_arr; - capacity = --len; - return data; - } - - public boolean remove(Object obj) { - int index = indexOf(obj); - if (index == -1) return false; - removeAt(index); - return true; - } - - public int indexOf(Object obj) { - for (int i = 0; i < len; i++) { - if (obj == null) { - if (arr[i] == null) return i; - } else { - if (obj.equals(arr[i])) return i; - } - } - return -1; - } - - public boolean contains(Object obj) { - return indexOf(obj) != -1; - } - - // Iterator is still fast but not as fast as iterative for loop - @Override - public java.util.Iterator iterator() { - return new java.util.Iterator() { - int index = 0; - - @Override - public boolean hasNext() { - return index < len; - } - - @Override - public T next() { - return arr[index++]; - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - }; - } - - @Override - public String toString() { - if (len == 0) return "[]"; - else { - StringBuilder sb = new StringBuilder(len).append("["); - for (int i = 0; i < len - 1; i++) sb.append(arr[i] + ", "); - return sb.append(arr[len - 1] + "]").toString(); - } - } -} diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/fenwicktree/README.md b/src/main/java/com/williamfiset/algorithms/datastructures/fenwicktree/README.md index 26f450d5d..ad3f5cece 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/fenwicktree/README.md +++ b/src/main/java/com/williamfiset/algorithms/datastructures/fenwicktree/README.md @@ -18,7 +18,7 @@ ft.get(1); // 11 ft.get(4); // 6 ft.get(5); // 5 -ft.updateRange(3, 6, -20); // Add -20 to interval [1, 4] in O(log(n)) +ft.updateRange(3, 6, -20); // Add -20 to interval [3, 6] in O(log(n)) ft.get(3); // -7 ft.get(4); // -14 ft.get(5); // -15 diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/hashtable/DoubleHashingTestObject.java b/src/main/java/com/williamfiset/algorithms/datastructures/hashtable/DoubleHashingTestObject.java index f8a9513b4..59a66ddd7 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/hashtable/DoubleHashingTestObject.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/hashtable/DoubleHashingTestObject.java @@ -88,10 +88,13 @@ public int hashCode2() { @Override public boolean equals(Object o) { - DoubleHashingTestObject obj = (DoubleHashingTestObject) o; - if (hash != obj.hash) return false; - if (intData != null) return intData.equals(obj.intData); - if (vectorData != null) return java.util.Arrays.equals(vectorData, obj.vectorData); - return stringData.equals(obj.stringData); + if (this == o) return true; + else if (o instanceof DoubleHashingTestObject) { + DoubleHashingTestObject obj = (DoubleHashingTestObject) o; + if (hash != obj.hash) return false; + if (intData != null) return intData.equals(obj.intData); + if (vectorData != null) return java.util.Arrays.equals(vectorData, obj.vectorData); + return stringData.equals(obj.stringData); + } else return false; } } diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableDoubleHashing.java b/src/main/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableDoubleHashing.java index 9af8a6f34..580f30f0b 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableDoubleHashing.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableDoubleHashing.java @@ -44,7 +44,7 @@ protected int probe(int x) { // probing so that all the cells can be reached. @Override protected void adjustCapacity() { - while (!(new BigInteger(String.valueOf(capacity)).isProbablePrime(20))) { + while (!(BigInteger.valueOf(capacity).isProbablePrime(20))) { capacity++; } } diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/stack/ArrayStack.java b/src/main/java/com/williamfiset/algorithms/datastructures/stack/ArrayStack.java index 3f34d8717..a831c4ca8 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/stack/ArrayStack.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/stack/ArrayStack.java @@ -3,7 +3,9 @@ import java.util.Arrays; import java.util.EmptyStackException; -/** @author liujingkun */ +/** + * @author liujingkun + */ public class ArrayStack implements Stack { private int size; private int capacity; diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/stack/Stack.java b/src/main/java/com/williamfiset/algorithms/datastructures/stack/Stack.java index 15a269688..61cacfcb5 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/stack/Stack.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/stack/Stack.java @@ -1,6 +1,8 @@ package com.williamfiset.algorithms.datastructures.stack; -/** @author liujingkun */ +/** + * @author liujingkun + */ public interface Stack { // return the number of elements in the stack public int size(); diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/suffixarray/SuffixArray.java b/src/main/java/com/williamfiset/algorithms/datastructures/suffixarray/SuffixArray.java index 77b5c498a..ac8702f12 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/suffixarray/SuffixArray.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/suffixarray/SuffixArray.java @@ -88,6 +88,7 @@ private void kasai() { @Override public String toString() { + if (!constructedLcpArray) buildLcpArray(); StringBuilder sb = new StringBuilder(); sb.append("-----i-----SA-----LCP---Suffix\n"); diff --git a/src/main/java/com/williamfiset/algorithms/dp/CoinChange.java b/src/main/java/com/williamfiset/algorithms/dp/CoinChange.java index ea0e815a7..5daa688d7 100644 --- a/src/main/java/com/williamfiset/algorithms/dp/CoinChange.java +++ b/src/main/java/com/williamfiset/algorithms/dp/CoinChange.java @@ -3,32 +3,53 @@ * the minimum number of coins required for a certain amount of change given the coin denominations. * You may use each coin denomination as many times as you please. * - *

Tested against: https://leetcode.com/problems/coin-change/ + *

Tested against: https://leetcode.com/problems/coin-change + * + *

Run locally: + * + *

./gradlew run -Palgorithm=dp.CoinChange * * @author William Fiset, william.alexandre.fiset@gmail.com */ package com.williamfiset.algorithms.dp; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + public class CoinChange { - private static final int INF = 987654321; + public static class Solution { + // Contains the minimum number of coins to make a certain amount, if a solution exists. + Optional minCoins = Optional.empty(); - public static int coinChange(int[] coins, int amount) { + // The coins selected as part of the optimal solution. + List selectedCoins = new ArrayList(); + } + + // TODO(william): setting an explicit infinity could lead to a wrong answer for + // very large values. Prefer to use null instead. + private static final int INF = Integer.MAX_VALUE / 2; + public static Solution coinChange(int[] coins, final int n) { if (coins == null) throw new IllegalArgumentException("Coins array is null"); if (coins.length == 0) throw new IllegalArgumentException("No coin values :/"); + for (int coin : coins) { + if (coin <= 0) { + throw new IllegalArgumentException("Coin with value `" + coin + "` is not allowed."); + } + } - final int N = coins.length; + final int m = coins.length; // Initialize table and set first row to be infinity - int[][] dp = new int[N + 1][amount + 1]; + int[][] dp = new int[m + 1][n + 1]; java.util.Arrays.fill(dp[0], INF); dp[1][0] = 0; // Iterate through all the coins - for (int i = 1; i <= N; i++) { - + for (int i = 1; i <= m; i++) { int coinValue = coins[i - 1]; - for (int j = 1; j <= amount; j++) { + for (int j = 1; j <= n; j++) { // Consider not selecting this coin dp[i][j] = dp[i - 1][j]; @@ -40,73 +61,157 @@ public static int coinChange(int[] coins, int amount) { } } - // The amount we wanted to make cannot be made :/ - if (dp[N][amount] == INF) return -1; + // p(dp); - // Return the minimum number of coins needed - return dp[N][amount]; - } + Solution solution = new Solution(); + + if (dp[m][n] != INF) { + solution.minCoins = Optional.of(dp[m][n]); + } else { + return solution; + } + + for (int change = n, coinIndex = m; coinIndex > 0; ) { + int coinValue = coins[coinIndex - 1]; + boolean canSelectCoin = change - coinValue >= 0; + if (canSelectCoin && dp[coinIndex][change - coinValue] < dp[coinIndex][change]) { + solution.selectedCoins.add(coinValue); + change -= coinValue; + } else { + coinIndex--; + } + } - public static int coinChangeSpaceEfficient(int[] coins, int amount) { + return solution; + } + public static Solution coinChangeSpaceEfficient(int[] coins, int n) { if (coins == null) throw new IllegalArgumentException("Coins array is null"); // Initialize table and set everything to infinity except first cell - int[] dp = new int[amount + 1]; + int[] dp = new int[n + 1]; java.util.Arrays.fill(dp, INF); dp[0] = 0; - for (int i = 1; i <= amount; i++) { - for (int coinValue : coins) { - if (i - coinValue >= 0 && dp[i - coinValue] + 1 < dp[i]) { - dp[i] = dp[i - coinValue] + 1; + for (int i = 1; i <= n; i++) { + for (int coin : coins) { + if (i - coin < 0) { + continue; + } + if (dp[i - coin] + 1 < dp[i]) { + dp[i] = dp[i - coin] + 1; } } } - // The amount we wanted to make cannot be made :/ - if (dp[amount] == INF) return -1; + Solution solution = new Solution(); + if (dp[n] != INF) { + solution.minCoins = Optional.of(dp[n]); + } else { + return solution; + } + + for (int i = n; i > 0; ) { + int selectedCoinValue = INF; + int cellWithFewestCoins = dp[i]; + for (int coin : coins) { + if (i - coin < 0) { + continue; + } + if (dp[i - coin] < cellWithFewestCoins) { + cellWithFewestCoins = dp[i - coin]; + selectedCoinValue = coin; + } + } + solution.selectedCoins.add(selectedCoinValue); + i -= selectedCoinValue; + } // Return the minimum number of coins needed - return dp[amount]; + return solution; } // The recursive approach has the advantage that it does not have to visit // all possible states like the tabular approach does. This can speedup // things especially if the coin denominations are large. - public static int coinChangeRecursive(int[] coins, int amount) { - + public static int coinChangeRecursive(int[] coins, int n) { if (coins == null) throw new IllegalArgumentException("Coins array is null"); - if (amount < 0) return -1; + if (n < 0) return -1; - int[] dp = new int[amount + 1]; - return coinChangeRecursive(amount, coins, dp); + int[] dp = new int[n + 1]; + return coinChangeRecursive(n, coins, dp); } // Private helper method to actually go the recursion - private static int coinChangeRecursive(int amount, int[] coins, int[] dp) { - - // Base cases. - if (amount < 0) return -1; - if (amount == 0) return 0; - if (dp[amount] != 0) return dp[amount]; + private static int coinChangeRecursive(int n, int[] coins, int[] dp) { + if (n < 0) return -1; + if (n == 0) return 0; + if (dp[n] != 0) return dp[n]; int minCoins = INF; for (int coinValue : coins) { - - int newAmount = amount - coinValue; - int value = coinChangeRecursive(newAmount, coins, dp); + int value = coinChangeRecursive(n - coinValue, coins, dp); if (value != -1 && value < minCoins) minCoins = value + 1; } // If we weren't able to find some coins to make our // amount then cache -1 as the answer. - return dp[amount] = (minCoins == INF) ? -1 : minCoins; + return dp[n] = (minCoins == INF) ? -1 : minCoins; + } + + // DP table print function. Used for debugging. + private static void p(int[][] dp) { + for (int[] r : dp) { + for (int v : r) { + System.out.printf("%4d, ", v == INF ? -1 : v); + } + System.out.println(); + } + } + + private static void p(int[] dp) { + for (int v : dp) { + System.out.printf("%4d, ", v == INF ? -1 : v); + } + System.out.println(); } public static void main(String[] args) { + // example1(); + // example2(); + // example3(); + example4(); + } + + private static void example4() { + int n = 11; + int[] coins = {2, 4, 1}; + // System.out.println(coinChange(coins, n).minCoins); + System.out.println(coinChangeSpaceEfficient(coins, n)); + // System.out.println(coinChangeRecursive(coins, n)); + // System.out.println(coinChange(coins, n).selectedCoins); + } + + private static void example1() { int[] coins = {2, 6, 1}; - System.out.println(coinChange(coins, 17)); + System.out.println(coinChange(coins, 17).minCoins); + System.out.println(coinChange(coins, 17).selectedCoins); + System.out.println(coinChangeSpaceEfficient(coins, 17)); + System.out.println(coinChangeRecursive(coins, 17)); + } + + private static void example2() { + int[] coins = {2, 3, 5}; + System.out.println(coinChange(coins, 12).minCoins); + System.out.println(coinChange(coins, 12).selectedCoins); + System.out.println(coinChangeSpaceEfficient(coins, 12)); + System.out.println(coinChangeRecursive(coins, 12)); + } + + private static void example3() { + int[] coins = {3, 4, 7}; + System.out.println(coinChange(coins, 17).minCoins); + System.out.println(coinChange(coins, 17).selectedCoins); System.out.println(coinChangeSpaceEfficient(coins, 17)); System.out.println(coinChangeRecursive(coins, 17)); } diff --git a/src/main/java/com/williamfiset/algorithms/dp/MinimumWeightPerfectMatching.java b/src/main/java/com/williamfiset/algorithms/dp/MinimumWeightPerfectMatching.java index f92f76816..6d3ed625e 100644 --- a/src/main/java/com/williamfiset/algorithms/dp/MinimumWeightPerfectMatching.java +++ b/src/main/java/com/williamfiset/algorithms/dp/MinimumWeightPerfectMatching.java @@ -73,7 +73,6 @@ public int[] getMinWeightCostMatching() { } // Recursive impl - // TODO(william): move to another file? public void solveRecursive() { if (solved) return; Double[] dp = new Double[1 << n]; diff --git a/src/main/java/com/williamfiset/algorithms/dp/MwpmInterface.java b/src/main/java/com/williamfiset/algorithms/dp/MwpmInterface.java index 8c2255313..af84da354 100644 --- a/src/main/java/com/williamfiset/algorithms/dp/MwpmInterface.java +++ b/src/main/java/com/williamfiset/algorithms/dp/MwpmInterface.java @@ -1,9 +1,10 @@ -// Simple interface for MinimumWeightPerfectMatching (MWPM) solutions to simplify testing. - package com.williamfiset.algorithms.dp; +// Simple interface for MinimumWeightPerfectMatching (MWPM) solutions to simplify testing. public interface MwpmInterface { + // Gets the minimum weight matching cost public double getMinWeightCost(); + // Returns an optimal matching. public int[] getMatching(); } diff --git a/src/main/java/com/williamfiset/algorithms/dp/examples/boardtilings/BoardTilingsSolver.java b/src/main/java/com/williamfiset/algorithms/dp/examples/boardtilings/BoardTilingsSolver.java index 4db34cd7e..bda49423c 100644 --- a/src/main/java/com/williamfiset/algorithms/dp/examples/boardtilings/BoardTilingsSolver.java +++ b/src/main/java/com/williamfiset/algorithms/dp/examples/boardtilings/BoardTilingsSolver.java @@ -1,3 +1,5 @@ +package com.williamfiset.algorithms.dp.examples.boardtilings; + import java.util.*; public class BoardTilingsSolver { diff --git a/src/main/java/com/williamfiset/algorithms/dp/examples/editdistance/EditDistance.java b/src/main/java/com/williamfiset/algorithms/dp/examples/editdistance/EditDistance.java index 889a52b3f..c018f9bb3 100644 --- a/src/main/java/com/williamfiset/algorithms/dp/examples/editdistance/EditDistance.java +++ b/src/main/java/com/williamfiset/algorithms/dp/examples/editdistance/EditDistance.java @@ -1,3 +1,5 @@ +package com.williamfiset.algorithms.dp.examples.editdistance; + import java.io.*; import java.util.*; diff --git a/src/main/java/com/williamfiset/algorithms/dp/examples/houserobber/HouseRobber.java b/src/main/java/com/williamfiset/algorithms/dp/examples/houserobber/HouseRobber.java index 57c57ca6d..b2258ce45 100644 --- a/src/main/java/com/williamfiset/algorithms/dp/examples/houserobber/HouseRobber.java +++ b/src/main/java/com/williamfiset/algorithms/dp/examples/houserobber/HouseRobber.java @@ -14,7 +14,7 @@ * *

Run: $ java -cp src/main/java com/williamfiset/algorithms/dp/examples/HouseRobber */ -package com.williamfiset.algorithms.dp.examples; +package com.williamfiset.algorithms.dp.examples.houserobber; import java.util.*; diff --git a/src/main/java/com/williamfiset/algorithms/dp/examples/magicalcows/MagicalCows.java b/src/main/java/com/williamfiset/algorithms/dp/examples/magicalcows/MagicalCows.java index c14f9306f..4805c4813 100644 --- a/src/main/java/com/williamfiset/algorithms/dp/examples/magicalcows/MagicalCows.java +++ b/src/main/java/com/williamfiset/algorithms/dp/examples/magicalcows/MagicalCows.java @@ -1,3 +1,5 @@ +package com.williamfiset.algorithms.dp.examples.magicalcows; + /** * Solution to Magical Cows (https://open.kattis.com/problems/magicalcows) * diff --git a/src/main/java/com/williamfiset/algorithms/dp/examples/narrowartgallery/NarrowArtGalleryRecursive.java b/src/main/java/com/williamfiset/algorithms/dp/examples/narrowartgallery/NarrowArtGalleryRecursive.java index b0cdac391..17af39dfb 100644 --- a/src/main/java/com/williamfiset/algorithms/dp/examples/narrowartgallery/NarrowArtGalleryRecursive.java +++ b/src/main/java/com/williamfiset/algorithms/dp/examples/narrowartgallery/NarrowArtGalleryRecursive.java @@ -1,3 +1,5 @@ +package com.williamfiset.algorithms.dp.examples.narrowartgallery; + /** * Solution to the Narrow Art Gallery problem from the 2014 ICPC North America Qualifier * @@ -47,9 +49,9 @@ public static int f(int k, int r, int c) { return INF; } // Return the value of this subproblem, if it's already been computed. - // if (dp[k][r][c] != null) { - // return dp[k][r][c]; - // } + if (dp[k][r][c] != null) { + return dp[k][r][c]; + } // Get the value of the current room at row `r` and column `c`. int roomValue = gallery[r][c]; return dp[k][r][c] = diff --git a/src/main/java/com/williamfiset/algorithms/dp/examples/scenes/Scenes.java b/src/main/java/com/williamfiset/algorithms/dp/examples/scenes/Scenes.java index b852d40ec..1f2faf413 100644 --- a/src/main/java/com/williamfiset/algorithms/dp/examples/scenes/Scenes.java +++ b/src/main/java/com/williamfiset/algorithms/dp/examples/scenes/Scenes.java @@ -1,3 +1,5 @@ +package com.williamfiset.algorithms.dp.examples.scenes; + /** * Solution to the Mountain Scenes problem (https://open.kattis.com/problems/scenes) * diff --git a/src/main/java/com/williamfiset/algorithms/dp/examples/tilingdominoes/TilingDominoes.java b/src/main/java/com/williamfiset/algorithms/dp/examples/tilingdominoes/TilingDominoes.java index 4f57a8ab1..491bee341 100644 --- a/src/main/java/com/williamfiset/algorithms/dp/examples/tilingdominoes/TilingDominoes.java +++ b/src/main/java/com/williamfiset/algorithms/dp/examples/tilingdominoes/TilingDominoes.java @@ -1,3 +1,5 @@ +package com.williamfiset.algorithms.dp.examples.tilingdominoes; + /** * Solution to Tri Tiling (https://open.kattis.com/problems/tritiling) * diff --git a/src/main/java/com/williamfiset/algorithms/graphtheory/Boruvkas.java b/src/main/java/com/williamfiset/algorithms/graphtheory/Boruvkas.java index 40dbfa84e..1be3a5f7d 100644 --- a/src/main/java/com/williamfiset/algorithms/graphtheory/Boruvkas.java +++ b/src/main/java/com/williamfiset/algorithms/graphtheory/Boruvkas.java @@ -17,6 +17,7 @@ public Edge(int u, int v, int cost) { public String toString() { return String.format("%d %d, cost: %d", u, v, cost); } + // @Override public int compareTo(Edge other) { int cmp = cost - other.cost; diff --git a/src/main/java/com/williamfiset/algorithms/graphtheory/ConnectedComponentsDfsSolverAdjacencyList.java b/src/main/java/com/williamfiset/algorithms/graphtheory/ConnectedComponentsDfsSolverAdjacencyList.java index 7ee545ada..827945121 100644 --- a/src/main/java/com/williamfiset/algorithms/graphtheory/ConnectedComponentsDfsSolverAdjacencyList.java +++ b/src/main/java/com/williamfiset/algorithms/graphtheory/ConnectedComponentsDfsSolverAdjacencyList.java @@ -19,7 +19,9 @@ public class ConnectedComponentsDfsSolverAdjacencyList { private boolean[] visited; private List> graph; - /** @param graph - An undirected graph as an adjacency list. */ + /** + * @param graph - An undirected graph as an adjacency list. + */ public ConnectedComponentsDfsSolverAdjacencyList(List> graph) { if (graph == null) throw new NullPointerException(); this.n = graph.size(); diff --git a/src/main/java/com/williamfiset/algorithms/graphtheory/KruskalsEdgeListPartialSortSolver.java b/src/main/java/com/williamfiset/algorithms/graphtheory/KruskalsEdgeListPartialSortSolver.java index e1742176c..b3a651014 100644 --- a/src/main/java/com/williamfiset/algorithms/graphtheory/KruskalsEdgeListPartialSortSolver.java +++ b/src/main/java/com/williamfiset/algorithms/graphtheory/KruskalsEdgeListPartialSortSolver.java @@ -17,12 +17,14 @@ public class KruskalsEdgeListPartialSortSolver { static class Edge implements Comparable { int u, v, cost; + // 'u' and 'v' are nodes indexes and 'cost' is the cost of taking this edge. public Edge(int u, int v, int cost) { this.u = u; this.v = v; this.cost = cost; } + // Sort edges based on cost. @Override public int compareTo(Edge other) { diff --git a/src/main/java/com/williamfiset/algorithms/graphtheory/networkflow/NetworkFlowSolverBase.java b/src/main/java/com/williamfiset/algorithms/graphtheory/networkflow/NetworkFlowSolverBase.java index dae728f01..bba05a637 100644 --- a/src/main/java/com/williamfiset/algorithms/graphtheory/networkflow/NetworkFlowSolverBase.java +++ b/src/main/java/com/williamfiset/algorithms/graphtheory/networkflow/NetworkFlowSolverBase.java @@ -1,4 +1,6 @@ -/** @author William Fiset, william.alexandre.fiset@gmail.com */ +/** + * @author William Fiset, william.alexandre.fiset@gmail.com + */ package com.williamfiset.algorithms.graphtheory.networkflow; import java.util.ArrayList; diff --git a/src/main/java/com/williamfiset/algorithms/graphtheory/treealgorithms/LowestCommonAncestor.java b/src/main/java/com/williamfiset/algorithms/graphtheory/treealgorithms/LowestCommonAncestor.java index 34a6e0e04..5ed4cc500 100644 --- a/src/main/java/com/williamfiset/algorithms/graphtheory/treealgorithms/LowestCommonAncestor.java +++ b/src/main/java/com/williamfiset/algorithms/graphtheory/treealgorithms/LowestCommonAncestor.java @@ -14,7 +14,7 @@ public static class TreeNode { // Useful constructor for root node. public TreeNode(int id) { - this(id, /*parent=*/ null); + this(id, /* parent= */ null); } public TreeNode(int id, TreeNode parent) { diff --git a/src/main/java/com/williamfiset/algorithms/graphtheory/treealgorithms/LowestCommonAncestorEulerTour.java b/src/main/java/com/williamfiset/algorithms/graphtheory/treealgorithms/LowestCommonAncestorEulerTour.java index 51fbd85ba..28efcf56f 100644 --- a/src/main/java/com/williamfiset/algorithms/graphtheory/treealgorithms/LowestCommonAncestorEulerTour.java +++ b/src/main/java/com/williamfiset/algorithms/graphtheory/treealgorithms/LowestCommonAncestorEulerTour.java @@ -94,7 +94,7 @@ public static class TreeNode { // Useful constructor for root node. public TreeNode(int index) { - this(index, /*parent=*/ null); + this(index, /* parent= */ null); } public TreeNode(int index, TreeNode parent) { @@ -192,7 +192,7 @@ private void setup(TreeNode root) { last = new int[n]; // Do depth first search to construct Euler tour. - dfs(root, /*depth=*/ 0); + dfs(root, /* depth= */ 0); // Initialize and build sparse table on the `nodeDepth` array which will // allow us to index into the `nodeOrder` array and return the LCA. diff --git a/src/main/java/com/williamfiset/algorithms/graphtheory/treealgorithms/RootingTree.java b/src/main/java/com/williamfiset/algorithms/graphtheory/treealgorithms/RootingTree.java index 0d7a2dbc7..09208c8bd 100644 --- a/src/main/java/com/williamfiset/algorithms/graphtheory/treealgorithms/RootingTree.java +++ b/src/main/java/com/williamfiset/algorithms/graphtheory/treealgorithms/RootingTree.java @@ -19,7 +19,7 @@ public static class TreeNode { // Useful constructor for root node. public TreeNode(int id) { - this(id, /*parent=*/ null); + this(id, /* parent= */ null); } public TreeNode(int id, TreeNode parent) { diff --git a/src/main/java/com/williamfiset/algorithms/graphtheory/treealgorithms/TreeIsomorphism.java b/src/main/java/com/williamfiset/algorithms/graphtheory/treealgorithms/TreeIsomorphism.java index 6e82d08d6..015b3ca60 100644 --- a/src/main/java/com/williamfiset/algorithms/graphtheory/treealgorithms/TreeIsomorphism.java +++ b/src/main/java/com/williamfiset/algorithms/graphtheory/treealgorithms/TreeIsomorphism.java @@ -19,7 +19,7 @@ public static class TreeNode { // Useful constructor for root node. public TreeNode(int id) { - this(id, /*parent=*/ null); + this(id, /* parent= */ null); } public TreeNode(int id, TreeNode parent) { diff --git a/src/main/java/com/williamfiset/algorithms/linearalgebra/MatrixDeterminantLaplaceExpansion.java b/src/main/java/com/williamfiset/algorithms/linearalgebra/MatrixDeterminantLaplaceExpansion.java index 54852a722..b0c933f13 100644 --- a/src/main/java/com/williamfiset/algorithms/linearalgebra/MatrixDeterminantLaplaceExpansion.java +++ b/src/main/java/com/williamfiset/algorithms/linearalgebra/MatrixDeterminantLaplaceExpansion.java @@ -62,14 +62,91 @@ public static void main(String[] args) { }; System.out.println(determinant(m)); // -27435 - System.out.println(); + m = + new double[][] { + {1, 3, 5, 9}, + {1, 3, 1, 7}, + {4, 3, 9, 7}, + {5, 2, 0, 9}, + }; // determinant(mat1) = -376 , mat(4 * 4) + System.out.println(determinant(m)); - for (int n = 1; ; n++) { - m = new double[n][n]; - for (int i = 0; i < n; i++) - for (int j = 0; j < n; j++) m[i][j] = Math.floor(Math.random() * 10); - System.out.printf("Found determinant of %dx%d matrix to be: %.4f\n", n, n, determinant(m)); - } + m = + new double[][] { + {1, 3, 5, 4}, + {2, 3, 1, 3}, + {4, 3, 9, 7}, + {5, 2, 6, 9}, + }; // determinant(mat2) = -152 , mat(4 * 4) + System.out.println(determinant(m)); + m = + new double[][] { + {4, 7, 2, 3}, + {1, 3, 1, 2}, + {2, 5, 3, 4}, + {1, 4, 2, 3}, + }; // determinant(mat3) = -3 , mat(4 * 4) + System.out.println(determinant(m)); + m = + new double[][] { + {1, 0, 0, 0, 0, 2}, + {0, 1, 0, 0, 2, 0}, + {0, 0, 1, 2, 0, 0}, + {0, 0, 2, 1, 0, 0}, + {0, 2, 0, 0, 1, 0}, + {2, 0, 0, 0, 0, 1}, + }; // determinant(mat4) = -27 , mat(6 * 6) + System.out.println(determinant(m)); + m = + new double[][] { + {1, 1, 9, 3, 1, 2, 3}, + {9, 1, 8, 4, 2, 3, 1}, + {3, 2, 7, 2, 9, 5, 5}, + {4, 6, 2, 1, 7, 9, 6}, + {5, 3, 1, 3, 1, 5, 3}, + {2, 7, 9, 5, 0, 1, 2}, + {2, 1, 3, 8, 9, 1, 4} + }; // determinant(mat5) = 66704 mat(7 * 7) + System.out.println(determinant(m)); + m = + new double[][] { + {1, 1, 9, 3, 1, 2, 3, 9}, + {9, 1, 8, 4, 2, 3, 1, 8}, + {3, 2, 7, 2, 9, 5, 5, 7}, + {4, 6, 2, 1, 7, 9, 6, 6}, + {5, 3, 1, 3, 1, 5, 3, 5}, + {2, 7, 9, 5, 0, 1, 2, 4}, + {2, 1, 3, 8, 9, 1, 4, 3}, + {6, 1, 6, 7, 9, 1, 4, 2} + }; // determinant(mat6) = -39240 , mat(8 * 8) + System.out.println(determinant(m)); + m = + new double[][] { + {1, 1, 9, 3, 1, 2, 3, 9, 1}, + {9, 1, 8, 4, 2, 3, 1, 8, 2}, + {3, 2, 7, 2, 9, 5, 5, 7, 3}, + {4, 6, 2, 1, 7, 9, 6, 6, 4}, + {5, 3, 1, 3, 1, 5, 3, 5, 5}, + {2, 7, 9, 5, 0, 1, 2, 4, 6}, + {2, 1, 3, 8, 9, 1, 4, 3, 7}, + {6, 1, 6, 7, 9, 1, 4, 2, 8}, + {9, 8, 7, 4, 3, 3, 4, 2, 9} + }; // determinant(mat7) = 1910870 , mat( 9 * 9) + System.out.println(determinant(m)); + m = + new double[][] { + {1, 2, 4, 8, 6, 3, 4, 8, 0, 2}, + {2, 2, 3, 4, 5, 6, 7, 8, 9, 1}, + {5, 2, 3, 4, 8, 9, 1, 9, 8, 3}, + {1, 1, 1, 6, 4, 2, 5, 9, 8, 7}, + {9, 5, 0, 1, 2, 0, 6, 0, 0, 0}, + {8, 4, 0, 1, 2, 3, 4, 5, 8, 4}, + {7, 3, 3, 6, 7, 8, 9, 1, 7, 3}, + {1, 2, 4, 0, 0, 0, 0, 3, 5, 2}, + {1, 1, 0, 4, 5, 0, 0, 4, 2, 1}, + {1, 0, 0, 0, 9, 0, 0, 1, 1, 6} + }; // determinant(mat0) = 17265530 (1.726553E7) + System.out.println(determinant(m)); } // Given an n*n matrix, this method finds the determinant using Laplace/cofactor expansion. @@ -97,48 +174,45 @@ private static double laplace(double[][] m) { // Base case is 3x3 determinant if (n == 3) { + /* + * Used as a temporary variables to make calculation easy + * | a b c | + * | d e f | + * | g h i | + */ double a = m[0][0], b = m[0][1], c = m[0][2]; double d = m[1][0], e = m[1][1], f = m[1][2]; double g = m[2][0], h = m[2][1], i = m[2][2]; return a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g); } - int det = 0; - for (int i = 0; i < n; i++) { - for (int j = 0; j < n; j++) { - - double c = m[i][j]; - if (Math.abs(c) > EPS) { - double[][] newMatrix = constructMatrix(m, j); - double parity = ((j & 1) == 0) ? +1 : -1; - det += parity * c * laplace(newMatrix); - } + double c = m[0][i]; + if (c > EPS) { + int sign = ((i & 1) == 0) ? +1 : -1; + det += sign * m[0][i] * laplace(constructMatrix(m, 0, i)); } } - return det; } // Constructs a matrix one dimension smaller than the last by // excluding the top row and some selected column. This // method ends up consuming a lot of space we called recursively multiple times - // since it allocates meory for a new matrix. - private static double[][] constructMatrix(double[][] m, int skipColumn) { - - int n = m.length; + // since it allocates memory for a new matrix. + private static double[][] constructMatrix(double[][] mat, int excludingRow, int excludingCol) { + int n = mat.length; double[][] newMatrix = new double[n - 1][n - 1]; - - int ii = 0; - for (int i = 1; i < n; i++, ii++) { - int jj = 0; + int rPtr = -1; + for (int i = 0; i < n; i++) { + if (i == excludingRow) continue; + ++rPtr; + int cPtr = -1; for (int j = 0; j < n; j++) { - if (j == skipColumn) continue; - double v = m[i][j]; - newMatrix[ii][jj++] = v; - } - } - + if (j == excludingCol) continue; + newMatrix[rPtr][++cPtr] = mat[i][j]; + } // end of inner loop + } // end of outer loop return newMatrix; - } + } // end of createSubMatrix } diff --git a/src/main/java/com/williamfiset/algorithms/math/ModPow.java b/src/main/java/com/williamfiset/algorithms/math/ModPow.java index 77451811d..94994396d 100644 --- a/src/main/java/com/williamfiset/algorithms/math/ModPow.java +++ b/src/main/java/com/williamfiset/algorithms/math/ModPow.java @@ -11,6 +11,8 @@ */ package com.williamfiset.algorithms.math; +import java.math.BigInteger; + public class ModPow { // The values placed into the modPow function cannot be greater @@ -87,12 +89,12 @@ public static long modPow(long a, long n, long mod) { // Example usage public static void main(String[] args) { - java.math.BigInteger A, N, M, r1; + BigInteger A, N, M, r1; long a, n, m, r2; - A = new java.math.BigInteger("3"); - N = new java.math.BigInteger("4"); - M = new java.math.BigInteger("1000000"); + A = BigInteger.valueOf(3); + N = BigInteger.valueOf(4); + M = BigInteger.valueOf(1000000); a = A.longValue(); n = N.longValue(); m = M.longValue(); @@ -102,9 +104,9 @@ public static void main(String[] args) { r2 = modPow(a, n, m); // 81 System.out.println(r1 + " " + r2); - A = new java.math.BigInteger("-45"); - N = new java.math.BigInteger("12345"); - M = new java.math.BigInteger("987654321"); + A = BigInteger.valueOf(-45); + N = BigInteger.valueOf(12345); + M = BigInteger.valueOf(987654321); a = A.longValue(); n = N.longValue(); m = M.longValue(); @@ -114,9 +116,9 @@ public static void main(String[] args) { r2 = modPow(a, n, m); // 323182557 System.out.println(r1 + " " + r2); - A = new java.math.BigInteger("6"); - N = new java.math.BigInteger("-66"); - M = new java.math.BigInteger("101"); + A = BigInteger.valueOf(6); + N = BigInteger.valueOf(-66); + M = BigInteger.valueOf(101); a = A.longValue(); n = N.longValue(); m = M.longValue(); @@ -126,9 +128,9 @@ public static void main(String[] args) { r2 = modPow(a, n, m); // 84 System.out.println(r1 + " " + r2); - A = new java.math.BigInteger("-5"); - N = new java.math.BigInteger("-7"); - M = new java.math.BigInteger("1009"); + A = BigInteger.valueOf(-5); + N = BigInteger.valueOf(-7); + M = BigInteger.valueOf(1009); a = A.longValue(); n = N.longValue(); m = M.longValue(); @@ -139,9 +141,9 @@ public static void main(String[] args) { System.out.println(r1 + " " + r2); for (int i = 0; i < 1000; i++) { - A = new java.math.BigInteger(a + ""); - N = new java.math.BigInteger(n + ""); - M = new java.math.BigInteger(m + ""); + A = BigInteger.valueOf(a); + N = BigInteger.valueOf(n); + M = BigInteger.valueOf(m); a = Math.random() < 0.5 ? randLong(MAX) : -randLong(MAX); n = randLong(); m = randLong(MAX); diff --git a/src/main/java/com/williamfiset/algorithms/math/NChooseRModPrime.java b/src/main/java/com/williamfiset/algorithms/math/NChooseRModPrime.java index fda19ef1a..a3574edac 100644 --- a/src/main/java/com/williamfiset/algorithms/math/NChooseRModPrime.java +++ b/src/main/java/com/williamfiset/algorithms/math/NChooseRModPrime.java @@ -1,4 +1,6 @@ -/** @author Rohit Mazumder, mazumder.rohit7@gmai.com */ +/** + * @author Rohit Mazumder, mazumder.rohit7@gmai.com + */ package com.williamfiset.algorithms.math; import java.math.BigInteger; @@ -33,11 +35,11 @@ public static long compute(int N, int R, int P) { // Method for testing output against the output generated by the compute(int,int,int) function private static String bigIntegerNChooseRModP(int N, int R, int P) { if (R == 0) return "1"; - BigInteger num = new BigInteger("1"); - BigInteger den = new BigInteger("1"); + BigInteger num = BigInteger.ONE; + BigInteger den = BigInteger.ONE; while (R > 0) { - num = num.multiply(new BigInteger("" + N)); - den = den.multiply(new BigInteger("" + R)); + num = num.multiply(BigInteger.valueOf(N)); + den = den.multiply(BigInteger.valueOf(R)); BigInteger gcd = num.gcd(den); num = num.divide(gcd); den = den.divide(gcd); @@ -45,7 +47,7 @@ private static String bigIntegerNChooseRModP(int N, int R, int P) { R--; } num = num.divide(den); - num = num.mod(new BigInteger("" + P)); + num = num.mod(BigInteger.valueOf(P)); return num.toString(); } diff --git a/src/main/java/com/williamfiset/algorithms/strings/RabinKarp.java b/src/main/java/com/williamfiset/algorithms/strings/RabinKarp.java index 96c873912..c8e9adce2 100644 --- a/src/main/java/com/williamfiset/algorithms/strings/RabinKarp.java +++ b/src/main/java/com/williamfiset/algorithms/strings/RabinKarp.java @@ -17,7 +17,7 @@ public class RabinKarp { // same value as ' ' since 0*95^0 = 0*95^0 + 0*95^1 + 0*95^2 private static final long ALPHABET_BASE = 95 + 1; private static final long[] ALPHABET = new long[127]; - private static final BigInteger BIG_ALPHA = new BigInteger(String.valueOf(ALPHABET_BASE)); + private static final BigInteger BIG_ALPHA = BigInteger.valueOf(ALPHABET_BASE); // More primes: 1009, 1013, 1019, 10007, 10009, 10037, 100003, 100019, 100043, 1000003, 1000033, // 1000037, @@ -35,7 +35,7 @@ public class RabinKarp { // Compute modular inverses for chosen mod values for (int i = 0; i < N_HASHES; i++) { - java.math.BigInteger mod = new java.math.BigInteger(String.valueOf(MODS[i])); + java.math.BigInteger mod = java.math.BigInteger.valueOf(MODS[i]); MOD_INVERSES[i] = BIG_ALPHA.modInverse(mod).longValue(); BIG_MODS[i] = mod; } @@ -83,7 +83,7 @@ public static List rabinKarp(String text, String pattern) { long[] patternHash = computeHash(pattern); long[] rollingHash = computeHash(text.substring(0, PL)); - final BigInteger BIG_PL = new BigInteger(String.valueOf(PL)); + final BigInteger BIG_PL = BigInteger.valueOf(PL); final long[] POWERS = new long[N_HASHES]; for (int i = 0; i < N_HASHES; i++) POWERS[i] = BIG_ALPHA.modPow(BIG_PL, BIG_MODS[i]).longValue(); @@ -121,7 +121,7 @@ public static List rabinKarpBackwards(String text, String pattern) { long[] patternHash = computeHash(pattern); long[] rollingHash = computeHash(text.substring(TL - PL, TL)); - final BigInteger BIG_PL = new BigInteger(String.valueOf(PL)); + final BigInteger BIG_PL = BigInteger.valueOf(PL); final long[] POWERS = new long[N_HASHES]; for (int i = 0; i < N_HASHES; i++) POWERS[i] = BIG_ALPHA.modPow(BIG_PL, BIG_MODS[i]).longValue(); diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/balancedtree/AVLTreeTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/balancedtree/AVLTreeTest.java index 5d1b1884f..9461291e3 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/balancedtree/AVLTreeTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/balancedtree/AVLTreeTest.java @@ -6,8 +6,7 @@ import java.util.Collections; import java.util.List; import java.util.TreeSet; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.*; public class AVLTreeTest { @@ -18,7 +17,7 @@ public class AVLTreeTest { private AVLTreeRecursive tree; - @Before + @BeforeEach public void setup() { tree = new AVLTreeRecursive<>(); } diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/balancedtree/RedBlackTreeTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/balancedtree/RedBlackTreeTest.java index e795624cc..dd4e536cf 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/balancedtree/RedBlackTreeTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/balancedtree/RedBlackTreeTest.java @@ -1,10 +1,10 @@ package com.williamfiset.algorithms.datastructures.balancedtree; import static com.google.common.truth.Truth.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.*; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.*; public class RedBlackTreeTest { @@ -15,14 +15,14 @@ public class RedBlackTreeTest { private RedBlackTree tree; - @Before + @BeforeEach public void setup() { tree = new RedBlackTree<>(); } - @Test(expected = IllegalArgumentException.class) + @Test public void testNullInsertion() { - tree.insert(null); + assertThrows(IllegalArgumentException.class, () -> tree.insert(null)); } @Test diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/balancedtree/TreapTreeTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/balancedtree/TreapTreeTest.java index 7a6cb863f..51f469e8b 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/balancedtree/TreapTreeTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/balancedtree/TreapTreeTest.java @@ -1,13 +1,13 @@ package com.williamfiset.algorithms.datastructures.balancedtree; import static com.google.common.truth.Truth.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.TreeSet; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.*; public class TreapTreeTest { @@ -18,14 +18,14 @@ public class TreapTreeTest { private TreapTree tree; - @Before + @BeforeEach public void setup() { tree = new TreapTree<>(); } - @Test(expected = IllegalArgumentException.class) + @Test public void testNullInsertion() { - tree.insert(null); + assertThrows(IllegalArgumentException.class, () -> tree.insert(null)); } @Test diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/binarysearchtree/BinarySearchTreeTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/binarysearchtree/BinarySearchTreeTest.java index 33463d770..71705f7e1 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/binarysearchtree/BinarySearchTreeTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/binarysearchtree/BinarySearchTreeTest.java @@ -1,6 +1,7 @@ package com.williamfiset.algorithms.datastructures.binarysearchtree; import static com.google.common.truth.Truth.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.ArrayDeque; import java.util.ArrayList; @@ -9,8 +10,7 @@ import java.util.Deque; import java.util.Iterator; import java.util.List; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.*; class TestTreeNode { @@ -84,7 +84,7 @@ public class BinarySearchTreeTest { static final int LOOPS = 100; - @Before + @BeforeEach public void setup() {} @Test @@ -202,7 +202,7 @@ public void testContains() { assertThat(tree.contains('C')).isTrue(); } - @Test(expected = ConcurrentModificationException.class) + @Test public void concurrentModificationErrorPreOrder() { BinarySearchTree bst = new BinarySearchTree<>(); @@ -213,13 +213,17 @@ public void concurrentModificationErrorPreOrder() { Iterator iter = bst.traverse(TreeTraversalOrder.PRE_ORDER); - while (iter.hasNext()) { - bst.add(0); - iter.next(); - } + assertThrows( + ConcurrentModificationException.class, + () -> { + while (iter.hasNext()) { + bst.add(0); + iter.next(); + } + }); } - @Test(expected = ConcurrentModificationException.class) + @Test public void concurrentModificationErrorInOrderOrder() { BinarySearchTree bst = new BinarySearchTree<>(); @@ -230,13 +234,17 @@ public void concurrentModificationErrorInOrderOrder() { Iterator iter = bst.traverse(TreeTraversalOrder.IN_ORDER); - while (iter.hasNext()) { - bst.add(0); - iter.next(); - } + assertThrows( + ConcurrentModificationException.class, + () -> { + while (iter.hasNext()) { + bst.add(0); + iter.next(); + } + }); } - @Test(expected = ConcurrentModificationException.class) + @Test public void concurrentModificationErrorPostOrder() { BinarySearchTree bst = new BinarySearchTree<>(); @@ -247,13 +255,17 @@ public void concurrentModificationErrorPostOrder() { Iterator iter = bst.traverse(TreeTraversalOrder.POST_ORDER); - while (iter.hasNext()) { - bst.add(0); - iter.next(); - } + assertThrows( + ConcurrentModificationException.class, + () -> { + while (iter.hasNext()) { + bst.add(0); + iter.next(); + } + }); } - @Test(expected = ConcurrentModificationException.class) + @Test public void concurrentModificationErrorLevelOrder() { BinarySearchTree bst = new BinarySearchTree<>(); @@ -264,13 +276,17 @@ public void concurrentModificationErrorLevelOrder() { Iterator iter = bst.traverse(TreeTraversalOrder.LEVEL_ORDER); - while (iter.hasNext()) { - bst.add(0); - iter.next(); - } + assertThrows( + ConcurrentModificationException.class, + () -> { + while (iter.hasNext()) { + bst.add(0); + iter.next(); + } + }); } - @Test(expected = ConcurrentModificationException.class) + @Test public void concurrentModificationErrorRemovingPreOrder() { BinarySearchTree bst = new BinarySearchTree<>(); @@ -281,13 +297,17 @@ public void concurrentModificationErrorRemovingPreOrder() { Iterator iter = bst.traverse(TreeTraversalOrder.PRE_ORDER); - while (iter.hasNext()) { - bst.remove(2); - iter.next(); - } + assertThrows( + ConcurrentModificationException.class, + () -> { + while (iter.hasNext()) { + bst.remove(2); + iter.next(); + } + }); } - @Test(expected = ConcurrentModificationException.class) + @Test public void concurrentModificationErrorRemovingInOrderOrder() { BinarySearchTree bst = new BinarySearchTree<>(); @@ -298,13 +318,17 @@ public void concurrentModificationErrorRemovingInOrderOrder() { Iterator iter = bst.traverse(TreeTraversalOrder.IN_ORDER); - while (iter.hasNext()) { - bst.remove(2); - iter.next(); - } + assertThrows( + ConcurrentModificationException.class, + () -> { + while (iter.hasNext()) { + bst.remove(2); + iter.next(); + } + }); } - @Test(expected = ConcurrentModificationException.class) + @Test public void concurrentModificationErrorRemovingPostOrder() { BinarySearchTree bst = new BinarySearchTree<>(); @@ -315,13 +339,17 @@ public void concurrentModificationErrorRemovingPostOrder() { Iterator iter = bst.traverse(TreeTraversalOrder.POST_ORDER); - while (iter.hasNext()) { - bst.remove(2); - iter.next(); - } + assertThrows( + ConcurrentModificationException.class, + () -> { + while (iter.hasNext()) { + bst.remove(2); + iter.next(); + } + }); } - @Test(expected = ConcurrentModificationException.class) + @Test public void concurrentModificationErrorRemovingLevelOrder() { BinarySearchTree bst = new BinarySearchTree<>(); @@ -332,10 +360,14 @@ public void concurrentModificationErrorRemovingLevelOrder() { Iterator iter = bst.traverse(TreeTraversalOrder.LEVEL_ORDER); - while (iter.hasNext()) { - bst.remove(2); - iter.next(); - } + assertThrows( + ConcurrentModificationException.class, + () -> { + while (iter.hasNext()) { + bst.remove(2); + iter.next(); + } + }); } @Test diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/binarysearchtree/SplayTreeTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/binarysearchtree/SplayTreeTest.java index ec017ea13..70ef27d5b 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/binarysearchtree/SplayTreeTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/binarysearchtree/SplayTreeTest.java @@ -4,7 +4,7 @@ import com.williamfiset.algorithms.datastructures.utils.TestUtils; import java.util.*; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class SplayTreeTest { diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/bloomfilter/BloomFilterTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/bloomfilter/BloomFilterTest.java index 6caae053e..971018c0b 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/bloomfilter/BloomFilterTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/bloomfilter/BloomFilterTest.java @@ -6,8 +6,7 @@ import java.util.HashSet; import java.util.Random; import java.util.Set; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.*; public class BloomFilterTest { @@ -20,7 +19,7 @@ public class BloomFilterTest { static final int TEST_SZ = 1000; static final int LOOPS = 1000; - @Before + @BeforeEach public void setup() {} @Test diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/dynamicarray/DynamicArrayTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/dynamicarray/DynamicArrayTest.java deleted file mode 100644 index 3ba0c8c9e..000000000 --- a/src/test/java/com/williamfiset/algorithms/datastructures/dynamicarray/DynamicArrayTest.java +++ /dev/null @@ -1,221 +0,0 @@ -package com.williamfiset.algorithms.datastructures.dynamicarray; - -import static com.google.common.truth.Truth.assertThat; - -import org.junit.Test; - -public class DynamicArrayTest { - - @Test - public void testEmptyList() { - DynamicArray list = new DynamicArray<>(); - assertThat(list.isEmpty()).isTrue(); - } - - @Test(expected = Exception.class) - public void testRemovingEmpty() { - DynamicArray list = new DynamicArray<>(); - list.removeAt(0); - } - - @Test(expected = Exception.class) - public void testIndexOutOfBounds() { - DynamicArray list = new DynamicArray<>(); - list.add(-56); - list.add(-53); - list.add(-55); - list.removeAt(3); - } - - @Test(expected = Exception.class) - public void testIndexOutOfBounds2() { - DynamicArray list = new DynamicArray<>(); - for (int i = 0; i < 1000; i++) list.add(789); - list.removeAt(1000); - } - - @Test(expected = Exception.class) - public void testIndexOutOfBounds3() { - DynamicArray list = new DynamicArray<>(); - for (int i = 0; i < 1000; i++) list.add(789); - list.removeAt(-1); - } - - @Test(expected = Exception.class) - public void testIndexOutOfBounds4() { - DynamicArray list = new DynamicArray<>(); - for (int i = 0; i < 15; i++) list.add(123); - list.removeAt(-66); - } - - @Test(expected = IndexOutOfBoundsException.class) - public void testIndexOutOfBounds5() { - DynamicArray list = new DynamicArray<>(); - for (int i = 0; i < 10; i++) list.add(12); - list.set(-1, 3); - } - - @Test(expected = IndexOutOfBoundsException.class) - public void testIndexOutOfBounds6() { - DynamicArray list = new DynamicArray<>(); - for (int i = 0; i < 10; i++) list.add(12); - list.set(10, 3); - } - - @Test(expected = IndexOutOfBoundsException.class) - public void testIndexOutOfBounds7() { - DynamicArray list = new DynamicArray<>(); - for (int i = 0; i < 10; i++) list.add(12); - list.set(15, 3); - } - - @Test(expected = IndexOutOfBoundsException.class) - public void testIndexOutOfBounds8() { - DynamicArray list = new DynamicArray<>(); - for (int i = 0; i < 10; i++) list.add(12); - list.get(-2); - } - - @Test(expected = IndexOutOfBoundsException.class) - public void testIndexOutOfBounds9() { - DynamicArray list = new DynamicArray<>(); - for (int i = 0; i < 10; i++) list.add(12); - list.get(10); - } - - @Test(expected = IndexOutOfBoundsException.class) - public void testIndexOutOfBounds10() { - DynamicArray list = new DynamicArray<>(); - for (int i = 0; i < 10; i++) list.add(12); - list.get(15); - } - - @Test - public void testRemoving() { - - DynamicArray list = new DynamicArray<>(); - String[] strs = {"a", "b", "c", "d", "e", null, "g", "h"}; - for (String s : strs) list.add(s); - - boolean ret = list.remove("c"); - assertThat(ret).isTrue(); - - ret = list.remove("c"); - assertThat(ret).isFalse(); - - ret = list.remove("h"); - assertThat(ret).isTrue(); - - ret = list.remove(null); - assertThat(ret).isTrue(); - - ret = list.remove("a"); - assertThat(ret).isTrue(); - - ret = list.remove("a"); - assertThat(ret).isFalse(); - - ret = list.remove("h"); - assertThat(ret).isFalse(); - - ret = list.remove(null); - assertThat(ret).isFalse(); - } - - @Test - public void testRemoving2() { - - DynamicArray list = new DynamicArray<>(); - String[] strs = {"a", "b", "c", "d"}; - for (String s : strs) list.add(s); - - assertThat(list.remove("a")).isTrue(); - assertThat(list.remove("b")).isTrue(); - assertThat(list.remove("c")).isTrue(); - assertThat(list.remove("d")).isTrue(); - - assertThat(list.remove("a")).isFalse(); - assertThat(list.remove("b")).isFalse(); - assertThat(list.remove("c")).isFalse(); - assertThat(list.remove("d")).isFalse(); - } - - @Test - public void testIndexOfNullElement() { - DynamicArray list = new DynamicArray<>(); - String[] strs = {"a", "b", null, "d"}; - for (String s : strs) list.add(s); - assertThat(list.indexOf(null)).isEqualTo(2); - } - - @Test - public void testAddingElements() { - - DynamicArray list = new DynamicArray<>(); - - int[] elems = {1, 2, 3, 4, 5, 6, 7}; - - for (int i = 0; i < elems.length; i++) list.add(elems[i]); - - for (int i = 0; i < elems.length; i++) assertThat(list.get(i).intValue()).isEqualTo(elems[i]); - } - - @Test - public void testAddAndRemove() { - - DynamicArray list = new DynamicArray<>(0); - - for (int i = 0; i < 55; i++) list.add(44L); - for (int i = 0; i < 55; i++) list.remove(44L); - assertThat(list.isEmpty()).isTrue(); - - for (int i = 0; i < 55; i++) list.add(44L); - for (int i = 0; i < 55; i++) list.removeAt(0); - assertThat(list.isEmpty()).isTrue(); - - for (int i = 0; i < 155; i++) list.add(44L); - for (int i = 0; i < 155; i++) list.remove(44L); - assertThat(list.isEmpty()).isTrue(); - - for (int i = 0; i < 155; i++) list.add(44L); - for (int i = 0; i < 155; i++) list.removeAt(0); - assertThat(list.isEmpty()).isTrue(); - } - - @Test - public void testAddSetRemove() { - - DynamicArray list = new DynamicArray<>(0); - - for (int i = 0; i < 55; i++) list.add(44L); - for (int i = 0; i < 55; i++) list.set(i, 33L); - for (int i = 0; i < 55; i++) list.remove(33L); - assertThat(list.isEmpty()).isTrue(); - - for (int i = 0; i < 55; i++) list.add(44L); - for (int i = 0; i < 55; i++) list.set(i, 33L); - for (int i = 0; i < 55; i++) list.removeAt(0); - assertThat(list.isEmpty()).isTrue(); - - for (int i = 0; i < 155; i++) list.add(44L); - for (int i = 0; i < 155; i++) list.set(i, 33L); - for (int i = 0; i < 155; i++) list.remove(33L); - assertThat(list.isEmpty()).isTrue(); - - for (int i = 0; i < 155; i++) list.add(44L); - for (int i = 0; i < 155; i++) list.removeAt(0); - assertThat(list.isEmpty()).isTrue(); - } - - @Test - public void testSize() { - - DynamicArray list = new DynamicArray<>(); - - Integer[] elems = {-76, 45, 66, 3, null, 54, 33}; - for (int i = 0, sz = 1; i < elems.length; i++, sz++) { - list.add(elems[i]); - assertThat(list.size()).isEqualTo(sz); - } - } -} diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/fenwicktree/FenwickTreeRangeQueryPointUpdateTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/fenwicktree/FenwickTreeRangeQueryPointUpdateTest.java index ce879c710..30cf0caef 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/fenwicktree/FenwickTreeRangeQueryPointUpdateTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/fenwicktree/FenwickTreeRangeQueryPointUpdateTest.java @@ -1,9 +1,9 @@ package com.williamfiset.algorithms.datastructures.fenwicktree; import static com.google.common.truth.Truth.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.*; public class FenwickTreeRangeQueryPointUpdateTest { @@ -15,7 +15,7 @@ public class FenwickTreeRangeQueryPointUpdateTest { static long UNUSED_VAL; - @Before + @BeforeEach public void setup() { UNUSED_VAL = randValue(); } @@ -169,9 +169,9 @@ public static long randValue() { return (long) (Math.random() * MAX_RAND_NUM * 2) + MIN_RAND_NUM; } - @Test(expected = IllegalArgumentException.class) + @Test public void testIllegalCreation() { - new FenwickTreeRangeQueryPointUpdate(null); + assertThrows(IllegalArgumentException.class, () -> new FenwickTreeRangeQueryPointUpdate(null)); } // Generate a list of random numbers, one based diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/fenwicktree/FenwickTreeRangeUpdatePointQueryTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/fenwicktree/FenwickTreeRangeUpdatePointQueryTest.java index 8c17d45cd..13e34e35f 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/fenwicktree/FenwickTreeRangeUpdatePointQueryTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/fenwicktree/FenwickTreeRangeUpdatePointQueryTest.java @@ -1,9 +1,9 @@ package com.williamfiset.algorithms.datastructures.fenwicktree; import static com.google.common.truth.Truth.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.*; public class FenwickTreeRangeUpdatePointQueryTest { @@ -31,14 +31,14 @@ public void updateRange(int i, int j, long v) { static long UNUSED_VAL; - @Before + @BeforeEach public void setup() { UNUSED_VAL = randValue(); } - @Test(expected = IllegalArgumentException.class) + @Test public void testIllegalCreation() { - new FenwickTreeRangeUpdatePointQuery(null); + assertThrows(IllegalArgumentException.class, () -> new FenwickTreeRangeUpdatePointQuery(null)); } @Test diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/fibonacciheap/FibonacciHeapTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/fibonacciheap/FibonacciHeapTest.java index 3c8159eef..ec59f0bab 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/fibonacciheap/FibonacciHeapTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/fibonacciheap/FibonacciHeapTest.java @@ -2,6 +2,7 @@ import static com.google.common.truth.Truth.assertThat; import static java.util.Collections.sort; +import static org.junit.jupiter.api.Assertions.*; import java.util.ArrayList; import java.util.Collection; @@ -9,9 +10,7 @@ import java.util.NoSuchElementException; import java.util.Queue; import java.util.Random; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.*; // Disclaimer: Based by help of // "http://langrsoft.com/jeff/2011/11/test-driving-a-heap-based-priority-queue/">Test-Driving a @@ -22,12 +21,12 @@ public final class FibonacciHeapTest { private Queue queue; - @Before + @BeforeEach public void setUp() { queue = new FibonacciHeap(); } - @After + @AfterEach public void tearDown() { queue = null; } @@ -157,8 +156,8 @@ public void offerPeekAndElement() { assertThat(queue.size()).isEqualTo(4); } - @Test(expected = NoSuchElementException.class) + @Test public void elementThrowsException() { - queue.element(); + assertThrows(NoSuchElementException.class, () -> queue.element()); } } diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/hashtable/DoubleHashingTestObject.java b/src/test/java/com/williamfiset/algorithms/datastructures/hashtable/DoubleHashingTestObject.java index 3e1395032..a65c6c85d 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/hashtable/DoubleHashingTestObject.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/hashtable/DoubleHashingTestObject.java @@ -88,10 +88,13 @@ public int hashCode2() { @Override public boolean equals(Object o) { - DoubleHashingTestObject obj = (DoubleHashingTestObject) o; - if (hash != obj.hash) return false; - if (intData != null) return intData.equals(obj.intData); - if (vectorData != null) return java.util.Arrays.equals(vectorData, obj.vectorData); - return stringData.equals(obj.stringData); + if (this == o) return true; + else if (o instanceof DoubleHashingTestObject) { + DoubleHashingTestObject obj = (DoubleHashingTestObject) o; + if (hash != obj.hash) return false; + if (intData != null) return intData.equals(obj.intData); + if (vectorData != null) return java.util.Arrays.equals(vectorData, obj.vectorData); + return stringData.equals(obj.stringData); + } else return false; } } diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableDoubleHashingTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableDoubleHashingTest.java index 0df5d4488..982658a61 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableDoubleHashingTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableDoubleHashingTest.java @@ -1,9 +1,10 @@ package com.williamfiset.algorithms.datastructures.hashtable; import static com.google.common.truth.Truth.assertThat; +import static org.junit.jupiter.api.Assertions.*; import java.util.*; -import org.junit.*; +import org.junit.jupiter.api.*; public class HashTableDoubleHashingTest { @@ -18,35 +19,32 @@ public class HashTableDoubleHashingTest { HashTableDoubleHashing map; - @Before + @BeforeEach public void setup() { map = new HashTableDoubleHashing<>(); } - @Test(expected = IllegalArgumentException.class) - public void testNullKey() { - map.put(null, 5); - } - - @Test(expected = IllegalArgumentException.class) + @Test public void testIllegalCreation1() { - new HashTableDoubleHashing<>(-3, 0.5); + assertThrows(IllegalArgumentException.class, () -> new HashTableDoubleHashing<>(-3, 0.5)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testIllegalCreation2() { - new HashTableDoubleHashing<>(5, Double.POSITIVE_INFINITY); + assertThrows( + IllegalArgumentException.class, + () -> new HashTableDoubleHashing<>(5, Double.POSITIVE_INFINITY)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testIllegalCreation3() { - new HashTableDoubleHashing<>(6, -0.5); + assertThrows(IllegalArgumentException.class, () -> new HashTableDoubleHashing<>(6, -0.5)); } @Test public void testLegalCreation() { // System.out.println("testLegalCreation"); - new HashTableDoubleHashing<>(6, 0.9); + assertDoesNotThrow(() -> new HashTableDoubleHashing<>(6, 0.9)); } @Test @@ -107,28 +105,36 @@ public void testIterator() { } } - @Test(expected = java.util.ConcurrentModificationException.class) + @Test public void testConcurrentModificationException() { - // System.out.println("testConcurrentModificationException"); - DoubleHashingTestObject o1 = new DoubleHashingTestObject(1); - DoubleHashingTestObject o2 = new DoubleHashingTestObject(2); - DoubleHashingTestObject o3 = new DoubleHashingTestObject(3); - DoubleHashingTestObject o4 = new DoubleHashingTestObject(4); - map.add(o1, 1); - map.add(o2, 1); - map.add(o3, 1); - for (DoubleHashingTestObject key : map) map.add(o4, 4); + assertThrows( + ConcurrentModificationException.class, + () -> { + // System.out.println("testConcurrentModificationException"); + DoubleHashingTestObject o1 = new DoubleHashingTestObject(1); + DoubleHashingTestObject o2 = new DoubleHashingTestObject(2); + DoubleHashingTestObject o3 = new DoubleHashingTestObject(3); + DoubleHashingTestObject o4 = new DoubleHashingTestObject(4); + map.add(o1, 1); + map.add(o2, 1); + map.add(o3, 1); + for (DoubleHashingTestObject key : map) map.add(o4, 4); + }); } - @Test(expected = java.util.ConcurrentModificationException.class) + @Test public void testConcurrentModificationException2() { - DoubleHashingTestObject o1 = new DoubleHashingTestObject(1); - DoubleHashingTestObject o2 = new DoubleHashingTestObject(2); - DoubleHashingTestObject o3 = new DoubleHashingTestObject(3); - map.add(o1, 1); - map.add(o2, 1); - map.add(o3, 1); - for (DoubleHashingTestObject key : map) map.remove(o2); + assertThrows( + ConcurrentModificationException.class, + () -> { + DoubleHashingTestObject o1 = new DoubleHashingTestObject(1); + DoubleHashingTestObject o2 = new DoubleHashingTestObject(2); + DoubleHashingTestObject o3 = new DoubleHashingTestObject(3); + map.add(o1, 1); + map.add(o2, 1); + map.add(o3, 1); + for (DoubleHashingTestObject key : map) map.remove(o2); + }); } @Test diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableLinearProbingTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableLinearProbingTest.java index f5ccfe0d2..f18806fd0 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableLinearProbingTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableLinearProbingTest.java @@ -1,9 +1,10 @@ package com.williamfiset.algorithms.datastructures.hashtable; import static com.google.common.truth.Truth.assertThat; +import static org.junit.jupiter.api.Assertions.*; import java.util.*; -import org.junit.*; +import org.junit.jupiter.api.*; public class HashTableLinearProbingTest { @@ -24,8 +25,12 @@ public int hashCode() { @Override public boolean equals(Object o) { - HashObject ho = (HashObject) o; - return hashCode() == ho.hashCode() && data == ho.data; + if (this == o) return true; + else if (o instanceof HashObject) { + HashObject ho = (HashObject) o; + return hashCode() == ho.hashCode() && data == ho.data; + } + return false; } } @@ -40,34 +45,36 @@ public boolean equals(Object o) { HashTableLinearProbing map; - @Before + @BeforeEach public void setup() { map = new HashTableLinearProbing<>(); } - @Test(expected = IllegalArgumentException.class) + @Test public void testNullKey() { - map.put(null, 5); + assertThrows(IllegalArgumentException.class, () -> map.put(null, 5)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testIllegalCreation1() { - new HashTableLinearProbing<>(-3, 0.5); + assertThrows(IllegalArgumentException.class, () -> new HashTableLinearProbing<>(-3, 0.5)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testIllegalCreation2() { - new HashTableLinearProbing<>(5, Double.POSITIVE_INFINITY); + assertThrows( + IllegalArgumentException.class, + () -> new HashTableLinearProbing<>(5, Double.POSITIVE_INFINITY)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testIllegalCreation3() { - new HashTableLinearProbing<>(6, -0.5); + assertThrows(IllegalArgumentException.class, () -> new HashTableLinearProbing<>(6, -0.5)); } @Test public void testLegalCreation() { - new HashTableLinearProbing<>(6, 0.9); + assertDoesNotThrow(() -> new HashTableLinearProbing<>(6, 0.9)); } @Test @@ -120,20 +127,28 @@ public void testIterator() { } } - @Test(expected = java.util.ConcurrentModificationException.class) + @Test public void testConcurrentModificationException() { - map.add(1, 1); - map.add(2, 1); - map.add(3, 1); - for (Integer key : map) map.add(4, 4); + assertThrows( + ConcurrentModificationException.class, + () -> { + map.add(1, 1); + map.add(2, 1); + map.add(3, 1); + for (Integer key : map) map.add(4, 4); + }); } - @Test(expected = java.util.ConcurrentModificationException.class) + @Test public void testConcurrentModificationException2() { - map.add(1, 1); - map.add(2, 1); - map.add(3, 1); - for (Integer key : map) map.remove(2); + assertThrows( + ConcurrentModificationException.class, + () -> { + map.add(1, 1); + map.add(2, 1); + map.add(3, 1); + for (Integer key : map) map.remove(2); + }); } @Test diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableQuadraticProbingTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableQuadraticProbingTest.java index 57f06c6dc..13c1daad5 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableQuadraticProbingTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableQuadraticProbingTest.java @@ -1,9 +1,10 @@ package com.williamfiset.algorithms.datastructures.hashtable; import static com.google.common.truth.Truth.assertThat; +import static org.junit.jupiter.api.Assertions.*; import java.util.*; -import org.junit.*; +import org.junit.jupiter.api.*; public class HashTableQuadraticProbingTest { @@ -24,8 +25,11 @@ public int hashCode() { @Override public boolean equals(Object o) { - HashObject ho = (HashObject) o; - return hashCode() == ho.hashCode() && data == ho.data; + if (this == o) return true; + else if (o instanceof HashObject) { + HashObject ho = (HashObject) o; + return hashCode() == ho.hashCode() && data == ho.data; + } else return false; } } @@ -40,34 +44,36 @@ public boolean equals(Object o) { HashTableQuadraticProbing map; - @Before + @BeforeEach public void setup() { map = new HashTableQuadraticProbing<>(); } - @Test(expected = IllegalArgumentException.class) + @Test public void testNullKey() { - map.put(null, 5); + assertThrows(IllegalArgumentException.class, () -> map.put(null, 5)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testIllegalCreation1() { - new HashTableQuadraticProbing<>(-3, 0.5); + assertThrows(IllegalArgumentException.class, () -> new HashTableQuadraticProbing<>(-3, 0.5)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testIllegalCreation2() { - new HashTableQuadraticProbing<>(5, Double.POSITIVE_INFINITY); + assertThrows( + IllegalArgumentException.class, + () -> new HashTableQuadraticProbing<>(5, Double.POSITIVE_INFINITY)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testIllegalCreation3() { - new HashTableQuadraticProbing<>(6, -0.5); + assertThrows(IllegalArgumentException.class, () -> new HashTableQuadraticProbing<>(6, -0.5)); } @Test public void testLegalCreation() { - new HashTableQuadraticProbing<>(6, 0.9); + assertDoesNotThrow(() -> new HashTableQuadraticProbing<>(6, 0.9)); } @Test @@ -141,20 +147,28 @@ public void testIterator() { } } - @Test(expected = java.util.ConcurrentModificationException.class) + @Test public void testConcurrentModificationException() { - map.add(1, 1); - map.add(2, 1); - map.add(3, 1); - for (Integer key : map) map.add(4, 4); + assertThrows( + ConcurrentModificationException.class, + () -> { + map.add(1, 1); + map.add(2, 1); + map.add(3, 1); + for (Integer key : map) map.add(4, 4); + }); } - @Test(expected = java.util.ConcurrentModificationException.class) + @Test public void testConcurrentModificationException2() { - map.add(1, 1); - map.add(2, 1); - map.add(3, 1); - for (Integer key : map) map.remove(2); + assertThrows( + ConcurrentModificationException.class, + () -> { + map.add(1, 1); + map.add(2, 1); + map.add(3, 1); + for (Integer key : map) map.remove(2); + }); } @Test diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableSeparateChainingTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableSeparateChainingTest.java index 861f90bef..84518b394 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableSeparateChainingTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableSeparateChainingTest.java @@ -1,9 +1,10 @@ package com.williamfiset.algorithms.datastructures.hashtable; import static com.google.common.truth.Truth.assertThat; +import static org.junit.jupiter.api.Assertions.*; import java.util.*; -import org.junit.*; +import org.junit.jupiter.api.*; public class HashTableSeparateChainingTest { @@ -24,8 +25,11 @@ public int hashCode() { @Override public boolean equals(Object o) { - HashObject ho = (HashObject) o; - return hashCode() == ho.hashCode() && data == ho.data; + if (this == o) return true; + else if (o instanceof HashObject) { + HashObject ho = (HashObject) o; + return hashCode() == ho.hashCode() && data == ho.data; + } else return false; } } @@ -40,34 +44,31 @@ public boolean equals(Object o) { HashTableSeparateChaining map; - @Before + @BeforeEach public void setup() { map = new HashTableSeparateChaining<>(); } - @Test(expected = IllegalArgumentException.class) - public void testNullKey() { - map.put(null, 5); - } - - @Test(expected = IllegalArgumentException.class) + @Test public void testIllegalCreation1() { - new HashTableSeparateChaining<>(-3, 0.5); + assertThrows(IllegalArgumentException.class, () -> new HashTableSeparateChaining<>(-3, 0.5)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testIllegalCreation2() { - new HashTableSeparateChaining<>(5, Double.POSITIVE_INFINITY); + assertThrows( + IllegalArgumentException.class, + () -> new HashTableSeparateChaining<>(5, Double.POSITIVE_INFINITY)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testIllegalCreation3() { - new HashTableSeparateChaining<>(6, -0.5); + assertThrows(IllegalArgumentException.class, () -> new HashTableSeparateChaining<>(6, -0.5)); } @Test public void testLegalCreation() { - new HashTableSeparateChaining<>(6, 0.9); + assertDoesNotThrow(() -> new HashTableSeparateChaining<>(6, 0.9)); } @Test @@ -120,20 +121,28 @@ public void testIterator() { } } - @Test(expected = java.util.ConcurrentModificationException.class) + @Test public void testConcurrentModificationException() { - map.add(1, 1); - map.add(2, 1); - map.add(3, 1); - for (Integer key : map) map.add(4, 4); + assertThrows( + ConcurrentModificationException.class, + () -> { + map.add(1, 1); + map.add(2, 1); + map.add(3, 1); + for (Integer key : map) map.add(4, 4); + }); } - @Test(expected = java.util.ConcurrentModificationException.class) + @Test public void testConcurrentModificationException2() { - map.add(1, 1); - map.add(2, 1); - map.add(3, 1); - for (Integer key : map) map.remove(2); + assertThrows( + ConcurrentModificationException.class, + () -> { + map.add(1, 1); + map.add(2, 1); + map.add(3, 1); + for (Integer key : map) map.remove(2); + }); } @Test diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/kdtree/GeneralKDTreeTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/kdtree/GeneralKDTreeTest.java index 9e7855144..4d2005331 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/kdtree/GeneralKDTreeTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/kdtree/GeneralKDTreeTest.java @@ -1,20 +1,21 @@ package com.williamfiset.algorithms.datastructures.kdtree; import static com.google.common.truth.Truth.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class GeneralKDTreeTest { /* TREE CREATION TESTS */ - @Test(expected = IllegalArgumentException.class) + @Test public void testDimensionsZero() { - new GeneralKDTree<>(0); + assertThrows(IllegalArgumentException.class, () -> new GeneralKDTree<>(0)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testDimensionsNegative() { - new GeneralKDTree<>(-5); + assertThrows(IllegalArgumentException.class, () -> new GeneralKDTree<>(-5)); } /* INSERT METHOD TESTS */ @@ -32,16 +33,16 @@ public void testInsert() { assertThat(kdTree.getRootPoint() == pointRoot).isTrue(); } - @Test(expected = IllegalArgumentException.class) + @Test public void testInsertNull() { GeneralKDTree kdTree = new GeneralKDTree(2); - kdTree.insert(null); + assertThrows(IllegalArgumentException.class, () -> kdTree.insert(null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testInsertMismatchDimensions() { GeneralKDTree kdTree = new GeneralKDTree(2); - kdTree.insert(new Integer[] {1, 2, 3}); + assertThrows(IllegalArgumentException.class, () -> kdTree.insert(new Integer[] {1, 2, 3})); } /* SEARCH METHOD TESTS */ @@ -64,16 +65,16 @@ public void testSearch() { assertThat(kdTree.search(new Integer[] {7, 5, 4, 9})).isFalse(); } - @Test(expected = IllegalArgumentException.class) + @Test public void testSearchNull() { GeneralKDTree kdTree = new GeneralKDTree(2); - kdTree.search(null); + assertThrows(IllegalArgumentException.class, () -> kdTree.search(null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testSearchMismatchDimensions() { GeneralKDTree kdTree = new GeneralKDTree(2); - kdTree.search(new Integer[] {1, 2, 3}); + assertThrows(IllegalArgumentException.class, () -> kdTree.search(new Integer[] {1, 2, 3})); } /* FINDMIN METHOD TESTS */ @@ -97,16 +98,16 @@ public void testFindMin() { assertThat(kdTree.findMin(2) == min3).isTrue(); } - @Test(expected = IllegalArgumentException.class) + @Test public void testFindMinOutOfBounds() { GeneralKDTree kdTree = new GeneralKDTree(2); - kdTree.findMin(2); + assertThrows(IllegalArgumentException.class, () -> kdTree.findMin(2)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testFindMinNegative() { GeneralKDTree kdTree = new GeneralKDTree(2); - kdTree.findMin(-1); + assertThrows(IllegalArgumentException.class, () -> kdTree.findMin(-1)); } /* DELETE METHOD TESTS */ @@ -172,15 +173,15 @@ public void testDelete() { assertThat(kdTree.delete(point8) == null).isTrue(); } - @Test(expected = IllegalArgumentException.class) + @Test public void testDeleteNull() { GeneralKDTree kdTree = new GeneralKDTree(2); - kdTree.delete(null); + assertThrows(IllegalArgumentException.class, () -> kdTree.delete(null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testDeleteMismatchDimensions() { GeneralKDTree kdTree = new GeneralKDTree(2); - kdTree.delete(new Integer[] {1, 2, 3}); + assertThrows(IllegalArgumentException.class, () -> kdTree.delete(new Integer[] {1, 2, 3})); } } diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/linkedlist/LinkedListTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/linkedlist/LinkedListTest.java index 7cb8ec4e8..70cbaaad7 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/linkedlist/LinkedListTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/linkedlist/LinkedListTest.java @@ -1,11 +1,12 @@ package com.williamfiset.algorithms.datastructures.linkedlist; import static com.google.common.truth.Truth.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import org.junit.*; +import org.junit.jupiter.api.*; public class LinkedListTest { private static final int LOOPS = 10000; @@ -15,7 +16,7 @@ public class LinkedListTest { DoublyLinkedList list; - @Before + @BeforeEach public void setup() { list = new DoublyLinkedList<>(); } @@ -26,24 +27,24 @@ public void testEmptyList() { assertThat(list.size()).isEqualTo(0); } - @Test(expected = Exception.class) + @Test public void testRemoveFirstOfEmpty() { - list.removeFirst(); + assertThrows(Exception.class, () -> list.removeFirst()); } - @Test(expected = Exception.class) + @Test public void testRemoveLastOfEmpty() { - list.removeLast(); + assertThrows(Exception.class, () -> list.removeLast()); } - @Test(expected = Exception.class) + @Test public void testPeekFirstOfEmpty() { - list.peekFirst(); + assertThrows(Exception.class, () -> list.peekFirst()); } - @Test(expected = Exception.class) + @Test public void testPeekLastOfEmpty() { - list.peekLast(); + assertThrows(Exception.class, () -> list.peekLast()); } @Test diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/priorityqueue/BinaryHeapQuickRemovalsTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/priorityqueue/BinaryHeapQuickRemovalsTest.java index 7471b6de9..0d52de160 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/priorityqueue/BinaryHeapQuickRemovalsTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/priorityqueue/BinaryHeapQuickRemovalsTest.java @@ -6,14 +6,14 @@ import java.util.Collections; import java.util.List; import java.util.PriorityQueue; -import org.junit.*; +import org.junit.jupiter.api.*; public class BinaryHeapQuickRemovalsTest { static final int LOOPS = 100; static final int MAX_SZ = 100; - @Before + @BeforeEach public void setup() {} @Test diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/priorityqueue/BinaryHeapTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/priorityqueue/BinaryHeapTest.java index 8ac198d13..f85cb9c7a 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/priorityqueue/BinaryHeapTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/priorityqueue/BinaryHeapTest.java @@ -6,14 +6,14 @@ import java.util.Collections; import java.util.List; import java.util.PriorityQueue; -import org.junit.*; +import org.junit.jupiter.api.*; public class BinaryHeapTest { static final int LOOPS = 100; static final int MAX_SZ = 100; - @Before + @BeforeEach public void setup() {} @Test diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/priorityqueue/MinDHeapTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/priorityqueue/MinDHeapTest.java index 23e4e87f0..a36ea404b 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/priorityqueue/MinDHeapTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/priorityqueue/MinDHeapTest.java @@ -6,15 +6,14 @@ import java.util.Collections; import java.util.List; import java.util.PriorityQueue; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.*; public class MinDHeapTest { static final int LOOPS = 1000; static final int MAX_SZ = 100; - @Before + @BeforeEach public void setup() {} @Test @@ -196,6 +195,7 @@ public void testRemovingDuplicates() { assertThat(pq.poll()).isEqualTo(11); assertThat(pq.poll()).isEqualTo(13); } + /* @Test public void testRandomizedPolling() { diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/priorityqueue/MinIndexedBinaryHeapTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/priorityqueue/MinIndexedBinaryHeapTest.java index 9417d7517..eb9565afb 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/priorityqueue/MinIndexedBinaryHeapTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/priorityqueue/MinIndexedBinaryHeapTest.java @@ -1,6 +1,7 @@ package com.williamfiset.algorithms.datastructures.priorityqueue; import static com.google.common.truth.Truth.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.ArrayList; import java.util.Arrays; @@ -9,21 +10,21 @@ import java.util.List; import java.util.PriorityQueue; import java.util.Random; -import org.junit.*; +import org.junit.jupiter.api.*; public class MinIndexedBinaryHeapTest { - @Before + @BeforeEach public void setup() {} - @Test(expected = IllegalArgumentException.class) + @Test public void testIllegalSizeOfNegativeOne() { - new MinIndexedBinaryHeap(-1); + assertThrows(IllegalArgumentException.class, () -> new MinIndexedBinaryHeap(-1)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testIllegalSizeOfZero() { - new MinIndexedBinaryHeap(0); + assertThrows(IllegalArgumentException.class, () -> new MinIndexedBinaryHeap(0)); } @Test @@ -45,11 +46,15 @@ public void testContainsInvalidKey() { assertThat(pq.contains(3)).isFalse(); } - @Test(expected = IllegalArgumentException.class) + @Test public void testDuplicateKeys() { - MinIndexedBinaryHeap pq = new MinIndexedBinaryHeap(10); - pq.insert(5, "abcdef"); - pq.insert(5, "xyz"); + assertThrows( + IllegalArgumentException.class, + () -> { + MinIndexedBinaryHeap pq = new MinIndexedBinaryHeap(10); + pq.insert(5, "abcdef"); + pq.insert(5, "xyz"); + }); } @Test diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/quadtree/QuadTreeTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/quadtree/QuadTreeTest.java index 184c35f9f..6a34e3ecf 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/quadtree/QuadTreeTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/quadtree/QuadTreeTest.java @@ -2,8 +2,7 @@ import static com.google.common.truth.Truth.assertThat; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.*; public class QuadTreeTest { @@ -11,7 +10,7 @@ public class QuadTreeTest { static final int TEST_SZ = 1000; static final int MAX_RAND_NUM = +2000; - @Before + @BeforeEach public void setup() {} @Test diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/queue/IntQueueTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/queue/IntQueueTest.java index 0a8ad905f..2a5dfd4a0 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/queue/IntQueueTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/queue/IntQueueTest.java @@ -3,12 +3,11 @@ import static com.google.common.truth.Truth.assertThat; import java.util.*; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.*; public class IntQueueTest { - @Before + @BeforeEach public void setup() {} @Test diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/queue/QueueTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/queue/QueueTest.java index 1fff5d519..b045ee8dc 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/queue/QueueTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/queue/QueueTest.java @@ -1,88 +1,81 @@ package com.williamfiset.algorithms.datastructures.queue; import static com.google.common.truth.Truth.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.ArrayList; import java.util.List; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class QueueTest { - private List> queues = new ArrayList<>(); - - @Before - public void setup() { + private static List> inputs() { + List> queues = new ArrayList<>(); queues.add(new ArrayQueue(2)); queues.add(new LinkedQueue()); queues.add(new IntQueue(2)); + return queues; } - @Test - public void testEmptyQueue() { - for (Queue queue : queues) { - assertThat(queue.isEmpty()).isTrue(); - assertThat(queue.size()).isEqualTo(0); - } + @ParameterizedTest + @MethodSource("inputs") + public void testEmptyQueue(Queue queue) { + assertThat(queue.isEmpty()).isTrue(); + assertThat(queue.size()).isEqualTo(0); } - @Test(expected = Exception.class) - public void testPollOnEmpty() { - for (Queue queue : queues) { - queue.poll(); - } + @ParameterizedTest + @MethodSource("inputs") + public void testPollOnEmpty(Queue queue) { + assertThrows(Exception.class, () -> queue.poll()); } - @Test(expected = Exception.class) - public void testPeekOnEmpty() { - for (Queue queue : queues) { - queue.peek(); - } + @ParameterizedTest + @MethodSource("inputs") + public void testPeekOnEmpty(Queue queue) { + assertThrows(Exception.class, () -> queue.peek()); } - @Test - public void testOffer() { - for (Queue queue : queues) { - queue.offer(2); - assertThat(queue.size()).isEqualTo(1); - } + @ParameterizedTest + @MethodSource("inputs") + public void testOffer(Queue queue) { + queue.offer(2); + assertThat(queue.size()).isEqualTo(1); } - @Test - public void testPeek() { - for (Queue queue : queues) { - queue.offer(2); - assertThat((int) queue.peek()).isEqualTo(2); - assertThat(queue.size()).isEqualTo(1); - } + @ParameterizedTest + @MethodSource("inputs") + public void testPeek(Queue queue) { + queue.offer(2); + assertThat((int) queue.peek()).isEqualTo(2); + assertThat(queue.size()).isEqualTo(1); } - @Test - public void testPoll() { - for (Queue queue : queues) { - queue.offer(2); - assertThat((int) queue.poll()).isEqualTo(2); - assertThat(queue.size()).isEqualTo(0); - } + @ParameterizedTest + @MethodSource("inputs") + public void testPoll(Queue queue) { + queue.offer(2); + assertThat((int) queue.poll()).isEqualTo(2); + assertThat(queue.size()).isEqualTo(0); } - @Test - public void testExhaustively() { - for (Queue queue : queues) { - assertThat(queue.isEmpty()).isTrue(); - queue.offer(1); - assertThat(queue.isEmpty()).isFalse(); - queue.offer(2); - assertThat(queue.size()).isEqualTo(2); - assertThat((int) queue.peek()).isEqualTo(1); - assertThat(queue.size()).isEqualTo(2); - assertThat((int) queue.poll()).isEqualTo(1); - assertThat(queue.size()).isEqualTo(1); - assertThat((int) queue.peek()).isEqualTo(2); - assertThat(queue.size()).isEqualTo(1); - assertThat((int) queue.poll()).isEqualTo(2); - assertThat(queue.size()).isEqualTo(0); - assertThat(queue.isEmpty()).isTrue(); - } + @ParameterizedTest + @MethodSource("inputs") + public void testExhaustively(Queue queue) { + assertThat(queue.isEmpty()).isTrue(); + queue.offer(1); + assertThat(queue.isEmpty()).isFalse(); + queue.offer(2); + assertThat(queue.size()).isEqualTo(2); + assertThat((int) queue.peek()).isEqualTo(1); + assertThat(queue.size()).isEqualTo(2); + assertThat((int) queue.poll()).isEqualTo(1); + assertThat(queue.size()).isEqualTo(1); + assertThat((int) queue.peek()).isEqualTo(2); + assertThat(queue.size()).isEqualTo(1); + assertThat((int) queue.poll()).isEqualTo(2); + assertThat(queue.size()).isEqualTo(0); + assertThat(queue.isEmpty()).isTrue(); } } diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/GenericSegmentTree2Test.java b/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/GenericSegmentTree2Test.java index 157bb6d5a..aa36954ab 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/GenericSegmentTree2Test.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/GenericSegmentTree2Test.java @@ -7,15 +7,14 @@ import static com.google.common.truth.Truth.assertThat; import com.williamfiset.algorithms.utils.TestUtils; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.*; public class GenericSegmentTree2Test { static int ITERATIONS = 100; static int MAX_N = 28; - @Before + @BeforeEach public void setup() {} @Test diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/GenericSegmentTreeTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/GenericSegmentTreeTest.java index 7d1dc0616..38d0b4bfe 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/GenericSegmentTreeTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/GenericSegmentTreeTest.java @@ -7,7 +7,7 @@ import static com.google.common.truth.Truth.assertThat; import com.williamfiset.algorithms.utils.TestUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class GenericSegmentTreeTest { diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/MaxQuerySumUpdateSegmentTreeTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/MaxQuerySumUpdateSegmentTreeTest.java index b7db6503e..c1ac5e1af 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/MaxQuerySumUpdateSegmentTreeTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/MaxQuerySumUpdateSegmentTreeTest.java @@ -7,14 +7,13 @@ import static com.google.common.truth.Truth.assertThat; import com.williamfiset.algorithms.utils.TestUtils; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.*; public class MaxQuerySumUpdateSegmentTreeTest { static int ITERATIONS = 1000; - @Before + @BeforeEach public void setup() {} @Test diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/MinQueryAssignUpdateSegmentTreeTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/MinQueryAssignUpdateSegmentTreeTest.java index 287ff0204..e12fd4269 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/MinQueryAssignUpdateSegmentTreeTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/MinQueryAssignUpdateSegmentTreeTest.java @@ -7,14 +7,13 @@ import static com.google.common.truth.Truth.assertThat; import com.williamfiset.algorithms.utils.TestUtils; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.*; public class MinQueryAssignUpdateSegmentTreeTest { static int ITERATIONS = 500; - @Before + @BeforeEach public void setup() {} @Test diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/MinQuerySumUpdateSegmentTreeTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/MinQuerySumUpdateSegmentTreeTest.java index 6d6bf0d55..31b3498a9 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/MinQuerySumUpdateSegmentTreeTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/MinQuerySumUpdateSegmentTreeTest.java @@ -7,14 +7,13 @@ import static com.google.common.truth.Truth.assertThat; import com.williamfiset.algorithms.utils.TestUtils; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.*; public class MinQuerySumUpdateSegmentTreeTest { static int ITERATIONS = 1000; - @Before + @BeforeEach public void setup() {} @Test diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/SegmentTreeWithPointersTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/SegmentTreeWithPointersTest.java index aca53597e..9d9f8374c 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/SegmentTreeWithPointersTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/SegmentTreeWithPointersTest.java @@ -3,25 +3,33 @@ package com.williamfiset.algorithms.datastructures.segmenttree; import static com.google.common.truth.Truth.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.williamfiset.algorithms.utils.TestUtils; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.*; public class SegmentTreeWithPointersTest { - @Before + @BeforeEach public void setup() {} - @Test(expected = IllegalArgumentException.class) + @Test public void testIllegalSegmentTreeCreation1() { - Node tree = new Node(null); + assertThrows( + IllegalArgumentException.class, + () -> { + Node tree = new Node(null); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void testIllegalSegmentTreeCreation2() { - int size = -10; - Node tree = new Node(size); + assertThrows( + IllegalArgumentException.class, + () -> { + int size = -10; + Node tree = new Node(size); + }); } @Test diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/SumQueryAssignUpdateSegmentTreeTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/SumQueryAssignUpdateSegmentTreeTest.java index 3b3b01735..74ac738ea 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/SumQueryAssignUpdateSegmentTreeTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/SumQueryAssignUpdateSegmentTreeTest.java @@ -7,14 +7,13 @@ import static com.google.common.truth.Truth.assertThat; import com.williamfiset.algorithms.utils.TestUtils; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.*; public class SumQueryAssignUpdateSegmentTreeTest { static int ITERATIONS = 100; - @Before + @BeforeEach public void setup() {} @Test diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/SumQueryMultiplicationUpdateSegmentTreeTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/SumQueryMultiplicationUpdateSegmentTreeTest.java index 4e0c26cb0..432fbd98b 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/SumQueryMultiplicationUpdateSegmentTreeTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/SumQueryMultiplicationUpdateSegmentTreeTest.java @@ -7,15 +7,14 @@ import static com.google.common.truth.Truth.assertThat; import com.williamfiset.algorithms.utils.TestUtils; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.*; public class SumQueryMultiplicationUpdateSegmentTreeTest { static int ITERATIONS = 100; static int MAX_N = 28; - @Before + @BeforeEach public void setup() {} @Test diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/SumQuerySumUpdateSegmentTreeTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/SumQuerySumUpdateSegmentTreeTest.java index c45d889b5..f388d1750 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/SumQuerySumUpdateSegmentTreeTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/SumQuerySumUpdateSegmentTreeTest.java @@ -7,14 +7,13 @@ import static com.google.common.truth.Truth.assertThat; import com.williamfiset.algorithms.utils.TestUtils; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.*; public class SumQuerySumUpdateSegmentTreeTest { static int ITERATIONS = 100; - @Before + @BeforeEach public void setup() {} @Test diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/set/HSetTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/set/HSetTest.java index 083cc9ab9..40031a0ba 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/set/HSetTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/set/HSetTest.java @@ -7,7 +7,7 @@ import java.util.HashSet; import java.util.List; import java.util.Random; -import org.junit.*; +import org.junit.jupiter.api.*; // You can set the hash value of this object to be whatever you want // This makes it great for testing special cases. @@ -26,7 +26,9 @@ public int hashCode() { @Override public boolean equals(Object o) { - return data == ((ConstObj) o).data; + if (this == o) return true; + else if (o instanceof ConstObj) return data == ((ConstObj) o).data; + else return false; } } @@ -40,7 +42,7 @@ public class HSetTest { HSet hs; - @Before + @BeforeEach public void setup() { hs = new HSet<>(); } diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/skiplist/SkipListTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/skiplist/SkipListTest.java index 5c4448ebd..750148920 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/skiplist/SkipListTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/skiplist/SkipListTest.java @@ -8,9 +8,9 @@ */ package com.williamfiset.algorithms.datastructures.skiplist; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; -import org.junit.*; +import org.junit.jupiter.api.*; public class SkipListTest { @@ -22,11 +22,11 @@ public void testIndex() { sl.insert(10); sl.insert(25); - assertTrue("Index should be 2", sl.getIndex(25) == 2); + assertEquals(2, sl.getIndex(25), "Index should be 2"); sl.insert(13); sl.insert(14); - assertTrue("Index should be 3", sl.getIndex(14) == 3); + assertEquals(3, sl.getIndex(14), "Index should be 3"); } @Test @@ -34,7 +34,7 @@ public void testIndex() { public void testIndexWithNonExistingValue() { SkipList sl = new SkipList(4, 1, 45); - assertTrue("Index should be -1", sl.getIndex(44) == -1); + assertEquals(-1, sl.getIndex(44), "Index should be -1"); } @Test @@ -43,9 +43,9 @@ public void testIndexWithNonExistingValue() { public void testInsertGreaterThanMaxValue() { SkipList sl = new SkipList(3, 1, 65); - assertTrue("Insert should return false", sl.insert(66) == false); - assertTrue("Insert should return false", sl.insert(103) == false); - assertTrue("Insert should return false", sl.insert(67) == false); + assertFalse(sl.insert(66), "Insert should return false"); + assertFalse(sl.insert(103), "Insert should return false"); + assertFalse(sl.insert(67), "Insert should return false"); } @Test @@ -54,10 +54,10 @@ public void testInsertGreaterThanMaxValue() { public void testInsertLesserThanMinValue() { SkipList sl = new SkipList(3, 10, 83); - assertTrue("Insert should return false", sl.insert(5) == false); - assertTrue("Insert should return false", sl.insert(4) == false); - assertTrue("Insert should return false", sl.insert(3) == false); - assertTrue("Insert should return false", sl.insert(2) == false); + assertFalse(sl.insert(5), "Insert should return false"); + assertFalse(sl.insert(4), "Insert should return false"); + assertFalse(sl.insert(3), "Insert should return false"); + assertFalse(sl.insert(2), "Insert should return false"); } @Test @@ -67,14 +67,14 @@ public void testSimpleFunctionality() { sl.insert(5); sl.insert(8); - assertTrue("Size should be 4", sl.size() == 4); - assertTrue("Object with key 5 should be found", sl.find(5)); - assertTrue("Object with key 8 should be found", sl.find(8)); + assertEquals(4, sl.size(), "Size should be 4"); + assertTrue(sl.find(5), "Object with key 5 should be found"); + assertTrue(sl.find(8), "Object with key 8 should be found"); sl.remove(5); - assertTrue("Size should be 3", sl.size() == 3); - assertFalse("Object with key 5 shouldn't be found", sl.find(5)); + assertEquals(3, sl.size(), "Size should be 3"); + assertFalse(sl.find(5), "Object with key 5 shouldn't be found"); } @Test @@ -82,19 +82,19 @@ public void testSimpleFunctionality() { public void testSize() { SkipList sl = new SkipList(3, 1, 10); - assertTrue("Size should be initialized to 2", sl.size() == 2); + assertEquals(2, sl.size(), "Size should be initialized to 2"); sl.insert(3); sl.insert(4); sl.insert(5); - assertTrue("Size should be 5", sl.size() == 5); - assertFalse("Size shouldn't be 4", sl.size() == 4); + assertEquals(5, sl.size(), "Size should be 5"); + assertNotEquals(4, sl.size(), "Size shouldn't be 4"); sl.remove(3); sl.remove(4); - assertTrue("Size should be 3", sl.size() == 3); + assertEquals(3, sl.size(), "Size should be 3"); } @Test @@ -112,13 +112,13 @@ public void testFind() { sl.insert(30); sl.insert(24); - assertTrue("Size should be 11", sl.size() == 11); - assertTrue("Object with key 43 should be found", sl.find(43)); - assertFalse("Object with key 44 shouldn't be found", sl.find(44)); + assertEquals(11, sl.size(), "Size should be 11"); + assertTrue(sl.find(43), "Object with key 43 should be found"); + assertFalse(sl.find(44), "Object with key 44 shouldn't be found"); sl.remove(43); - assertFalse("Object with key 43 shouldn't be found", sl.find(43)); + assertFalse(sl.find(43), "Object with key 43 shouldn't be found"); } @Test @@ -128,12 +128,12 @@ public void testDuplicate() { SkipList sl = new SkipList(2, 2, 5); sl.insert(4); - assertFalse("Duplicate insert should return false", sl.insert(4)); - assertTrue("Duplicate should not exist, size should be 3", sl.size() == 3); + assertFalse(sl.insert(4), "Duplicate insert should return false"); + assertEquals(3, sl.size(), "Duplicate should not exist, size should be 3"); sl.remove(4); - assertFalse("Element exist after removal", sl.find(4)); + assertFalse(sl.find(4), "Element exist after removal"); } @Test @@ -141,12 +141,12 @@ public void testDuplicate() { public void testRemoveNonExisting() { SkipList sl = new SkipList(2, 2, 5); - assertFalse("Remove should return false when Object does not exist", sl.remove(4)); + assertFalse(sl.remove(4), "Remove should return false when Object does not exist"); sl.insert(4); - assertTrue("Object should be removable", sl.remove(4)); - assertFalse("Remove should return false when it has already been removed", sl.remove(4)); + assertTrue(sl.remove(4), "Object should be removable"); + assertFalse(sl.remove(4), "Remove should return false when it has already been removed"); } @Test @@ -154,7 +154,7 @@ public void testRemoveNonExisting() { public void testRemoveHeadTail() { SkipList sl = new SkipList(3, 1, 10); - assertFalse("Head shouldn't be removable", sl.remove(1)); - assertFalse("Tail shouldn't be removable", sl.remove(10)); + assertFalse(sl.remove(1), "Head shouldn't be removable"); + assertFalse(sl.remove(10), "Tail shouldn't be removable"); } } diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/sparsetable/SparseTableTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/sparsetable/SparseTableTest.java index a892f71d0..0c614b1b5 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/sparsetable/SparseTableTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/sparsetable/SparseTableTest.java @@ -3,7 +3,7 @@ import static com.google.common.truth.Truth.assertThat; import java.util.*; -import org.junit.*; +import org.junit.jupiter.api.*; public class SparseTableTest { diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/stack/StackTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/stack/StackTest.java index 8473f7ea6..a10cd14c9 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/stack/StackTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/stack/StackTest.java @@ -1,88 +1,81 @@ package com.williamfiset.algorithms.datastructures.stack; import static com.google.common.truth.Truth.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.ArrayList; import java.util.List; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class StackTest { - private List> stacks = new ArrayList<>(); - - @Before - public void setup() { + private static List> inputs() { + List> stacks = new ArrayList<>(); stacks.add(new ListStack()); stacks.add(new ArrayStack()); stacks.add(new IntStack(2)); + return stacks; } - @Test - public void testEmptyStack() { - for (Stack stack : stacks) { - assertThat(stack.isEmpty()).isTrue(); - assertThat(stack.size()).isEqualTo(0); - } + @ParameterizedTest + @MethodSource("inputs") + public void testEmptyStack(Stack stack) { + assertThat(stack.isEmpty()).isTrue(); + assertThat(stack.size()).isEqualTo(0); } - @Test(expected = Exception.class) - public void testPopOnEmpty() { - for (Stack stack : stacks) { - stack.pop(); - } + @ParameterizedTest + @MethodSource("inputs") + public void testPopOnEmpty(Stack stack) { + assertThrows(Exception.class, () -> stack.pop()); } - @Test(expected = Exception.class) - public void testPeekOnEmpty() { - for (Stack stack : stacks) { - stack.peek(); - } + @ParameterizedTest + @MethodSource("inputs") + public void testPeekOnEmpty(Stack stack) { + assertThrows(Exception.class, () -> stack.peek()); } - @Test - public void testPush() { - for (Stack stack : stacks) { - stack.push(2); - assertThat(stack.size()).isEqualTo(1); - } + @ParameterizedTest + @MethodSource("inputs") + public void testPush(Stack stack) { + stack.push(2); + assertThat(stack.size()).isEqualTo(1); } - @Test - public void testPeek() { - for (Stack stack : stacks) { - stack.push(2); - assertThat((int) (Integer) stack.peek()).isEqualTo(2); - assertThat(stack.size()).isEqualTo(1); - } + @ParameterizedTest + @MethodSource("inputs") + public void testPeek(Stack stack) { + stack.push(2); + assertThat((int) (Integer) stack.peek()).isEqualTo(2); + assertThat(stack.size()).isEqualTo(1); } - @Test - public void testPop() { - for (Stack stack : stacks) { - stack.push(2); - assertThat((int) stack.pop()).isEqualTo(2); - assertThat(stack.size()).isEqualTo(0); - } + @ParameterizedTest + @MethodSource("inputs") + public void testPop(Stack stack) { + stack.push(2); + assertThat((int) stack.pop()).isEqualTo(2); + assertThat(stack.size()).isEqualTo(0); } - @Test - public void testExhaustively() { - for (Stack stack : stacks) { - assertThat(stack.isEmpty()).isTrue(); - stack.push(1); - assertThat(stack.isEmpty()).isFalse(); - stack.push(2); - assertThat(stack.size()).isEqualTo(2); - assertThat((int) stack.peek()).isEqualTo(2); - assertThat(stack.size()).isEqualTo(2); - assertThat((int) stack.pop()).isEqualTo(2); - assertThat(stack.size()).isEqualTo(1); - assertThat((int) stack.peek()).isEqualTo(1); - assertThat(stack.size()).isEqualTo(1); - assertThat((int) stack.pop()).isEqualTo(1); - assertThat(stack.size()).isEqualTo(0); - assertThat(stack.isEmpty()).isTrue(); - } + @ParameterizedTest + @MethodSource("inputs") + public void testExhaustively(Stack stack) { + assertThat(stack.isEmpty()).isTrue(); + stack.push(1); + assertThat(stack.isEmpty()).isFalse(); + stack.push(2); + assertThat(stack.size()).isEqualTo(2); + assertThat((int) stack.peek()).isEqualTo(2); + assertThat(stack.size()).isEqualTo(2); + assertThat((int) stack.pop()).isEqualTo(2); + assertThat(stack.size()).isEqualTo(1); + assertThat((int) stack.peek()).isEqualTo(1); + assertThat(stack.size()).isEqualTo(1); + assertThat((int) stack.pop()).isEqualTo(1); + assertThat(stack.size()).isEqualTo(0); + assertThat(stack.isEmpty()).isTrue(); } } diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/suffixarray/SuffixArrayTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/suffixarray/SuffixArrayTest.java index 64fc01e9b..b8f7c0dc2 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/suffixarray/SuffixArrayTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/suffixarray/SuffixArrayTest.java @@ -4,7 +4,7 @@ import java.security.SecureRandom; import java.util.Random; -import org.junit.*; +import org.junit.jupiter.api.*; public class SuffixArrayTest { @@ -18,7 +18,7 @@ public class SuffixArrayTest { String ASCII_LETTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; - @Before + @BeforeEach public void setup() {} @Test diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/trie/TrieTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/trie/TrieTest.java index 6dbe8c918..b44e4b00c 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/trie/TrieTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/trie/TrieTest.java @@ -1,47 +1,72 @@ package com.williamfiset.algorithms.datastructures.trie; import static com.google.common.truth.Truth.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; -import org.junit.*; +import org.junit.jupiter.api.*; public class TrieTest { - // @Before public void setup() { } + // @BeforeEach public void setup() { } - @Test(expected = IllegalArgumentException.class) + @Test public void testBadTrieDelete1() { - Trie t = new Trie(); - t.insert("some string"); - t.delete("some string", 0); + assertThrows( + IllegalArgumentException.class, + () -> { + Trie t = new Trie(); + t.insert("some string"); + t.delete("some string", 0); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void testBadTrieDelete2() { - Trie t = new Trie(); - t.insert("some string"); - t.delete("some string", -1); + assertThrows( + IllegalArgumentException.class, + () -> { + Trie t = new Trie(); + t.insert("some string"); + t.delete("some string", -1); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void testBadTrieDelete3() { - Trie t = new Trie(); - t.insert("some string"); - t.delete("some string", -345); + assertThrows( + IllegalArgumentException.class, + () -> { + Trie t = new Trie(); + t.insert("some string"); + t.delete("some string", -345); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void testBadTrieInsert() { - (new Trie()).insert(null); + assertThrows( + IllegalArgumentException.class, + () -> { + (new Trie()).insert(null); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void testBadTrieCount() { - (new Trie()).count(null); + assertThrows( + IllegalArgumentException.class, + () -> { + (new Trie()).count(null); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void testBadTrieContains() { - (new Trie()).contains(null); + assertThrows( + IllegalArgumentException.class, + () -> { + (new Trie()).contains(null); + }); } @Test diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/unionfind/UnionFindTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/unionfind/UnionFindTest.java index aa39b1ae2..bf1bfca95 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/unionfind/UnionFindTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/unionfind/UnionFindTest.java @@ -2,8 +2,11 @@ // import static org.junit.Assert.*; import static com.google.common.truth.Truth.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; -import org.junit.*; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; public class UnionFindTest { @@ -218,18 +221,9 @@ public void testSize() { assertThat(uf.size()).isEqualTo(5); } - @Test(expected = IllegalArgumentException.class) - public void testBadUnionFindCreation1() { - new UnionFind(-1); - } - - @Test(expected = IllegalArgumentException.class) - public void testBadUnionFindCreation2() { - new UnionFind(-3463); - } - - @Test(expected = IllegalArgumentException.class) - public void testBadUnionFindCreation3() { - new UnionFind(0); + @ParameterizedTest(name = "Size: {0}") + @ValueSource(ints = {-1, -3463, 0}) + public void testBadUnionFindCreation(int size) { + assertThrows(IllegalArgumentException.class, () -> new UnionFind(size)); } } diff --git a/src/test/java/com/williamfiset/algorithms/dp/CoinChangeTest.java b/src/test/java/com/williamfiset/algorithms/dp/CoinChangeTest.java index 997d8b6d7..028352bf0 100644 --- a/src/test/java/com/williamfiset/algorithms/dp/CoinChangeTest.java +++ b/src/test/java/com/williamfiset/algorithms/dp/CoinChangeTest.java @@ -5,7 +5,7 @@ import com.google.common.primitives.Ints; import com.williamfiset.algorithms.utils.TestUtils; import java.util.*; -import org.junit.*; +import org.junit.jupiter.api.*; public class CoinChangeTest { @@ -19,12 +19,64 @@ public void testCoinChange() { int amount = TestUtils.randValue(1, 1000); - int v1 = CoinChange.coinChange(coinValues, amount); - int v2 = CoinChange.coinChangeSpaceEfficient(coinValues, amount); + CoinChange.Solution solution1 = CoinChange.coinChange(coinValues, amount); + CoinChange.Solution solution2 = CoinChange.coinChangeSpaceEfficient(coinValues, amount); + int v1 = solution1.minCoins.isPresent() ? solution1.minCoins.get() : -1; + int v2 = solution2.minCoins.isPresent() ? solution2.minCoins.get() : -1; int v3 = CoinChange.coinChangeRecursive(coinValues, amount); assertThat(v1).isEqualTo(v2); assertThat(v2).isEqualTo(v3); } } + + @Test + public void testCoinChangeSelectedCoins() { + for (int i = 1; i < LOOPS; i++) { + List values = TestUtils.randomIntegerList(i, 1, 1000); + int[] coinValues = Ints.toArray(values); + + int amount = TestUtils.randValue(1, 1000); + + CoinChange.Solution solution = CoinChange.coinChange(coinValues, amount); + int selectedCoinsSum = 0; + for (int v : solution.selectedCoins) { + selectedCoinsSum += v; + } + if (!solution.minCoins.isPresent()) { + assertThat(solution.selectedCoins.size()).isEqualTo(0); + } else { + // Verify that the size of the selected coins is equal to the optimal solution. + assertThat(solution.selectedCoins.size()).isEqualTo(solution.minCoins.get()); + + // Further verify that the sum of the selected coins equals the amount we want to make. + assertThat(selectedCoinsSum).isEqualTo(amount); + } + } + } + + @Test + public void testCoinChangeSpaceEfficientSelectedCoins() { + for (int i = 1; i < LOOPS; i++) { + List values = TestUtils.randomIntegerList(i, 1, 1000); + int[] coinValues = Ints.toArray(values); + + int amount = TestUtils.randValue(1, 1000); + + CoinChange.Solution solution = CoinChange.coinChangeSpaceEfficient(coinValues, amount); + int selectedCoinsSum = 0; + for (int v : solution.selectedCoins) { + selectedCoinsSum += v; + } + if (!solution.minCoins.isPresent()) { + assertThat(solution.selectedCoins.size()).isEqualTo(0); + } else { + // Verify that the size of the selected coins is equal to the optimal solution. + assertThat(solution.selectedCoins.size()).isEqualTo(solution.minCoins.get()); + + // Further verify that the sum of the selected coins equals the amount we want to make. + assertThat(selectedCoinsSum).isEqualTo(amount); + } + } + } } diff --git a/src/test/java/com/williamfiset/algorithms/dp/WeightedMaximumCardinalityMatchingTest.java b/src/test/java/com/williamfiset/algorithms/dp/WeightedMaximumCardinalityMatchingTest.java index 2fe3debc9..b378b3802 100644 --- a/src/test/java/com/williamfiset/algorithms/dp/WeightedMaximumCardinalityMatchingTest.java +++ b/src/test/java/com/williamfiset/algorithms/dp/WeightedMaximumCardinalityMatchingTest.java @@ -3,7 +3,7 @@ import static com.google.common.truth.Truth.assertThat; import java.util.*; -import org.junit.*; +import org.junit.jupiter.api.*; public class WeightedMaximumCardinalityMatchingTest { @@ -302,25 +302,37 @@ public void testNegativeEdge_smallerThanINFWeights() { MwpmInterface mwpm = new WeightedMaximumCardinalityMatchingRecursive(g); double cost = mwpm.getMinWeightCost(); - assertThat(cost).isEqualTo(-1.0 + -3.0 + -5.0 + (-3 * 50 * INF)); + double expectedCost = -1.0 + -3.0 + -5.0 + (-3 * 50 * INF); + assertThat(cost).isEqualTo(expectedCost); int[] matching = mwpm.getMatching(); int[] expectedMatching = {0, 1, 2, 3, 4, 5}; assertThat(matching).isEqualTo(expectedMatching); + assertOptimalMatching(matching, g, expectedCost); } @Test public void testDisjointGraph() { - int n = 6; + int n = 8; Double[][] g = createEmptyMatrix(n); + addUndirectedWeightedEdge(g, 0, 1, 3); + addUndirectedWeightedEdge(g, 0, 2, 5); + addUndirectedWeightedEdge(g, 1, 2, 1); + addUndirectedWeightedEdge(g, 1, 3, 4); + addUndirectedWeightedEdge(g, 2, 3, 2); + + addUndirectedWeightedEdge(g, 4, 5, 3); + addUndirectedWeightedEdge(g, 4, 6, 5); + addUndirectedWeightedEdge(g, 5, 6, 1); + addUndirectedWeightedEdge(g, 5, 7, 4); + addUndirectedWeightedEdge(g, 6, 7, 2); MwpmInterface mwpm = new WeightedMaximumCardinalityMatchingRecursive(g); double cost = mwpm.getMinWeightCost(); - assertThat(cost).isEqualTo(0); + assertThat(cost).isEqualTo(10); int[] matching = mwpm.getMatching(); - int[] expectedMatching = {}; - assertThat(matching).isEqualTo(expectedMatching); + assertOptimalMatching(matching, g, 10); } @Test @@ -376,14 +388,7 @@ public void testMatchingAndCostAreConsistent() { MwpmInterface[] impls = getImplementations(costMatrix); for (MwpmInterface mwpm : impls) { - int[] matching = mwpm.getMatching(); - double totalMinCost = 0; - for (int i = 0; i < matching.length / 2; i++) { - int ii = matching[2 * i]; - int jj = matching[2 * i + 1]; - totalMinCost += costMatrix[ii][jj]; - } - assertThat(totalMinCost).isEqualTo(mwpm.getMinWeightCost()); + assertOptimalMatching(mwpm.getMatching(), costMatrix, mwpm.getMinWeightCost()); } } } @@ -393,7 +398,7 @@ public void testAgainstBruteForce_largeValues() { for (int loop = 0; loop < LOOPS; loop++) { int n = Math.max(1, (int) (Math.random() * 6)) * 2; // n is either 2,4,6,8, or 10 Double[][] costMatrix = new Double[n][n]; - randomFillSymmetricMatrix(costMatrix, /*maxValue=*/ 10000); + randomFillSymmetricMatrix(costMatrix, /* maxValue= */ 10000); MwpmInterface[] impls = getImplementations(costMatrix); for (MwpmInterface mwpm : impls) { @@ -411,7 +416,7 @@ public void testAgainstBruteForce_smallValues() { for (int loop = 0; loop < LOOPS; loop++) { int n = Math.max(1, (int) (Math.random() * 6)) * 2; // n is either 2,4,6,8, or 10 Double[][] costMatrix = new Double[n][n]; - randomFillSymmetricMatrix(costMatrix, /*maxValue=*/ 3); + randomFillSymmetricMatrix(costMatrix, /* maxValue= */ 3); MwpmInterface[] impls = getImplementations(costMatrix); for (MwpmInterface mwpm : impls) { @@ -433,4 +438,13 @@ public void randomFillSymmetricMatrix(Double[][] dist, int maxValue) { } } } + + private void assertOptimalMatching( + int[] matching, Double[][] costMatrix, double expectedMatchingCost) { + double total = 0; + for (int i = 0; i < matching.length; i += 2) { + total += costMatrix[matching[i]][matching[i + 1]]; + } + assertThat(total).isEqualTo(expectedMatchingCost); + } } diff --git a/src/test/java/com/williamfiset/algorithms/geometry/ConvexHullMonotoneChainsAlgorithmTest.java b/src/test/java/com/williamfiset/algorithms/geometry/ConvexHullMonotoneChainsAlgorithmTest.java index cbccade75..08cdaf9d4 100644 --- a/src/test/java/com/williamfiset/algorithms/geometry/ConvexHullMonotoneChainsAlgorithmTest.java +++ b/src/test/java/com/williamfiset/algorithms/geometry/ConvexHullMonotoneChainsAlgorithmTest.java @@ -4,7 +4,7 @@ import com.google.common.collect.ImmutableList; import java.awt.geom.*; -import org.junit.*; +import org.junit.jupiter.api.*; public class ConvexHullMonotoneChainsAlgorithmTest { diff --git a/src/test/java/com/williamfiset/algorithms/geometry/MinimumCostConvexPolygonTriangulationTest.java b/src/test/java/com/williamfiset/algorithms/geometry/MinimumCostConvexPolygonTriangulationTest.java index 4eace741d..ecda84dc1 100644 --- a/src/test/java/com/williamfiset/algorithms/geometry/MinimumCostConvexPolygonTriangulationTest.java +++ b/src/test/java/com/williamfiset/algorithms/geometry/MinimumCostConvexPolygonTriangulationTest.java @@ -3,7 +3,7 @@ import static com.google.common.truth.Truth.assertThat; import java.awt.geom.*; -import org.junit.*; +import org.junit.jupiter.api.*; public class MinimumCostConvexPolygonTriangulationTest { diff --git a/src/test/java/com/williamfiset/algorithms/graphtheory/ArticulationPointsAdjacencyListTest.java b/src/test/java/com/williamfiset/algorithms/graphtheory/ArticulationPointsAdjacencyListTest.java index 2f09aec80..b7b3dfdad 100644 --- a/src/test/java/com/williamfiset/algorithms/graphtheory/ArticulationPointsAdjacencyListTest.java +++ b/src/test/java/com/williamfiset/algorithms/graphtheory/ArticulationPointsAdjacencyListTest.java @@ -3,7 +3,7 @@ import static com.google.common.truth.Truth.assertThat; import java.util.*; -import org.junit.*; +import org.junit.jupiter.api.*; public class ArticulationPointsAdjacencyListTest { diff --git a/src/test/java/com/williamfiset/algorithms/graphtheory/BreadthFirstSearchAdjacencyListIterativeTest.java b/src/test/java/com/williamfiset/algorithms/graphtheory/BreadthFirstSearchAdjacencyListIterativeTest.java index ada85f9eb..917ef9b92 100644 --- a/src/test/java/com/williamfiset/algorithms/graphtheory/BreadthFirstSearchAdjacencyListIterativeTest.java +++ b/src/test/java/com/williamfiset/algorithms/graphtheory/BreadthFirstSearchAdjacencyListIterativeTest.java @@ -6,25 +6,26 @@ import static com.williamfiset.algorithms.graphtheory.BreadthFirstSearchAdjacencyListIterative.createEmptyGraph; import static java.lang.Math.max; import static java.lang.Math.random; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.*; public class BreadthFirstSearchAdjacencyListIterativeTest { BreadthFirstSearchAdjacencyListIterative solver; - @Before + @BeforeEach public void setup() { solver = null; } - @Test(expected = IllegalArgumentException.class) + @Test public void testNullGraphInput() { - new BreadthFirstSearchAdjacencyListIterative(null); + assertThrows( + IllegalArgumentException.class, () -> new BreadthFirstSearchAdjacencyListIterative(null)); } @Test diff --git a/src/test/java/com/williamfiset/algorithms/graphtheory/BridgesAdjacencyListIterativeTest.java b/src/test/java/com/williamfiset/algorithms/graphtheory/BridgesAdjacencyListIterativeTest.java index 7fa5b3345..8e9de87c0 100644 --- a/src/test/java/com/williamfiset/algorithms/graphtheory/BridgesAdjacencyListIterativeTest.java +++ b/src/test/java/com/williamfiset/algorithms/graphtheory/BridgesAdjacencyListIterativeTest.java @@ -5,7 +5,7 @@ import com.google.common.collect.ImmutableList; import java.util.*; import org.apache.commons.lang3.tuple.Pair; -import org.junit.*; +import org.junit.jupiter.api.*; public class BridgesAdjacencyListIterativeTest { diff --git a/src/test/java/com/williamfiset/algorithms/graphtheory/BridgesAdjacencyListTest.java b/src/test/java/com/williamfiset/algorithms/graphtheory/BridgesAdjacencyListTest.java index 24ffee4ae..595b024ff 100644 --- a/src/test/java/com/williamfiset/algorithms/graphtheory/BridgesAdjacencyListTest.java +++ b/src/test/java/com/williamfiset/algorithms/graphtheory/BridgesAdjacencyListTest.java @@ -5,7 +5,7 @@ import com.google.common.collect.ImmutableList; import java.util.*; import org.apache.commons.lang3.tuple.Pair; -import org.junit.*; +import org.junit.jupiter.api.*; public class BridgesAdjacencyListTest { diff --git a/src/test/java/com/williamfiset/algorithms/graphtheory/EulerianPathDirectedEdgesAdjacencyListTest.java b/src/test/java/com/williamfiset/algorithms/graphtheory/EulerianPathDirectedEdgesAdjacencyListTest.java index 7bba95f3b..8375c6b01 100644 --- a/src/test/java/com/williamfiset/algorithms/graphtheory/EulerianPathDirectedEdgesAdjacencyListTest.java +++ b/src/test/java/com/williamfiset/algorithms/graphtheory/EulerianPathDirectedEdgesAdjacencyListTest.java @@ -3,13 +3,13 @@ import static com.google.common.truth.Truth.assertThat; import java.util.*; -import org.junit.*; +import org.junit.jupiter.api.*; public class EulerianPathDirectedEdgesAdjacencyListTest { EulerianPathDirectedEdgesAdjacencyList solver; - @Before + @BeforeEach public void setUp() { solver = null; } diff --git a/src/test/java/com/williamfiset/algorithms/graphtheory/FloydWarshallSolverTest.java b/src/test/java/com/williamfiset/algorithms/graphtheory/FloydWarshallSolverTest.java index e75dc742c..fbb65afdf 100644 --- a/src/test/java/com/williamfiset/algorithms/graphtheory/FloydWarshallSolverTest.java +++ b/src/test/java/com/williamfiset/algorithms/graphtheory/FloydWarshallSolverTest.java @@ -3,8 +3,7 @@ import static com.google.common.truth.Truth.assertThat; import java.util.*; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.*; public class FloydWarshallSolverTest { @@ -13,7 +12,7 @@ public class FloydWarshallSolverTest { static double[][] matrix1, matrix2, matrix3; - @Before + @BeforeEach public void setup() { matrix1 = new double[][] { diff --git a/src/test/java/com/williamfiset/algorithms/graphtheory/KahnsTest.java b/src/test/java/com/williamfiset/algorithms/graphtheory/KahnsTest.java index 850ebb1a7..e58f1c327 100644 --- a/src/test/java/com/williamfiset/algorithms/graphtheory/KahnsTest.java +++ b/src/test/java/com/williamfiset/algorithms/graphtheory/KahnsTest.java @@ -1,11 +1,12 @@ package com.williamfiset.algorithms.graphtheory; import static com.google.common.truth.Truth.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.williamfiset.algorithms.utils.graphutils.GraphGenerator; import com.williamfiset.algorithms.utils.graphutils.Utils; import java.util.*; -import org.junit.*; +import org.junit.jupiter.api.*; public class KahnsTest { @@ -40,7 +41,7 @@ private static boolean isTopsortOrdering(List> g, int[] order) { return true; } - @Test(expected = IllegalArgumentException.class) + @Test public void cycleInGraph() { List> g = Utils.createEmptyAdjacencyList(4); Utils.addDirectedEdge(g, 0, 1); @@ -48,7 +49,7 @@ public void cycleInGraph() { Utils.addDirectedEdge(g, 2, 3); Utils.addDirectedEdge(g, 3, 0); Kahns solver = new Kahns(); - solver.kahns(g); + assertThrows(IllegalArgumentException.class, () -> solver.kahns(g)); } @Test diff --git a/src/test/java/com/williamfiset/algorithms/graphtheory/KosarajuTest.java b/src/test/java/com/williamfiset/algorithms/graphtheory/KosarajuTest.java index c048e83a7..3ce6974c7 100644 --- a/src/test/java/com/williamfiset/algorithms/graphtheory/KosarajuTest.java +++ b/src/test/java/com/williamfiset/algorithms/graphtheory/KosarajuTest.java @@ -6,10 +6,11 @@ package com.williamfiset.algorithms.graphtheory; import static com.google.common.truth.Truth.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrowsExactly; import com.google.common.collect.ImmutableList; import java.util.*; -import org.junit.*; +import org.junit.jupiter.api.*; public class KosarajuTest { @@ -25,9 +26,9 @@ public static void addEdge(List> graph, int from, int to) { graph.get(from).add(to); } - @Test(expected = IllegalArgumentException.class) + @Test public void nullGraphConstructor() { - new Kosaraju(null); + assertThrowsExactly(IllegalArgumentException.class, () -> new Kosaraju(null)); } @Test diff --git a/src/test/java/com/williamfiset/algorithms/graphtheory/SteinerTreeTest.java b/src/test/java/com/williamfiset/algorithms/graphtheory/SteinerTreeTest.java index ea003fcc7..d4713841d 100644 --- a/src/test/java/com/williamfiset/algorithms/graphtheory/SteinerTreeTest.java +++ b/src/test/java/com/williamfiset/algorithms/graphtheory/SteinerTreeTest.java @@ -2,7 +2,7 @@ import static com.google.common.truth.Truth.assertThat; -import org.junit.*; +import org.junit.jupiter.api.*; public class SteinerTreeTest { diff --git a/src/test/java/com/williamfiset/algorithms/graphtheory/TarjanSccSolverAdjacencyListTest.java b/src/test/java/com/williamfiset/algorithms/graphtheory/TarjanSccSolverAdjacencyListTest.java index 0ccd37318..cab07eebf 100644 --- a/src/test/java/com/williamfiset/algorithms/graphtheory/TarjanSccSolverAdjacencyListTest.java +++ b/src/test/java/com/williamfiset/algorithms/graphtheory/TarjanSccSolverAdjacencyListTest.java @@ -1,10 +1,11 @@ package com.williamfiset.algorithms.graphtheory; import static com.google.common.truth.Truth.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.common.collect.ImmutableList; import java.util.*; -import org.junit.*; +import org.junit.jupiter.api.*; public class TarjanSccSolverAdjacencyListTest { @@ -20,9 +21,9 @@ public static void addEdge(List> graph, int from, int to) { graph.get(from).add(to); } - @Test(expected = IllegalArgumentException.class) + @Test public void nullGraphConstructor() { - new TarjanSccSolverAdjacencyList(null); + assertThrows(IllegalArgumentException.class, () -> new TarjanSccSolverAdjacencyList(null)); } @Test diff --git a/src/test/java/com/williamfiset/algorithms/graphtheory/TravelingSalesmanProblemTest.java b/src/test/java/com/williamfiset/algorithms/graphtheory/TravelingSalesmanProblemTest.java index f9b1c2486..5e8909bdd 100644 --- a/src/test/java/com/williamfiset/algorithms/graphtheory/TravelingSalesmanProblemTest.java +++ b/src/test/java/com/williamfiset/algorithms/graphtheory/TravelingSalesmanProblemTest.java @@ -1,68 +1,71 @@ package com.williamfiset.algorithms.graphtheory; import static com.google.common.truth.Truth.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.*; -import org.junit.*; +import org.junit.jupiter.api.*; public class TravelingSalesmanProblemTest { private static final double EPS = 1e-5; - @Test(expected = IllegalArgumentException.class) + @Test public void testTspRecursiveInvalidStartNode() { double[][] dist = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; - new TspDynamicProgrammingRecursive(321, dist); + assertThrows( + IllegalArgumentException.class, () -> new TspDynamicProgrammingRecursive(321, dist)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testTspIterativeInvalidStartNode() { double[][] dist = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; - new TspDynamicProgrammingIterative(321, dist); + assertThrows( + IllegalArgumentException.class, () -> new TspDynamicProgrammingIterative(321, dist)); } - @Test(expected = IllegalStateException.class) + @Test public void testTspRecursiveNonSquareMatrix() { double[][] dist = { {1, 2, 3}, {4, 5, 6} }; - new TspDynamicProgrammingRecursive(dist); + assertThrows(IllegalStateException.class, () -> new TspDynamicProgrammingRecursive(dist)); } - @Test(expected = IllegalStateException.class) + @Test public void testTspIterativeNonSquareMatrix() { double[][] dist = { {1, 2, 3}, {4, 5, 6} }; - new TspDynamicProgrammingIterative(dist); + assertThrows(IllegalStateException.class, () -> new TspDynamicProgrammingIterative(dist)); } - @Test(expected = IllegalStateException.class) + @Test public void testTspRecursiveSmallGraph() { double[][] dist = { {0, 1}, {1, 0} }; - new TspDynamicProgrammingRecursive(dist); + assertThrows(IllegalStateException.class, () -> new TspDynamicProgrammingRecursive(dist)); } - @Test(expected = IllegalStateException.class) + @Test public void testTspIterativeSmallGraph() { double[][] dist = { {0, 1}, {1, 0} }; - new TspDynamicProgrammingIterative(dist); + assertThrows(IllegalStateException.class, () -> new TspDynamicProgrammingIterative(dist)); } @Test diff --git a/src/test/java/com/williamfiset/algorithms/graphtheory/TwoSatSolverAdjacencyListTest.java b/src/test/java/com/williamfiset/algorithms/graphtheory/TwoSatSolverAdjacencyListTest.java index d57d4c404..29eaa0e4b 100644 --- a/src/test/java/com/williamfiset/algorithms/graphtheory/TwoSatSolverAdjacencyListTest.java +++ b/src/test/java/com/williamfiset/algorithms/graphtheory/TwoSatSolverAdjacencyListTest.java @@ -3,7 +3,7 @@ import static com.google.common.truth.Truth.assertThat; import java.util.*; -import org.junit.*; +import org.junit.jupiter.api.*; public class TwoSatSolverAdjacencyListTest { diff --git a/src/test/java/com/williamfiset/algorithms/graphtheory/networkflow/BipartiteGraphCheckAdjacencyListTest.java b/src/test/java/com/williamfiset/algorithms/graphtheory/networkflow/BipartiteGraphCheckAdjacencyListTest.java index c0c0c4bd0..4768393ae 100644 --- a/src/test/java/com/williamfiset/algorithms/graphtheory/networkflow/BipartiteGraphCheckAdjacencyListTest.java +++ b/src/test/java/com/williamfiset/algorithms/graphtheory/networkflow/BipartiteGraphCheckAdjacencyListTest.java @@ -4,14 +4,14 @@ import com.williamfiset.algorithms.utils.graphutils.Utils; import java.util.*; -import org.junit.*; +import org.junit.jupiter.api.*; public class BipartiteGraphCheckAdjacencyListTest { private List> graph; private BipartiteGraphCheckAdjacencyList solver; - @Before + @BeforeEach public void setUp() {} @Test diff --git a/src/test/java/com/williamfiset/algorithms/graphtheory/networkflow/MaxFlowTests.java b/src/test/java/com/williamfiset/algorithms/graphtheory/networkflow/MaxFlowTests.java index a71e33f50..3c9f23f12 100644 --- a/src/test/java/com/williamfiset/algorithms/graphtheory/networkflow/MaxFlowTests.java +++ b/src/test/java/com/williamfiset/algorithms/graphtheory/networkflow/MaxFlowTests.java @@ -4,13 +4,13 @@ import com.williamfiset.algorithms.graphtheory.networkflow.NetworkFlowSolverBase.Edge; import java.util.*; -import org.junit.*; +import org.junit.jupiter.api.*; public class MaxFlowTests { List solvers; - @Before + @BeforeEach public void setUp() { solvers = new ArrayList<>(); } diff --git a/src/test/java/com/williamfiset/algorithms/graphtheory/networkflow/MinCostMaxFlowTests.java b/src/test/java/com/williamfiset/algorithms/graphtheory/networkflow/MinCostMaxFlowTests.java index 750cd2c7d..c250a99e2 100644 --- a/src/test/java/com/williamfiset/algorithms/graphtheory/networkflow/MinCostMaxFlowTests.java +++ b/src/test/java/com/williamfiset/algorithms/graphtheory/networkflow/MinCostMaxFlowTests.java @@ -3,13 +3,13 @@ import static com.google.common.truth.Truth.assertThat; import java.util.*; -import org.junit.*; +import org.junit.jupiter.api.*; public class MinCostMaxFlowTests { List solvers; - @Before + @BeforeEach public void setUp() { solvers = new ArrayList<>(); } diff --git a/src/test/java/com/williamfiset/algorithms/graphtheory/treealgorithms/LowestCommonAncestorEulerTourTest.java b/src/test/java/com/williamfiset/algorithms/graphtheory/treealgorithms/LowestCommonAncestorEulerTourTest.java index 7f2676da9..f837cb168 100644 --- a/src/test/java/com/williamfiset/algorithms/graphtheory/treealgorithms/LowestCommonAncestorEulerTourTest.java +++ b/src/test/java/com/williamfiset/algorithms/graphtheory/treealgorithms/LowestCommonAncestorEulerTourTest.java @@ -3,7 +3,7 @@ import static com.google.common.truth.Truth.assertThat; import java.util.*; -import org.junit.*; +import org.junit.jupiter.api.*; public class LowestCommonAncestorEulerTourTest { diff --git a/src/test/java/com/williamfiset/algorithms/graphtheory/treealgorithms/LowestCommonAncestorTest.java b/src/test/java/com/williamfiset/algorithms/graphtheory/treealgorithms/LowestCommonAncestorTest.java index bfe8aeb13..d8b1f07bb 100644 --- a/src/test/java/com/williamfiset/algorithms/graphtheory/treealgorithms/LowestCommonAncestorTest.java +++ b/src/test/java/com/williamfiset/algorithms/graphtheory/treealgorithms/LowestCommonAncestorTest.java @@ -6,7 +6,7 @@ import com.williamfiset.algorithms.graphtheory.treealgorithms.LowestCommonAncestor.TreeNode; import java.util.*; -import org.junit.*; +import org.junit.jupiter.api.*; public class LowestCommonAncestorTest { diff --git a/src/test/java/com/williamfiset/algorithms/graphtheory/treealgorithms/RootingTreeTest.java b/src/test/java/com/williamfiset/algorithms/graphtheory/treealgorithms/RootingTreeTest.java index bbc8e0f8c..b22412620 100644 --- a/src/test/java/com/williamfiset/algorithms/graphtheory/treealgorithms/RootingTreeTest.java +++ b/src/test/java/com/williamfiset/algorithms/graphtheory/treealgorithms/RootingTreeTest.java @@ -4,7 +4,7 @@ import com.williamfiset.algorithms.graphtheory.treealgorithms.RootingTree.TreeNode; import java.util.*; -import org.junit.*; +import org.junit.jupiter.api.*; public class RootingTreeTest { diff --git a/src/test/java/com/williamfiset/algorithms/graphtheory/treealgorithms/TreeCenterLongestPathImplTest.java b/src/test/java/com/williamfiset/algorithms/graphtheory/treealgorithms/TreeCenterLongestPathImplTest.java index 1172b3312..866dc4613 100644 --- a/src/test/java/com/williamfiset/algorithms/graphtheory/treealgorithms/TreeCenterLongestPathImplTest.java +++ b/src/test/java/com/williamfiset/algorithms/graphtheory/treealgorithms/TreeCenterLongestPathImplTest.java @@ -11,7 +11,7 @@ import static com.williamfiset.algorithms.graphtheory.treealgorithms.TreeCenterLongestPathImpl.findTreeCenters; import java.util.*; -import org.junit.*; +import org.junit.jupiter.api.*; public class TreeCenterLongestPathImplTest { diff --git a/src/test/java/com/williamfiset/algorithms/graphtheory/treealgorithms/TreeCenterTest.java b/src/test/java/com/williamfiset/algorithms/graphtheory/treealgorithms/TreeCenterTest.java index d0b9326c4..56723126a 100644 --- a/src/test/java/com/williamfiset/algorithms/graphtheory/treealgorithms/TreeCenterTest.java +++ b/src/test/java/com/williamfiset/algorithms/graphtheory/treealgorithms/TreeCenterTest.java @@ -11,7 +11,7 @@ import static com.williamfiset.algorithms.graphtheory.treealgorithms.TreeCenter.findTreeCenters; import java.util.*; -import org.junit.*; +import org.junit.jupiter.api.*; public class TreeCenterTest { diff --git a/src/test/java/com/williamfiset/algorithms/graphtheory/treealgorithms/TreeIsomorphismTest.java b/src/test/java/com/williamfiset/algorithms/graphtheory/treealgorithms/TreeIsomorphismTest.java index 73a9a7519..40a3c1e0e 100644 --- a/src/test/java/com/williamfiset/algorithms/graphtheory/treealgorithms/TreeIsomorphismTest.java +++ b/src/test/java/com/williamfiset/algorithms/graphtheory/treealgorithms/TreeIsomorphismTest.java @@ -9,15 +9,18 @@ import static com.williamfiset.algorithms.graphtheory.treealgorithms.TreeIsomorphism.addUndirectedEdge; import static com.williamfiset.algorithms.graphtheory.treealgorithms.TreeIsomorphism.createEmptyGraph; import static com.williamfiset.algorithms.graphtheory.treealgorithms.TreeIsomorphism.treesAreIsomorphic; +import static org.junit.Assert.assertThrows; import java.util.*; -import org.junit.*; +import org.junit.jupiter.api.*; public class TreeIsomorphismTest { - @Test(expected = IllegalArgumentException.class) + @Test public void emptyTreeThrowsException() { - treesAreIsomorphic(createEmptyGraph(0), createEmptyGraph(1)); + assertThrows( + IllegalArgumentException.class, + () -> treesAreIsomorphic(createEmptyGraph(0), createEmptyGraph(1))); } @Test diff --git a/src/test/java/com/williamfiset/algorithms/graphtheory/treealgorithms/TreeIsomorphismWithBfsTest.java b/src/test/java/com/williamfiset/algorithms/graphtheory/treealgorithms/TreeIsomorphismWithBfsTest.java index e192e0bd1..02453af34 100644 --- a/src/test/java/com/williamfiset/algorithms/graphtheory/treealgorithms/TreeIsomorphismWithBfsTest.java +++ b/src/test/java/com/williamfiset/algorithms/graphtheory/treealgorithms/TreeIsomorphismWithBfsTest.java @@ -13,7 +13,7 @@ import static com.williamfiset.algorithms.graphtheory.treealgorithms.TreeIsomorphismWithBfs.treesAreIsomorphic; import java.util.*; -import org.junit.*; +import org.junit.jupiter.api.*; public class TreeIsomorphismWithBfsTest { diff --git a/src/test/java/com/williamfiset/algorithms/other/BitManipulationsTest.java b/src/test/java/com/williamfiset/algorithms/other/BitManipulationsTest.java index caeda91db..74c6930d5 100644 --- a/src/test/java/com/williamfiset/algorithms/other/BitManipulationsTest.java +++ b/src/test/java/com/williamfiset/algorithms/other/BitManipulationsTest.java @@ -2,7 +2,7 @@ import static com.google.common.truth.Truth.assertThat; -import org.junit.*; +import org.junit.jupiter.api.*; public class BitManipulationsTest { diff --git a/src/test/java/com/williamfiset/algorithms/other/LazyRangeAdderTest.java b/src/test/java/com/williamfiset/algorithms/other/LazyRangeAdderTest.java index c6549efa3..357a7bbfd 100644 --- a/src/test/java/com/williamfiset/algorithms/other/LazyRangeAdderTest.java +++ b/src/test/java/com/williamfiset/algorithms/other/LazyRangeAdderTest.java @@ -2,7 +2,7 @@ import static com.google.common.truth.Truth.assertThat; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class LazyRangeAdderTest { diff --git a/src/test/java/com/williamfiset/algorithms/other/SlidingWindowMaximumTest.java b/src/test/java/com/williamfiset/algorithms/other/SlidingWindowMaximumTest.java index 60e0dc91f..dc91ee761 100644 --- a/src/test/java/com/williamfiset/algorithms/other/SlidingWindowMaximumTest.java +++ b/src/test/java/com/williamfiset/algorithms/other/SlidingWindowMaximumTest.java @@ -2,7 +2,7 @@ import static com.google.common.truth.Truth.assertThat; -import org.junit.*; +import org.junit.jupiter.api.*; public class SlidingWindowMaximumTest { diff --git a/src/test/java/com/williamfiset/algorithms/search/InterpolationSearchTest.java b/src/test/java/com/williamfiset/algorithms/search/InterpolationSearchTest.java index d69ef603b..7aa74eed0 100644 --- a/src/test/java/com/williamfiset/algorithms/search/InterpolationSearchTest.java +++ b/src/test/java/com/williamfiset/algorithms/search/InterpolationSearchTest.java @@ -2,35 +2,22 @@ import static com.google.common.truth.Truth.assertThat; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.*; public class InterpolationSearchTest { - @Test - public void testCoverage1() { - int[] arr = {0, 1, 2, 3, 4, 5}; - int index = InterpolationSearch.interpolationSearch(arr, 2); - assertThat(index).isEqualTo(2); - } - - @Test - public void testCoverage2() { - int[] arr = {0, 1, 2, 3, 4, 5}; - int index = InterpolationSearch.interpolationSearch(arr, 5); - assertThat(index).isEqualTo(5); - } - - @Test - public void testCoverage3() { - int[] arr = {0, 1, 2, 3, 4, 5}; - int index = InterpolationSearch.interpolationSearch(arr, -1); - assertThat(index).isEqualTo(-1); + private static Arguments[] inputs() { + return new Arguments[] { + Arguments.of(2, 2), Arguments.of(5, 5), Arguments.of(-1, -1), Arguments.of(8, -1) + }; } - @Test - public void testCoverage4() { + @ParameterizedTest(name = "Search value: {0}, Expected index: {1}") + @MethodSource("inputs") + public void testCoverage(int val, int expected) { int[] arr = {0, 1, 2, 3, 4, 5}; - int index = InterpolationSearch.interpolationSearch(arr, 8); - assertThat(index).isEqualTo(-1); + int index = InterpolationSearch.interpolationSearch(arr, val); + assertThat(index).isEqualTo(expected); } } diff --git a/src/test/java/com/williamfiset/algorithms/sorting/QuickSelectTest.java b/src/test/java/com/williamfiset/algorithms/sorting/QuickSelectTest.java index 014427a73..80d51905b 100644 --- a/src/test/java/com/williamfiset/algorithms/sorting/QuickSelectTest.java +++ b/src/test/java/com/williamfiset/algorithms/sorting/QuickSelectTest.java @@ -4,7 +4,7 @@ import com.williamfiset.algorithms.utils.TestUtils; import java.util.Arrays; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class QuickSelectTest { diff --git a/src/test/java/com/williamfiset/algorithms/sorting/RadixSortTest.java b/src/test/java/com/williamfiset/algorithms/sorting/RadixSortTest.java index 983fdf1a3..9f1f0cf37 100644 --- a/src/test/java/com/williamfiset/algorithms/sorting/RadixSortTest.java +++ b/src/test/java/com/williamfiset/algorithms/sorting/RadixSortTest.java @@ -4,7 +4,7 @@ import java.util.Arrays; import java.util.Random; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class RadixSortTest { static Random random = new Random(); diff --git a/src/test/java/com/williamfiset/algorithms/sorting/SortingTest.java b/src/test/java/com/williamfiset/algorithms/sorting/SortingTest.java index 32b71e7ca..94a5765f6 100644 --- a/src/test/java/com/williamfiset/algorithms/sorting/SortingTest.java +++ b/src/test/java/com/williamfiset/algorithms/sorting/SortingTest.java @@ -5,7 +5,7 @@ import com.williamfiset.algorithms.utils.TestUtils; import java.util.Arrays; import java.util.EnumSet; -import org.junit.Test; +import org.junit.jupiter.api.Test; // Test all sorting algorithms under various constraints. // diff --git a/src/test/java/com/williamfiset/algorithms/strings/BoyerMooreStringSearchTest.java b/src/test/java/com/williamfiset/algorithms/strings/BoyerMooreStringSearchTest.java index 7318d5070..788121c63 100644 --- a/src/test/java/com/williamfiset/algorithms/strings/BoyerMooreStringSearchTest.java +++ b/src/test/java/com/williamfiset/algorithms/strings/BoyerMooreStringSearchTest.java @@ -6,8 +6,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Random; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.*; public class BoyerMooreStringSearchTest { @@ -15,7 +14,7 @@ public class BoyerMooreStringSearchTest { private Random random; private final int MAX_ITERATION = 20; - @Before + @BeforeEach public void setup() { underTest = new BoyerMooreStringSearch(); random = new Random(); diff --git a/src/test/java/com/williamfiset/algorithms/strings/LongestCommonSubstringTest.java b/src/test/java/com/williamfiset/algorithms/strings/LongestCommonSubstringTest.java index a43c74a75..ebee4d96a 100644 --- a/src/test/java/com/williamfiset/algorithms/strings/LongestCommonSubstringTest.java +++ b/src/test/java/com/williamfiset/algorithms/strings/LongestCommonSubstringTest.java @@ -9,7 +9,7 @@ import com.google.common.collect.ImmutableList; import com.williamfiset.algorithms.utils.TestUtils; import java.util.*; -import org.junit.*; +import org.junit.jupiter.api.*; public class LongestCommonSubstringTest { diff --git a/src/test/java/com/williamfiset/algorithms/strings/ZAlgorithmTest.java b/src/test/java/com/williamfiset/algorithms/strings/ZAlgorithmTest.java index 104bf5170..c8dcd0f28 100644 --- a/src/test/java/com/williamfiset/algorithms/strings/ZAlgorithmTest.java +++ b/src/test/java/com/williamfiset/algorithms/strings/ZAlgorithmTest.java @@ -2,13 +2,12 @@ import static com.google.common.truth.Truth.assertThat; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.*; public class ZAlgorithmTest { private ZAlgorithm underTest; - @Before + @BeforeEach public void setup() { underTest = new ZAlgorithm(); }