├── .gitignore ├── LICENSE ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main └── java │ └── com │ └── packt │ └── datastructuresandalg │ ├── lesson1 │ ├── activity │ │ ├── improveintersection │ │ │ ├── Intersection.java │ │ │ └── solution │ │ │ │ ├── FastInterstectionSol1.java │ │ │ │ └── FastInterstectionSol2.java │ │ └── octaltodecimal │ │ │ ├── OctalToDecimal.java │ │ │ └── solution │ │ │ └── OctalToDecimal.java │ ├── arraysearch │ │ └── ArraySearch.java │ ├── assessment │ │ └── StrEquals.java │ ├── binarysearch │ │ └── BinarySearch.java │ ├── binarytodecimal │ │ └── BinaryToDecimal.java │ ├── checkduplicates │ │ └── Duplicates.java │ ├── circlemath │ │ └── CircleOperations.java │ ├── closestplane │ │ ├── ClosestPlane.java │ │ └── Point.java │ ├── countcharacters │ │ └── CountChars.java │ ├── intersection │ │ └── SimpleIntersection.java │ └── primefactors │ │ └── FindPrimeFactors.java │ ├── lesson2 │ ├── activity │ │ ├── mergesort │ │ │ ├── MergeSort.java │ │ │ └── solution │ │ │ │ └── MergeSort.java │ │ ├── postfix │ │ │ ├── EvalPostfix.java │ │ │ └── solution │ │ │ │ └── EvalPostfix.java │ │ └── selectionsort │ │ │ ├── SelectionSort.java │ │ │ └── solution │ │ │ └── SelectionSort.java │ ├── linkedlist │ │ ├── DblLinkedListNode.java │ │ ├── LinkedList.java │ │ └── LinkedListNode.java │ ├── queue │ │ ├── Queue.java │ │ └── QueueArray.java │ ├── sorting │ │ ├── BinarySearchRecursive.java │ │ ├── BubbleSort.java │ │ └── QuickSort.java │ └── stack │ │ ├── Stack.java │ │ ├── StackArray.java │ │ └── StringReverse.java │ ├── lesson3 │ ├── activity │ │ ├── inordersuccessor │ │ │ ├── InOrderSuccessorBinaryTree.java │ │ │ └── solution │ │ │ │ └── InOrderSuccessorBinaryTree.java │ │ └── openaddressing │ │ │ ├── OpenAddrHashTable.java │ │ │ └── solution │ │ │ ├── OpenAddrHashTable.java │ │ │ └── OpenAddrPair.java │ ├── binarytree │ │ ├── BinaryTree.java │ │ ├── BinaryTreeNode.java │ │ └── SimpleBinaryTree.java │ └── hashtable │ │ ├── ChainedHashTable.java │ │ ├── HashProvider.java │ │ ├── HashTable.java │ │ ├── MultiplicationHashing.java │ │ ├── Pair.java │ │ ├── RemainderHashing.java │ │ └── UniversalHashing.java │ ├── lesson4 │ ├── activity │ │ ├── coinchange │ │ │ ├── CoinChange.java │ │ │ └── solution │ │ │ │ └── CoinChange.java │ │ ├── egyptian │ │ │ ├── EgyptianFractions.java │ │ │ └── solution │ │ │ │ └── EgyptianFractions.java │ │ └── maxsubarray │ │ │ ├── MaximumSubarray.java │ │ │ └── solution │ │ │ └── MaximumSubarray.java │ ├── activityselection │ │ └── ActivitySelection.java │ ├── huffman │ │ └── Huffman.java │ ├── knapsack │ │ └── Knapsack.java │ ├── lcs │ │ └── LongestCommonSubsequence.java │ └── points │ │ └── ClosestPairOfPoints.java │ ├── lesson5 │ ├── activity │ │ ├── badcharacterrule │ │ │ ├── BadCharacterRule.java │ │ │ └── solution │ │ │ │ └── BadCharacterRule.java │ │ ├── boyermoore │ │ │ ├── BoyerMoore.java │ │ │ └── solution │ │ │ │ └── BoyerMoore.java │ │ └── naivestringmatching │ │ │ ├── NaiveStringMatching.java │ │ │ └── solution │ │ │ └── NaiveStringMatching.java │ ├── goodsuffixrule │ │ └── GoodSuffixRule.java │ └── rabinkarp │ │ └── RabinKarp.java │ ├── lesson6 │ ├── activity │ │ ├── floydwarshall │ │ │ ├── FloydWarshall.java │ │ │ └── solution │ │ │ │ └── FloydWarshall.java │ │ ├── maze │ │ │ ├── Maze.java │ │ │ └── solution │ │ │ │ └── Maze.java │ │ └── weightedundirected │ │ │ ├── AdjacencyMatrixWeightedUndirected.java │ │ │ └── solution │ │ │ └── AdjacencyMatrixWeightedUndirected.java │ ├── bfs │ │ └── Graph.java │ ├── dfs │ │ └── Graph.java │ ├── dijkstra │ │ ├── Dijkstra.java │ │ └── DijkstraWithPQ.java │ ├── floydwarshall │ │ └── FloydWarshall.java │ └── graph │ │ ├── AdjacencyListGraph.java │ │ ├── AdjacencyListWeightedGraph.java │ │ └── AdjacencyMatrixGraph.java │ ├── lesson7 │ └── activity │ │ └── sieve │ │ ├── SieveOfEratosthenes.java │ │ └── solution │ │ └── SieveOfEratosthenes.java │ └── setup │ └── HelloWorld.java └── test └── java └── com └── packt └── datastructuresandalg ├── lesson1 └── activity │ ├── improveintersection │ └── IntersectionTest.java │ └── octaltodecimal │ └── OctalToDecimalTest.java ├── lesson2 └── activity │ ├── mergesort │ └── MergeSortTest.java │ ├── postfix │ └── EvalPostfixTest.java │ └── selectionsort │ └── SelectionSortTest.java ├── lesson3 └── activity │ ├── inordersuccessor │ └── InOrderSuccessorBinaryTreeTest.java │ └── openaddressing │ └── OpenAddrHashTableTest.java ├── lesson4 └── activity │ ├── coinchange │ └── CoinChangeTest.java │ ├── egyptian │ └── EgyptianFractionsTest.java │ └── maxsubarray │ └── MaximumSubarrayTest.java ├── lesson5 └── activity │ ├── badcharacterrule │ └── BadCharacterRuleTest.java │ ├── boyermoore │ └── BoyerMooreTest.java │ └── naivestringmatching │ └── NaiveStringMatchingTest.java ├── lesson6 └── activity │ ├── floydwarshall │ └── FloydWarshallTest.java │ ├── maze │ └── MazeTest.java │ └── weightedundirected │ └── AdjacencyMatrixWeightedUndirectedTest.java ├── lesson7 └── activity │ └── sieve │ └── SieveOfEratosthenesTest.java └── setup └── HelloWorldTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | .idea/ 4 | build 5 | out/ 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Training By Packt 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![GitHub issues](https://img.shields.io/github/issues/TrainingByPackt/Data-Structures-and-Algorithms-in-Java.svg)](https://github.com/TrainingByPackt/Data-Structures-and-Algorithms-in-Java/issues) 2 | [![GitHub forks](https://img.shields.io/github/forks/TrainingByPackt/Data-Structures-and-Algorithms-in-Java.svg)](https://github.com/TrainingByPackt/Data-Structures-and-Algorithms-in-Java/network) 3 | [![GitHub stars](https://img.shields.io/github/stars/TrainingByPackt/Data-Structures-and-Algorithms-in-Java.svg)](https://github.com/TrainingByPackt/Data-Structures-and-Algorithms-in-Java/stargazers) 4 | [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](https://github.com/TrainingByPackt/Data-Structures-and-Algorithms-in-Java/pulls) 5 | 6 | 7 | 8 | # Beginning Java Data Structures and Algorithms 9 | Algorithms and data structures are crucial for application performance. This course teaches you tools that you can use to build efficient applications. It starts with an introduction to algorithms and explains bubble, merge, quicksort, and other popular programming patterns. You’ll also learn about data structures such as binary tree, hash table, and graphs. The course progresses to advanced concepts, such as algorithm design paradigms and graph theory. By the end of the course, you will know how to correctly implement common algorithms and data structures within your applications. 10 | 11 | 12 | ## What you will learn 13 | * Understand some of the fundamental concepts behind key algorithms 14 | * Express space and time complexities using Big O notation. 15 | * Correctly implement classic sorting algorithms like merge and quicksort, using native Java data structures 16 | * Correctly implement basic and complex data structures (like hash tables and binary trees) 17 | * Learn about different algorithm design paradigms, such as greedy, divide and conquer, and dynamic programming 18 | * Apply powerful string matching techniques and optimize your application logic 19 | * Master graph representations and learn about different graph algorithms, such as cycle detection, traversal, and shortest path 20 | 21 | 22 | ### Hardware requirements 23 | For an optimal student experience, we recommend the following hardware configuration: 24 | * **Processor**: 2.6 GHz or higher, preferably multi-core 25 | * **Memory**: 4GB RAM 26 | * **Hard disk**: 10GB or more 27 | * A projector 28 | * An Internet connection 29 | 30 | 31 | 32 | ### Software requirements 33 | You’ll also need the following software installed in advance: 34 | * Operating System: Windows (8 or higher). 35 | * Command Prompt or PowerShell on Windows 36 | * Terminal on macOS 37 | * Java SE Development Kit, JDK 8 latest 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | group 'com.packt' 2 | version '1.0-SNAPSHOT' 3 | 4 | apply plugin: 'java' 5 | 6 | sourceCompatibility = 1.8 7 | 8 | repositories { 9 | mavenCentral() 10 | } 11 | 12 | dependencies { 13 | testCompile group: 'junit', name: 'junit', version: '4.12' 14 | } 15 | 16 | task execute(type: JavaExec) { 17 | classpath = sourceSets.main.runtimeClasspath 18 | main = project.hasProperty("mainClass") ? project.getProperty("mainClass") : "com.packt.datastructuresandalg.lesson1.activity.improveintersection.Intersection" 19 | } 20 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TrainingByPackt/Data-Structures-and-Algorithms-in-Java/0e92a22fdda573b457d6d880e506758ac4691371/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'datastructuresandalg' 2 | 3 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson1/activity/improveintersection/Intersection.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson1.activity.improveintersection; 2 | 3 | import com.packt.datastructuresandalg.lesson1.binarysearch.BinarySearch; 4 | 5 | import java.util.Arrays; 6 | import java.util.LinkedList; 7 | import java.util.List; 8 | 9 | public class Intersection { 10 | 11 | private BinarySearch search = new BinarySearch(); 12 | 13 | public List intersection(int[] a, int[] b) { 14 | List result = new LinkedList<>(); 15 | for (int x : a) { 16 | for (int y : b) { 17 | if (x == y) result.add(x); 18 | } 19 | } 20 | return result; 21 | } 22 | 23 | public List intersectionFast(int[] a, int[] b) { 24 | return null; 25 | } 26 | 27 | public void mergeSort(int[] input) { 28 | Arrays.sort(input); 29 | } 30 | 31 | public static void main(String[] args) { 32 | Intersection inter = new Intersection(); 33 | System.out.println(inter.intersection(new int[]{4, 7, 5, 2, 3}, new int[]{4, 2, 3, 9, 1})); 34 | System.out.println(inter.intersection(new int[]{4, 6, 11, 2, 3}, new int[]{5, 11, 3, 9, 1})); 35 | 36 | System.out.println(inter.intersectionFast(new int[]{4, 7, 5, 2, 3}, new int[]{4, 2, 3, 9, 1})); 37 | System.out.println(inter.intersectionFast(new int[]{4, 6, 11, 2, 3}, new int[]{5, 11, 3, 9, 1})); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson1/activity/improveintersection/solution/FastInterstectionSol1.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson1.activity.improveintersection.solution; 2 | 3 | import com.packt.datastructuresandalg.lesson1.binarysearch.BinarySearch; 4 | 5 | import java.util.Arrays; 6 | import java.util.LinkedList; 7 | import java.util.List; 8 | 9 | public class FastInterstectionSol1 { 10 | 11 | private BinarySearch search = new BinarySearch(); 12 | 13 | public List intersectionFast(int[] a, int[] b) { 14 | List result = new LinkedList<>(); 15 | mergeSort(b); 16 | for (int x : a) { 17 | if (search.binarySearch(x, b)) result.add(x); 18 | } 19 | return result; 20 | } 21 | 22 | private void mergeSort(int[] input) { 23 | Arrays.sort(input); 24 | } 25 | 26 | public static void main(String[] args) { 27 | int[] numbers1 = new int[]{66, 24, 75, 22, 12, 87}; 28 | int[] numbers2 = new int[]{32, 41, 98, 66, 39, 24}; 29 | 30 | List result = new FastInterstectionSol1().intersectionFast(numbers1, numbers2); 31 | System.out.println(result); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson1/activity/improveintersection/solution/FastInterstectionSol2.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson1.activity.improveintersection.solution; 2 | 3 | import java.util.Arrays; 4 | import java.util.LinkedList; 5 | import java.util.List; 6 | 7 | public class FastInterstectionSol2 { 8 | 9 | public List intersectionFast(int[] a, int[] b) { 10 | List result = new LinkedList<>(); 11 | mergeSort(a); 12 | mergeSort(b); 13 | int ptrA = 0, ptrB = 0; 14 | while (ptrA < a.length && ptrB < b.length) { 15 | if (a[ptrA] == b[ptrB]) { 16 | result.add(a[ptrA]); 17 | ptrA++; 18 | ptrB++; 19 | } else if (a[ptrA] > b[ptrB]) ptrB++; 20 | else ptrA++; 21 | } 22 | return result; 23 | } 24 | 25 | public void mergeSort(int[] input) { 26 | Arrays.sort(input); 27 | } 28 | 29 | public static void main(String[] args) { 30 | int[] numbers1 = new int[]{66, 24, 75, 22, 12, 87}; 31 | int[] numbers2 = new int[]{32, 41, 98, 66, 39, 24}; 32 | 33 | List result = new FastInterstectionSol2().intersectionFast(numbers1, numbers2); 34 | System.out.println(result); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson1/activity/octaltodecimal/OctalToDecimal.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson1.activity.octaltodecimal; 2 | 3 | public class OctalToDecimal { 4 | public int convertToDecimal(String octal) { 5 | return 999; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson1/activity/octaltodecimal/solution/OctalToDecimal.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson1.activity.octaltodecimal.solution; 2 | 3 | public class OctalToDecimal { 4 | public int convertToDecimal(String oct) { 5 | int result = 0; 6 | for (int i = 1; i <= oct.length(); i++) { 7 | int octDigit = Integer.parseInt(oct.charAt(oct.length() - i) + ""); 8 | result += Math.pow(8, i - 1) * octDigit; 9 | } 10 | return result; 11 | } 12 | 13 | public static void main(String args[]) { 14 | OctalToDecimal octalToDecimal = new OctalToDecimal(); 15 | System.out.println(octalToDecimal.convertToDecimal("17")); 16 | System.out.println(octalToDecimal.convertToDecimal("72625")); 17 | System.out.println(octalToDecimal.convertToDecimal("1")); 18 | System.out.println(octalToDecimal.convertToDecimal("55142")); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson1/arraysearch/ArraySearch.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson1.arraysearch; 2 | 3 | public class ArraySearch { 4 | public int search(String strToMatch, String[] strArray) { 5 | for (int i = 0; i < strArray.length; i++) { 6 | if (strArray[i].equals(strToMatch)) { 7 | return i; 8 | } 9 | } 10 | return -1; 11 | } 12 | 13 | public static void main(String[] args) { 14 | ArraySearch arraySearch = new ArraySearch(); 15 | System.out.println(arraySearch.search("Alien", 16 | new String[]{"Interstellar", "District 9", "Blade Runner", "Alien", "Minority Report", "Primer"})); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson1/assessment/StrEquals.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson1.assessment; 2 | 3 | public class StrEquals { 4 | public boolean strEqual(String a, String b) { 5 | for (int i = 0; i < Math.min(b.length(), a.length()); i++) 6 | if (a.charAt(i) != b.charAt(i)) return false; 7 | return a.length() == b.length(); 8 | } 9 | 10 | public static void main(String[] args) { 11 | StrEquals strEquals = new StrEquals(); 12 | System.out.println(strEquals.strEqual("James", "Joao")); 13 | System.out.println(strEquals.strEqual("Ruth", "Ruth")); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson1/binarysearch/BinarySearch.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson1.binarysearch; 2 | 3 | public class BinarySearch { 4 | public boolean binarySearch(int x, int[] sortedNumbers) { 5 | int end = sortedNumbers.length - 1; 6 | int start = 0; 7 | while (start <= end) { 8 | int mid = (end - start) / 2 + start; 9 | if (sortedNumbers[mid] == x) return true; 10 | else if (sortedNumbers[mid] > x) end = mid - 1; 11 | else start = mid + 1; 12 | } 13 | return false; 14 | } 15 | 16 | public static void main(String args[]) { 17 | BinarySearch binarySearch = new BinarySearch(); 18 | System.out.println(binarySearch.binarySearch(7, new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})); 19 | System.out.println(binarySearch.binarySearch(0, new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})); 20 | } 21 | } -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson1/binarytodecimal/BinaryToDecimal.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson1.binarytodecimal; 2 | 3 | public class BinaryToDecimal { 4 | public int convertToDecimal(String binary) { 5 | int conversion = 1; 6 | int result = 0; 7 | for (int i = 1; i <= binary.length(); i++) { 8 | if (binary.charAt(binary.length() - i) == '1') 9 | result += conversion; 10 | conversion *= 2; 11 | } 12 | return result; 13 | } 14 | 15 | public int convertToDecimalAlt(String binary) { 16 | int result = 0; 17 | for (int i = 1; i <= binary.length(); i++) { 18 | if (binary.charAt(binary.length() - i) == '1') 19 | result += Math.pow(2, i - 1); 20 | } 21 | return result; 22 | } 23 | 24 | public static void main(String args[]) { 25 | BinaryToDecimal binaryToDecimal = new BinaryToDecimal(); 26 | System.out.println(binaryToDecimal.convertToDecimal("10110")); 27 | System.out.println(binaryToDecimal.convertToDecimalAlt("10110")); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson1/checkduplicates/Duplicates.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson1.checkduplicates; 2 | 3 | public class Duplicates { 4 | public boolean containsDuplicates(int[] numbers) { 5 | for (int i=0; i allPlanes) { 10 | double minDistance = Double.MAX_VALUE; 11 | for (Point p1 : allPlanes) { 12 | for (Point p2 : allPlanes) { 13 | double d = p1.distanceTo(p2); 14 | if (d != 0 && d < minDistance) minDistance = d; 15 | } 16 | } 17 | return minDistance; 18 | } 19 | 20 | public static void main(String[] args) { 21 | BinaryToDecimal binaryToDecimal = new BinaryToDecimal(); 22 | ClosestPlane closestPlane = new ClosestPlane(); 23 | 24 | System.out.println("BinaryToDecimal 11011 -> " + binaryToDecimal.convertToDecimal("10110")); 25 | System.out.println("BinaryToDecimal 11011 -> " + binaryToDecimal.convertToDecimalAlt("10110")); 26 | 27 | ArrayList allPlanes = new ArrayList(); 28 | allPlanes.add(new Point(5, 5)); 29 | allPlanes.add(new Point(15, 66)); 30 | allPlanes.add(new Point(105, 42)); 31 | allPlanes.add(new Point(7, 6)); 32 | 33 | System.out.println("Minimum distance: " + closestPlane.minimumDistance(allPlanes)); 34 | 35 | for (int j = 0; j < 7; j++) { 36 | ArrayList allPlanes2 = new ArrayList(); 37 | for (int i = 0; i < (500 * Math.pow(2, j)); i++) { 38 | allPlanes2.add(new Point((int) (Math.random() * 100000.0), (int) (Math.random() * 100000.0))); 39 | } 40 | long start = System.currentTimeMillis(); 41 | double minD = closestPlane.minimumDistance(allPlanes2); 42 | long end = System.currentTimeMillis(); 43 | System.out.println("Minimum distance: " + minD + " for " + allPlanes2.size() + " in: " + (end - start)); 44 | } 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson1/closestplane/Point.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson1.closestplane; 2 | 3 | import java.util.Objects; 4 | 5 | public class Point { 6 | private final int x; 7 | private final int y; 8 | 9 | public Point(int x, int y) { 10 | this.x = x; 11 | this.y = y; 12 | } 13 | 14 | public int getX() { 15 | return x; 16 | } 17 | 18 | public int getY() { 19 | return y; 20 | } 21 | 22 | @Override 23 | public boolean equals(Object o) { 24 | if (this == o) return true; 25 | if (o == null || getClass() != o.getClass()) return false; 26 | Point point = (Point) o; 27 | return x == point.x && 28 | y == point.y; 29 | } 30 | 31 | @Override 32 | public int hashCode() { 33 | return Objects.hash(x, y); 34 | } 35 | 36 | public double distanceTo(Point other) { 37 | return Math.sqrt(Math.pow(this.x - other.x, 2) + Math.pow(this.y - other.y, 2)); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson1/countcharacters/CountChars.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson1.countcharacters; 2 | 3 | public class CountChars { 4 | public int countChars(char c, String str) { 5 | int count = 0; 6 | for (int i = 0; i < str.length(); i++) { 7 | if (str.charAt(i) == c) count++; 8 | } 9 | return count; 10 | } 11 | 12 | public static void main(String args[]) { 13 | CountChars countChars = new CountChars(); 14 | System.out.println(countChars.countChars('a', "Sally sells sea shells on the seashore")); 15 | } 16 | } -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson1/intersection/SimpleIntersection.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson1.intersection; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class SimpleIntersection { 7 | 8 | public List intersection(int[] a, int[] b) { 9 | List result = new ArrayList<>(a.length); 10 | for (int x : a) { 11 | for (int y : b) { 12 | if (x == y) result.add(x); 13 | } 14 | } 15 | return result; 16 | } 17 | 18 | public static void main(String args[]) { 19 | SimpleIntersection simpleIntersection = new SimpleIntersection(); 20 | System.out.println(simpleIntersection.intersection(new int[]{4, 7, 5, 2, 3}, new int[]{4, 2, 3, 9, 1})); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson1/primefactors/FindPrimeFactors.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson1.primefactors; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class FindPrimeFactors { 7 | public List primeFactors(long x) { 8 | ArrayList result = new ArrayList<>(); 9 | long factor = 2; 10 | while (x > 1) { 11 | if (x % factor == 0) { 12 | result.add(factor); 13 | x /= factor; 14 | } else { 15 | factor += 1; 16 | } 17 | } 18 | return result; 19 | } 20 | 21 | public static void main(String args[]) { 22 | FindPrimeFactors findPrimeFactors = new FindPrimeFactors(); 23 | //System.out.println(findPrimeFactors.primeFactors(2100078577L)); 24 | System.out.println(findPrimeFactors.primeFactors(2100078578L)); 25 | } 26 | } -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson2/activity/mergesort/MergeSort.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson2.activity.mergesort; 2 | 3 | public class MergeSort { 4 | 5 | private void merge(int[] array, int start, int middle, int end) { 6 | 7 | } 8 | 9 | private void mergeSort(int[] array, int start, int end) { 10 | 11 | } 12 | 13 | public void mergeSort(int[] array) { 14 | 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson2/activity/mergesort/solution/MergeSort.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson2.activity.mergesort.solution; 2 | 3 | public class MergeSort { 4 | 5 | private void merge(int[] array, int start, int middle, int end) { 6 | int i = start; 7 | int j = middle + 1; 8 | int[] arrayTemp = new int[end - start + 1]; 9 | for (int k = 0; k < arrayTemp.length; k++) { 10 | if (i <= middle && (j > end || array[i] <= array[j])) { 11 | arrayTemp[k] = array[i]; 12 | i++; 13 | } else { 14 | arrayTemp[k] = array[j]; 15 | j++; 16 | } 17 | } 18 | System.arraycopy(arrayTemp, 0, array, start, arrayTemp.length); 19 | } 20 | 21 | private void mergeSort(int[] array, int start, int end) { 22 | if (start < end) { 23 | int middle = (end - start) / 2 + start; 24 | mergeSort(array, start, middle); 25 | mergeSort(array, middle + 1, end); 26 | merge(array, start, middle, end); 27 | } 28 | } 29 | 30 | public void mergeSort(int[] array) { 31 | mergeSort(array, 0, array.length - 1); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson2/activity/postfix/EvalPostfix.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson2.activity.postfix; 2 | 3 | public class EvalPostfix { 4 | public double evaluate(String postfix) { 5 | return 0.0; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson2/activity/postfix/solution/EvalPostfix.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson2.activity.postfix.solution; 2 | 3 | import com.packt.datastructuresandalg.lesson2.stack.Stack; 4 | 5 | public class EvalPostfix { 6 | 7 | public double evaluate(String postfix) { 8 | Stack stack = new Stack<>(); 9 | for (String token : postfix.split(" ")) { 10 | if (token.chars().allMatch(Character::isDigit)) 11 | stack.push(Integer.parseInt(token)); 12 | else if (token.equals("/")) 13 | stack.pop().flatMap(op1 -> stack.pop().map(op2 -> op2 / op1)) 14 | .ifPresent(stack::push); 15 | else if (token.equals("*")) 16 | stack.pop().flatMap(op1 -> stack.pop().map(op2 -> op2 * op1)) 17 | .ifPresent(stack::push); 18 | else if (token.equals("+")) 19 | stack.pop().flatMap(op1 -> stack.pop().map(op2 -> op2 + op1)) 20 | .ifPresent(stack::push); 21 | else if (token.equals("-")) 22 | stack.pop().flatMap(op1 -> stack.pop().map(op2 -> op2 - op1)) 23 | .ifPresent(stack::push); 24 | } 25 | return stack.pop().orElseThrow(() -> new IllegalArgumentException("Bad expression")); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson2/activity/selectionsort/SelectionSort.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson2.activity.selectionsort; 2 | 3 | public class SelectionSort { 4 | 5 | public void sort(int[] array) { 6 | 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson2/activity/selectionsort/solution/SelectionSort.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson2.activity.selectionsort.solution; 2 | 3 | public class SelectionSort { 4 | public void sort(int[] array) { 5 | for (int i = 0; i < array.length - 1; i++) { 6 | int minPtr = i; 7 | for (int j = i; j < array.length; j++) { 8 | if (array[j] < array[minPtr]) minPtr = j; 9 | } 10 | swap(array, minPtr, i); 11 | } 12 | } 13 | 14 | private void swap(int[] numbers, int j, int k) { 15 | int temp = numbers[j]; 16 | numbers[j] = numbers[k]; 17 | numbers[k] = temp; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson2/linkedlist/DblLinkedListNode.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson2.linkedlist; 2 | 3 | import java.util.Optional; 4 | 5 | public class DblLinkedListNode { 6 | private V value; 7 | private DblLinkedListNode next; 8 | private DblLinkedListNode previous; 9 | 10 | public DblLinkedListNode(V value, 11 | DblLinkedListNode next, 12 | DblLinkedListNode previous) { 13 | this.value = value; 14 | this.next = next; 15 | this.previous = previous; 16 | } 17 | 18 | public Optional> getNext() { 19 | return Optional.ofNullable(next); 20 | } 21 | 22 | public Optional> getPrevious() { 23 | return Optional.ofNullable(previous); 24 | } 25 | 26 | public V getValue() { 27 | return value; 28 | } 29 | 30 | public DblLinkedListNode setValue(V value) { 31 | this.value = value; 32 | return this; 33 | } 34 | 35 | public DblLinkedListNode setNext(DblLinkedListNode next) { 36 | this.next = next; 37 | return this; 38 | } 39 | 40 | 41 | public DblLinkedListNode setPrevious(DblLinkedListNode previous) { 42 | this.previous = previous; 43 | return this; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson2/linkedlist/LinkedList.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson2.linkedlist; 2 | 3 | import java.util.Optional; 4 | 5 | public class LinkedList { 6 | private LinkedListNode head; 7 | 8 | public LinkedList() { 9 | head = null; 10 | } 11 | 12 | public void addFront(V item) { 13 | this.head = new LinkedListNode<>(item, head); 14 | } 15 | 16 | public void deleteFront() { 17 | Optional> firstNode = Optional.ofNullable(this.head); 18 | this.head = firstNode.flatMap(LinkedListNode::getNext).orElse(null); 19 | firstNode.ifPresent(n -> n.setNext(null)); 20 | } 21 | 22 | public Optional> find(V item) { 23 | Optional> node = Optional.ofNullable(this.head); 24 | while (node.filter(n -> n.getValue() != item).isPresent()) { 25 | node = node.flatMap(LinkedListNode::getNext); 26 | } 27 | return node; 28 | } 29 | 30 | public void addAfter(LinkedListNode aNode, V item) { 31 | aNode.setNext(new LinkedListNode<>(item, aNode.getNext().orElse(null))); 32 | } 33 | 34 | public String toString() { 35 | Optional> node = Optional.ofNullable(this.head); 36 | StringBuffer result = new StringBuffer("["); 37 | while (node.isPresent()) { 38 | node.ifPresent(n -> result.append(n.getValue().toString())); 39 | node = node.flatMap(LinkedListNode::getNext); 40 | node.ifPresent(n -> result.append(", ")); 41 | } 42 | return result.append("]").toString(); 43 | } 44 | 45 | public static void main(String[] args) { 46 | LinkedList list = new LinkedList(); 47 | list.addFront("Isabel"); 48 | list.addFront("Ruth"); 49 | list.addFront("Karl"); 50 | list.addFront("John"); 51 | System.out.println(list.find("Isabel")); 52 | System.out.println(list.find("Ruth")); 53 | System.out.println(list.find("Karl")); 54 | System.out.println(list.find("John")); 55 | System.out.println(list.find("James")); 56 | 57 | list.deleteFront(); 58 | System.out.println(list.find("John")); 59 | list.addFront("Oliver"); 60 | System.out.println(list.find("Ruth")); 61 | list.addAfter(list.find("Ruth").get(), "Sam"); 62 | System.out.println(list.toString()); 63 | 64 | LinkedListNode x = new LinkedListNode<>(5, null); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson2/linkedlist/LinkedListNode.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson2.linkedlist; 2 | 3 | import java.util.Optional; 4 | 5 | public class LinkedListNode { 6 | private V value; 7 | private LinkedListNode next; 8 | 9 | public LinkedListNode(V value, LinkedListNode next) { 10 | this.value = value; 11 | this.next = next; 12 | } 13 | 14 | public Optional> getNext() { 15 | return Optional.ofNullable(next); 16 | } 17 | 18 | public V getValue() { 19 | return value; 20 | } 21 | 22 | public LinkedListNode setValue(V value) { 23 | this.value = value; 24 | return this; 25 | } 26 | 27 | public LinkedListNode setNext(LinkedListNode next) { 28 | this.next = next; 29 | return this; 30 | } 31 | 32 | @Override 33 | public String toString() { 34 | return "LinkedListNode{" + 35 | "value=" + value + 36 | '}'; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson2/queue/Queue.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson2.queue; 2 | 3 | import com.packt.datastructuresandalg.lesson2.linkedlist.DblLinkedListNode; 4 | 5 | import java.util.Optional; 6 | 7 | public class Queue { 8 | private DblLinkedListNode head; 9 | private DblLinkedListNode tail; 10 | 11 | public Queue() { 12 | head = null; 13 | tail = null; 14 | } 15 | 16 | public void enqueue(V item) { 17 | DblLinkedListNode node = new DblLinkedListNode<>(item, null, tail); 18 | Optional.ofNullable(tail).ifPresent(n -> n.setNext(node)); 19 | tail = node; 20 | if(head == null) head = node; 21 | } 22 | 23 | public Optional dequeue() { 24 | Optional> node = Optional.ofNullable(head); 25 | head = node.flatMap(DblLinkedListNode::getNext).orElse(null); 26 | Optional.ofNullable(head).ifPresent(n -> n.setPrevious(null)); 27 | if (head == null) tail = null; 28 | return node.map(DblLinkedListNode::getValue); 29 | } 30 | 31 | public static void main(String[] args) { 32 | Queue q = new Queue<>(); 33 | q.enqueue("one"); 34 | q.enqueue("two"); 35 | q.enqueue("three"); 36 | 37 | System.out.println(q.dequeue()); 38 | System.out.println(q.dequeue()); 39 | System.out.println(q.dequeue()); 40 | System.out.println(q.dequeue()); 41 | 42 | q.enqueue("one"); 43 | 44 | System.out.println(q.dequeue()); 45 | System.out.println(q.dequeue()); 46 | 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson2/queue/QueueArray.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson2.queue; 2 | 3 | import java.util.Optional; 4 | 5 | public class QueueArray { 6 | private V[] array; 7 | private int headPtr = 0; 8 | private int tailPtr = 0; 9 | private boolean full = false; 10 | 11 | public boolean enqueueSafe(V item) { 12 | if (!full) { 13 | array[tailPtr] = item; 14 | tailPtr = (tailPtr + 1) % array.length; 15 | this.full = tailPtr == headPtr; 16 | return true; 17 | } 18 | return false; 19 | } 20 | 21 | public Optional dequeueSafe() { 22 | if (headPtr != tailPtr || full) { 23 | Optional item = Optional.of(array[headPtr]); 24 | headPtr = (headPtr + 1) % array.length; 25 | this.full = false; 26 | return item; 27 | } else return Optional.empty(); 28 | } 29 | 30 | 31 | public QueueArray(int capacity) { 32 | array = (V[]) new Object[capacity]; 33 | } 34 | 35 | public void enqueue(V item) { 36 | array[tailPtr] = item; 37 | tailPtr = (tailPtr + 1) % array.length; 38 | } 39 | 40 | public Optional dequeue() { 41 | if (headPtr != tailPtr) { 42 | Optional item = Optional.of(array[headPtr]); 43 | headPtr = (headPtr + 1) % array.length; 44 | return item; 45 | } else return Optional.empty(); 46 | } 47 | 48 | 49 | public static void main(String[] args) { 50 | QueueArray q = new QueueArray<>(5); 51 | 52 | System.out.println(q.enqueueSafe("one")); 53 | System.out.println(q.enqueueSafe("two")); 54 | System.out.println(q.enqueueSafe("three")); 55 | System.out.println(q.enqueueSafe("four")); 56 | System.out.println(q.enqueueSafe("five")); 57 | System.out.println(q.enqueueSafe("six")); 58 | 59 | System.out.println(q.dequeue()); 60 | System.out.println(q.dequeue()); 61 | System.out.println(q.dequeue()); 62 | System.out.println(q.dequeue()); 63 | System.out.println(q.dequeue()); 64 | System.out.println(q.dequeue()); 65 | 66 | System.out.println(q.enqueueSafe("one")); 67 | System.out.println(q.enqueueSafe("two")); 68 | System.out.println(q.enqueueSafe("three")); 69 | 70 | System.out.println(q.dequeue()); 71 | System.out.println(q.dequeue()); 72 | System.out.println(q.dequeue()); 73 | System.out.println(q.dequeue()); 74 | 75 | System.out.println(q.enqueueSafe("one")); 76 | System.out.println(q.enqueueSafe("two")); 77 | System.out.println(q.enqueueSafe("three")); 78 | 79 | System.out.println(q.dequeue()); 80 | System.out.println(q.dequeue()); 81 | System.out.println(q.dequeue()); 82 | System.out.println(q.dequeue()); 83 | } 84 | } -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson2/sorting/BinarySearchRecursive.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson2.sorting; 2 | 3 | 4 | public class BinarySearchRecursive { 5 | public boolean binarySearch(int x, int[] sortedNumbers) { 6 | return binarySearch(x, sortedNumbers, 0, sortedNumbers.length); 7 | } 8 | 9 | public boolean binarySearch(int x, int[] sortedNumbers, int start, int end) { 10 | if (start <= end) { 11 | int mid = (end - start) / 2 + start; 12 | if (sortedNumbers[mid] == x) return true; 13 | if (sortedNumbers[mid] > x) 14 | return binarySearch(x, sortedNumbers, start, mid - 1); 15 | return binarySearch(x, sortedNumbers, mid + 1, end); 16 | } 17 | return false; 18 | } 19 | 20 | public static void main(String args[]) { 21 | BinarySearchRecursive binarySearch = new BinarySearchRecursive(); 22 | System.out.println(binarySearch.binarySearch(7, new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})); 23 | System.out.println(binarySearch.binarySearch(0, new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson2/sorting/BubbleSort.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson2.sorting; 2 | 3 | import java.util.Arrays; 4 | 5 | public class BubbleSort { 6 | 7 | public void sort(int[] numbers) { 8 | for (int i = 1; i < numbers.length; i++) { 9 | for (int j = 0; j < numbers.length - 1; j++) { 10 | if (numbers[j] > numbers[j + 1]) { 11 | int temp = numbers[j]; 12 | numbers[j] = numbers[j + 1]; 13 | numbers[j + 1] = temp; 14 | } 15 | } 16 | } 17 | } 18 | 19 | public void sortImprovement1(int[] numbers) { 20 | for (int i = 1; i < numbers.length; i++) { 21 | for (int j = 0; j < numbers.length - i; j++) { 22 | if (numbers[j] > numbers[j + 1]) { 23 | swap(numbers, j, j + 1); 24 | } 25 | } 26 | } 27 | } 28 | 29 | public void sortImprovement2(int[] numbers) { 30 | int i = 0; 31 | boolean swapOccured = true; 32 | while (swapOccured) { 33 | swapOccured = false; 34 | i++; 35 | for (int j = 0; j < numbers.length - i; j++) { 36 | if (numbers[j] > numbers[j + 1]) { 37 | swap(numbers, j, j + 1); 38 | swapOccured = true; 39 | } 40 | } 41 | } 42 | } 43 | 44 | private void swap(int[] numbers, int j, int k) { 45 | int temp = numbers[j]; 46 | numbers[j] = numbers[k]; 47 | numbers[k] = temp; 48 | } 49 | 50 | public static void main(String[] args) { 51 | BubbleSort bubbleSort = new BubbleSort(); 52 | int[] numbers = new int[]{2, 5, 7, 2, 4, 2, 8, 1, 0}; 53 | int[] numbers1 = new int[]{2, 5, 7, 2, 4, 2, 8, 1, 0}; 54 | int[] numbers2 = new int[]{2, 5, 7, 2, 4, 2, 8, 1, 0}; 55 | bubbleSort.sort(numbers); 56 | bubbleSort.sortImprovement1(numbers1); 57 | bubbleSort.sortImprovement2(numbers2); 58 | System.out.println(Arrays.toString(numbers)); 59 | System.out.println(Arrays.toString(numbers1)); 60 | System.out.println(Arrays.toString(numbers2)); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson2/sorting/QuickSort.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson2.sorting; 2 | 3 | import java.util.Arrays; 4 | 5 | public class QuickSort { 6 | public void sort(int[] numbers) { 7 | sort(numbers, 0, numbers.length - 1); 8 | } 9 | 10 | private void sort(int[] numbers, int start, int end) { 11 | if (start < end) { 12 | int p = partition(numbers, start, end); 13 | sort(numbers, start, p - 1); 14 | sort(numbers, p + 1, end); 15 | } 16 | } 17 | 18 | private int partition(int[] numbers, int start, int end) { 19 | int pivot = numbers[end]; 20 | int x = start - 1; 21 | for (int i = start; i < end; i++) { 22 | if (numbers[i] < pivot) { 23 | x++; 24 | swap(numbers, x, i); 25 | } 26 | } 27 | swap(numbers, x + 1, end); 28 | return x + 1; 29 | } 30 | 31 | private void swap(int[] numbers, int j, int k) { 32 | int temp = numbers[j]; 33 | numbers[j] = numbers[k]; 34 | numbers[k] = temp; 35 | } 36 | 37 | 38 | public static void main(String args[]) { 39 | QuickSort quickSort = new QuickSort(); 40 | int[] numbers = new int[]{2, 5, 7, 2, 4, 2, 8, 1, 0, 9, 3, 6}; 41 | quickSort.sort(numbers); 42 | System.out.println(Arrays.toString(numbers)); 43 | } 44 | 45 | } -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson2/stack/Stack.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson2.stack; 2 | 3 | import com.packt.datastructuresandalg.lesson2.linkedlist.LinkedListNode; 4 | 5 | import java.util.Optional; 6 | 7 | public class Stack { 8 | private LinkedListNode head; 9 | 10 | public void push(V item) { 11 | head = new LinkedListNode(item, head); 12 | } 13 | 14 | public Optional pop() { 15 | Optional> node = Optional.ofNullable(head); 16 | head = node.flatMap(LinkedListNode::getNext).orElse(null); 17 | return node.map(LinkedListNode::getValue); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson2/stack/StackArray.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson2.stack; 2 | 3 | import java.util.Optional; 4 | 5 | public class StackArray { 6 | private V[] array; 7 | private int headPtr = 0; 8 | 9 | public StackArray(int capacity) { 10 | array = (V[]) new Object[capacity]; 11 | } 12 | 13 | public void push(V item) { 14 | array[headPtr++] = item; 15 | } 16 | 17 | public Optional pop() { 18 | if (headPtr > 0) return Optional.of(array[--headPtr]); 19 | else return Optional.empty(); 20 | } 21 | } -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson2/stack/StringReverse.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson2.stack; 2 | 3 | import java.util.Optional; 4 | 5 | public class StringReverse { 6 | 7 | public String reverse(String str) { 8 | StringBuilder result = new StringBuilder(); 9 | StackArray stack = new StackArray<>(100); 10 | for (char c : str.toCharArray()) 11 | stack.push(c); 12 | Optional optChar = stack.pop(); 13 | while (optChar.isPresent()) { 14 | result.append(optChar.get()); 15 | optChar = stack.pop(); 16 | } 17 | return result.toString(); 18 | } 19 | 20 | public static void main(String[] args) { 21 | System.out.println(new StringReverse().reverse("This will be reversed")); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson3/activity/inordersuccessor/InOrderSuccessorBinaryTree.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson3.activity.inordersuccessor; 2 | 3 | import com.packt.datastructuresandalg.lesson3.binarytree.SimpleBinaryTree; 4 | 5 | import java.util.Optional; 6 | 7 | public class InOrderSuccessorBinaryTree extends SimpleBinaryTree { 8 | public Optional inOrderSuccessorKey(K key) { 9 | return null; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson3/activity/inordersuccessor/solution/InOrderSuccessorBinaryTree.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson3.activity.inordersuccessor.solution; 2 | 3 | import com.packt.datastructuresandalg.lesson3.binarytree.BinaryTreeNode; 4 | import com.packt.datastructuresandalg.lesson3.binarytree.SimpleBinaryTree; 5 | 6 | import java.util.Optional; 7 | 8 | public class InOrderSuccessorBinaryTree extends SimpleBinaryTree { 9 | public Optional inOrderSuccessorKey(K key) { 10 | Optional> node = Optional.ofNullable(root); 11 | Optional successor = Optional.empty(); 12 | while (node.isPresent() && !node.get().getKey().equals(key)) { 13 | if (((Comparable) node.get().getKey()).compareTo(key) > 0) { 14 | successor = node.map(BinaryTreeNode::getKey); 15 | node = node.flatMap(BinaryTreeNode::getLeft); 16 | } else 17 | node = node.flatMap(BinaryTreeNode::getRight); 18 | } 19 | 20 | return node.flatMap(BinaryTreeNode::getRight).map(this::minKey) 21 | .map(Optional::of).orElse(successor); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson3/activity/openaddressing/OpenAddrHashTable.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson3.activity.openaddressing; 2 | 3 | import com.packt.datastructuresandalg.lesson3.hashtable.HashProvider; 4 | import com.packt.datastructuresandalg.lesson3.hashtable.HashTable; 5 | import com.packt.datastructuresandalg.lesson3.hashtable.Pair; 6 | 7 | import java.util.Optional; 8 | 9 | public class OpenAddrHashTable implements HashTable { 10 | private final HashProvider hashProvider; 11 | private Pair[] array; 12 | 13 | public OpenAddrHashTable(int capacity, HashProvider hashProvider) { 14 | array = new Pair[capacity]; 15 | this.hashProvider = hashProvider; 16 | } 17 | 18 | public void put(K key, V value) { 19 | } 20 | 21 | public void remove(K key) { 22 | } 23 | 24 | public Optional get(K key) { 25 | return Optional.empty(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson3/activity/openaddressing/solution/OpenAddrHashTable.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson3.activity.openaddressing.solution; 2 | 3 | import com.packt.datastructuresandalg.lesson3.hashtable.HashProvider; 4 | import com.packt.datastructuresandalg.lesson3.hashtable.HashTable; 5 | 6 | import java.util.Optional; 7 | 8 | public class OpenAddrHashTable implements HashTable { 9 | private final HashProvider hashProvider; 10 | private OpenAddrPair[] array; 11 | 12 | public OpenAddrHashTable(int capacity, HashProvider hashProvider) { 13 | array = new OpenAddrPair[capacity]; 14 | this.hashProvider = hashProvider; 15 | } 16 | 17 | public void put(K key, V value) { 18 | int s = array.length; 19 | int hashValue = hashProvider.hashKey(key, s); 20 | int i = 0; 21 | while (i < s && array[(hashValue + i) % s] != null && 22 | !array[(hashValue + i) % s].isDeleted()) 23 | i++; 24 | if (i < s) array[(hashValue + i) % s] = new OpenAddrPair<>(key, value); 25 | } 26 | 27 | private int searchPosition(K key) { 28 | int s = array.length; 29 | int hashValue = hashProvider.hashKey(key, s); 30 | int i = 0; 31 | while (i < s && 32 | array[(hashValue + i) % s] != null && 33 | !array[(hashValue + i) % s].getKey().equals(key)) 34 | i++; 35 | return (hashValue + i) % s; 36 | } 37 | 38 | public Optional get(K key) { 39 | return Optional.ofNullable(array[searchPosition(key)]) 40 | .filter(kv -> !kv.isDeleted()) 41 | .filter(kv -> kv.getKey().equals(key)) 42 | .map(OpenAddrPair::getValue); 43 | } 44 | 45 | public void remove(K key) { 46 | Optional.ofNullable(array[searchPosition(key)]) 47 | .ifPresent(kv -> kv.setDeleted(true)); 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson3/activity/openaddressing/solution/OpenAddrPair.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson3.activity.openaddressing.solution; 2 | 3 | public class OpenAddrPair { 4 | private final K key; 5 | private final V value; 6 | private boolean deleted; 7 | 8 | public OpenAddrPair(K key, V value) { 9 | this.key = key; 10 | this.value = value; 11 | this.deleted = false; 12 | } 13 | 14 | public K getKey() { 15 | return key; 16 | } 17 | 18 | public V getValue() { 19 | return value; 20 | } 21 | 22 | public boolean isDeleted() { 23 | return deleted; 24 | } 25 | 26 | public void setDeleted(boolean deleted) { 27 | this.deleted = deleted; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson3/binarytree/BinaryTree.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson3.binarytree; 2 | 3 | import java.util.Optional; 4 | 5 | public interface BinaryTree { 6 | void put(K key,V value); 7 | 8 | Optional get(K key); 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson3/binarytree/BinaryTreeNode.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson3.binarytree; 2 | 3 | import java.util.Optional; 4 | 5 | public class BinaryTreeNode { 6 | private BinaryTreeNode left; 7 | private BinaryTreeNode right; 8 | private K key; 9 | private V value; 10 | 11 | public BinaryTreeNode(K key, V value) { 12 | this.key = key; 13 | this.value = value; 14 | } 15 | 16 | public Optional> getLeft() { 17 | return Optional.ofNullable(left); 18 | } 19 | 20 | public Optional> getRight() { 21 | return Optional.ofNullable(right); 22 | } 23 | 24 | public void setLeft(BinaryTreeNode left) { 25 | this.left = left; 26 | } 27 | 28 | public void setRight(BinaryTreeNode right) { 29 | this.right = right; 30 | } 31 | 32 | public K getKey() { 33 | return key; 34 | } 35 | 36 | public void setKey(K key) { 37 | this.key = key; 38 | } 39 | 40 | public V getValue() { 41 | return value; 42 | } 43 | 44 | public void setValue(V value) { 45 | this.value = value; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson3/binarytree/SimpleBinaryTree.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson3.binarytree; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Optional; 5 | import java.util.Queue; 6 | 7 | public class SimpleBinaryTree implements BinaryTree { 8 | protected BinaryTreeNode root; 9 | 10 | public void put(K key, V value) { 11 | if (root == null) 12 | root = new BinaryTreeNode<>(key, value); 13 | else 14 | put(key, value, root); 15 | } 16 | 17 | private void put(K key, V value, BinaryTreeNode node) { 18 | if (((Comparable) key).compareTo(node.getKey()) == 0) { 19 | node.setKey(key); 20 | node.setValue(value); 21 | } else if (((Comparable) key).compareTo(node.getKey()) < 0) { 22 | if (node.getLeft().isPresent()) 23 | put(key, value, node.getLeft().get()); 24 | else 25 | node.setLeft(new BinaryTreeNode<>(key, value)); 26 | } else { 27 | if (node.getRight().isPresent()) 28 | put(key, value, node.getRight().get()); 29 | else 30 | node.setRight(new BinaryTreeNode<>(key, value)); 31 | } 32 | } 33 | 34 | public Optional get(K key) { 35 | return Optional.ofNullable(root).flatMap(n -> get(key, n)); 36 | } 37 | 38 | private Optional get(K key, BinaryTreeNode node) { 39 | if (((Comparable) key).compareTo(node.getKey()) == 0) 40 | return Optional.of(node.getValue()); 41 | else if (((Comparable) key).compareTo(node.getKey()) < 0) 42 | return node.getLeft().flatMap(n -> get(key, n)); 43 | else 44 | return node.getRight().flatMap(n -> get(key, n)); 45 | } 46 | 47 | public void leftRotate(BinaryTreeNode nodeX, 48 | BinaryTreeNode parent) { 49 | BinaryTreeNode nodeY = nodeX.getRight().get(); 50 | nodeX.setRight(nodeY.getLeft().orElse(null)); 51 | if (parent == null) 52 | this.root = nodeY; 53 | else if (parent.getLeft().filter(n -> n == nodeX).isPresent()) 54 | parent.setLeft(nodeY); 55 | else 56 | parent.setRight(nodeY); 57 | nodeY.setLeft(nodeX); 58 | } 59 | 60 | public void rightRotate(BinaryTreeNode nodeX, 61 | BinaryTreeNode parent) { 62 | BinaryTreeNode nodeY = nodeX.getLeft().get(); 63 | nodeX.setLeft(nodeY.getRight().orElse(null)); 64 | if (parent == null) 65 | this.root = nodeY; 66 | else if (parent.getRight().filter(n -> n == nodeX).isPresent()) 67 | parent.setRight(nodeY); 68 | else 69 | parent.setLeft(nodeY); 70 | nodeY.setRight(nodeX); 71 | } 72 | 73 | 74 | public Optional minKey() { 75 | return Optional.ofNullable(root).map(this::minKey); 76 | } 77 | 78 | protected K minKey(BinaryTreeNode node) { 79 | return node.getLeft().map(this::minKey).orElse(node.getKey()); 80 | } 81 | 82 | public void printBfs() { 83 | Optional.ofNullable(root).ifPresent(r -> { 84 | Queue> queue = new LinkedList<>(); 85 | queue.add(r); 86 | while (!queue.isEmpty()) { 87 | BinaryTreeNode node = queue.remove(); 88 | System.out.println(node.getKey()); 89 | node.getLeft().ifPresent(queue::add); 90 | node.getRight().ifPresent(queue::add); 91 | } 92 | }); 93 | } 94 | 95 | 96 | public void printDfs() { 97 | Optional.ofNullable(root).ifPresent(this::printDfs); 98 | } 99 | 100 | private void printDfs(BinaryTreeNode node) { 101 | //System.out.println("PREORDER " + node.getKey()); 102 | node.getLeft().ifPresent(this::printDfs); 103 | System.out.println("INORDER " + node.getKey()); 104 | node.getRight().ifPresent(this::printDfs); 105 | //System.out.println("POSTORDER " + node.getKey()); 106 | } 107 | 108 | 109 | public static void main(String[] args) { 110 | SimpleBinaryTree binaryTree = new SimpleBinaryTree(); 111 | System.out.println(binaryTree.minKey()); 112 | binaryTree.put(457998224, "Isabel"); 113 | binaryTree.put(366112467, "John"); 114 | binaryTree.put(671031776, "Ruth"); 115 | binaryTree.put(225198452, "Sarah"); 116 | binaryTree.put(419274013, "Peter"); 117 | binaryTree.put(751965387, "Tom"); 118 | 119 | System.out.println(binaryTree.get(457998224)); 120 | System.out.println(binaryTree.get(366112467)); 121 | System.out.println(binaryTree.get(671031776)); 122 | System.out.println(binaryTree.get(225198452)); 123 | System.out.println(binaryTree.get(419274013)); 124 | System.out.println(binaryTree.get(751965387)); 125 | 126 | binaryTree.put(751965387, "Sam"); 127 | 128 | System.out.println(binaryTree.get(751965387)); 129 | System.out.println(binaryTree.get(999999999)); 130 | System.out.println(binaryTree.minKey()); 131 | 132 | binaryTree.printDfs(); 133 | binaryTree.printBfs(); 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson3/hashtable/ChainedHashTable.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson3.hashtable; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Optional; 5 | 6 | public class ChainedHashTable implements HashTable { 7 | private final HashProvider hashProvider; 8 | private LinkedList>[] array; 9 | 10 | public ChainedHashTable(int capacity, HashProvider hashProvider) { 11 | array = new LinkedList[capacity]; 12 | for (int i = 0; i < capacity; i++) array[i] = new LinkedList<>(); 13 | this.hashProvider = hashProvider; 14 | } 15 | 16 | public void put(K key, V value) { 17 | int hashValue = hashProvider.hashKey(key, array.length); 18 | array[hashValue].addFirst(new Pair<>(key, value)); 19 | } 20 | 21 | public Optional get(K key) { 22 | int hashValue = hashProvider.hashKey(key, array.length); 23 | return array[hashValue].stream() 24 | .filter(keyValue -> keyValue.getKey().equals(key)) 25 | .findFirst() 26 | .map(Pair::getValue); 27 | } 28 | 29 | public void remove(K key) { 30 | int hashValue = hashProvider.hashKey(key, array.length); 31 | array[hashValue].removeIf(p -> p.getKey().equals(key)); 32 | } 33 | 34 | public static void main(String args[]) { 35 | ChainedHashTable chainedHashTable = new ChainedHashTable<>(10, new RemainderHashing()); 36 | chainedHashTable.put(12,"Isabel"); 37 | chainedHashTable.put(22,"Ruth"); 38 | chainedHashTable.put(32,"Michelle"); 39 | chainedHashTable.put(11,"James"); 40 | chainedHashTable.put(21,"John"); 41 | chainedHashTable.put(31,"Peter"); 42 | System.out.println(chainedHashTable.get(12)); 43 | System.out.println(chainedHashTable.get(22)); 44 | System.out.println(chainedHashTable.get(32)); 45 | System.out.println(chainedHashTable.get(11)); 46 | System.out.println(chainedHashTable.get(21)); 47 | System.out.println(chainedHashTable.get(31)); 48 | System.out.println(chainedHashTable.get(42)); 49 | System.out.println(chainedHashTable.get(45)); 50 | chainedHashTable.remove(31); 51 | System.out.println(chainedHashTable.get(31)); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson3/hashtable/HashProvider.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson3.hashtable; 2 | 3 | public interface HashProvider { 4 | int hashKey(K key, int tableSize); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson3/hashtable/HashTable.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson3.hashtable; 2 | 3 | import java.util.Optional; 4 | 5 | public interface HashTable { 6 | void put(K key,V value); 7 | 8 | Optional get(K key); 9 | 10 | void remove(K key); 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson3/hashtable/MultiplicationHashing.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson3.hashtable; 2 | 3 | public class MultiplicationHashing implements HashProvider { 4 | private double k; 5 | 6 | public MultiplicationHashing(double k) { 7 | this.k = k; 8 | } 9 | 10 | public int hashKey(Integer key, int tableSize) { 11 | return (int) (tableSize * (k * key % 1)); 12 | } 13 | 14 | public static void main(String[] args) { 15 | MultiplicationHashing multiplicationHashing = new MultiplicationHashing((Math.sqrt(5) - 1) / 2); 16 | System.out.println(multiplicationHashing.hashKey(337481990, 1000)); 17 | System.out.println(multiplicationHashing.hashKey(116241990, 1000)); 18 | System.out.println(multiplicationHashing.hashKey(983611990, 1000)); 19 | System.out.println(multiplicationHashing.hashKey(201031990, 1000)); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson3/hashtable/Pair.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson3.hashtable; 2 | 3 | public class Pair { 4 | private final K key; 5 | private final V value; 6 | 7 | public Pair(K key, V value) { 8 | this.key = key; 9 | this.value = value; 10 | } 11 | 12 | public K getKey() { 13 | return key; 14 | } 15 | 16 | public V getValue() { 17 | return value; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson3/hashtable/RemainderHashing.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson3.hashtable; 2 | 3 | public class RemainderHashing implements HashProvider{ 4 | 5 | public int hashKey(Integer key, int tableSize) { 6 | return key % tableSize; 7 | } 8 | 9 | public static void main(String[] args) { 10 | RemainderHashing remainderHashing = new RemainderHashing(); 11 | System.out.println(remainderHashing.hashKey(337481990, 1000)); 12 | System.out.println(remainderHashing.hashKey(116241990, 1000)); 13 | System.out.println(remainderHashing.hashKey(983611990, 1000)); 14 | System.out.println(remainderHashing.hashKey(201031990, 1000)); 15 | 16 | System.out.println(remainderHashing.hashKey(337481990, 1447)); 17 | System.out.println(remainderHashing.hashKey(116241990, 1447)); 18 | System.out.println(remainderHashing.hashKey(983611990, 1447)); 19 | System.out.println(remainderHashing.hashKey(201031990, 1447)); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson3/hashtable/UniversalHashing.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson3.hashtable; 2 | 3 | import java.math.BigInteger; 4 | 5 | public class UniversalHashing implements HashProvider { 6 | 7 | private final BigInteger i, j; 8 | private final long p = 47055833459L; 9 | 10 | public UniversalHashing() { 11 | j = BigInteger.valueOf((long) (Math.random() * p)); 12 | i = BigInteger.valueOf(1 + (long) (Math.random() * (p - 1L))); 13 | } 14 | 15 | public int hashKey(Integer key, int tableSize) { 16 | return i.multiply(BigInteger.valueOf(key)).add(j) 17 | .mod(BigInteger.valueOf(p)) 18 | .mod(BigInteger.valueOf(tableSize)) 19 | .intValue(); 20 | } 21 | 22 | public static void main(String[] args) { 23 | UniversalHashing universalHashing = new UniversalHashing(); 24 | System.out.println(universalHashing.hashKey(337481990, 1000)); 25 | System.out.println(universalHashing.hashKey(116241990, 1000)); 26 | System.out.println(universalHashing.hashKey(983611990, 1000)); 27 | System.out.println(universalHashing.hashKey(201031990, 1000)); 28 | 29 | universalHashing = new UniversalHashing(); 30 | System.out.println(universalHashing.hashKey(337481990, 1000)); 31 | System.out.println(universalHashing.hashKey(116241990, 1000)); 32 | System.out.println(universalHashing.hashKey(983611990, 1000)); 33 | System.out.println(universalHashing.hashKey(201031990, 1000)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson4/activity/coinchange/CoinChange.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson4.activity.coinchange; 2 | 3 | public class CoinChange { 4 | public Integer ways(int N, int[] coins) { return null; } 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson4/activity/coinchange/solution/CoinChange.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson4.activity.coinchange.solution; 2 | 3 | public class CoinChange { 4 | public Integer ways(int N, int[] coins) { 5 | int[][] dp = new int[N + 1][coins.length + 1]; 6 | for (int j = 0; j <= coins.length; j++) 7 | dp[0][j] = 1; 8 | for (int j = 1; j <= coins.length; j++) { 9 | for (int i = 1; i <= N; i++) { 10 | dp[i][j] = dp[i][j - 1]; 11 | if (i - coins[j - 1] >= 0) 12 | dp[i][j] += dp[i - coins[j - 1]][j]; 13 | } 14 | } 15 | return dp[N][coins.length]; 16 | } 17 | 18 | public static void main(String[] args) { 19 | int[] coins = {1, 2, 3}; 20 | CoinChange cc = new CoinChange(); 21 | System.out.println(cc.ways(4, coins)); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson4/activity/egyptian/EgyptianFractions.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson4.activity.egyptian; 2 | 3 | import java.util.List; 4 | 5 | public class EgyptianFractions { 6 | public List build(Long numerator, Long denominator) { return null; } 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson4/activity/egyptian/solution/EgyptianFractions.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson4.activity.egyptian.solution; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class EgyptianFractions { 7 | public List build(Long numerator, Long denominator) { 8 | if (numerator == 0 || denominator == 0) 9 | return new ArrayList<>(); 10 | 11 | if (denominator % numerator == 0) { 12 | List l = new ArrayList<>(); 13 | l.add(denominator / numerator); 14 | return l; 15 | } 16 | 17 | Long n = denominator / numerator + 1; 18 | List r = build(numerator * n - denominator, denominator * n); 19 | r.add(0, n); 20 | return r; 21 | } 22 | 23 | public static void printResult(Long numerator, Long denominator) { 24 | EgyptianFractions fractions = new EgyptianFractions(); 25 | List ds = fractions.build(numerator, denominator); 26 | System.out.print(numerator + "/" + denominator + " ="); 27 | for (int i = 0; i < ds.size(); i++) { 28 | System.out.print(" 1/" + ds.get(i)); 29 | if (i + 1 < ds.size()) 30 | System.out.print(" +"); 31 | else 32 | System.out.print("\n"); 33 | } 34 | } 35 | 36 | public static void main(String[] args) { 37 | printResult(2l, 3l); 38 | printResult(6l, 14l); 39 | printResult(12l, 13l); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson4/activity/maxsubarray/MaximumSubarray.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson4.activity.maxsubarray; 2 | 3 | public class MaximumSubarray { 4 | public Integer maxSubarray(int[] a) { return null; } 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson4/activity/maxsubarray/solution/MaximumSubarray.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson4.activity.maxsubarray.solution; 2 | 3 | public class MaximumSubarray { 4 | public int maxSubarrayCross(int[] a, int l, int m, int h) { 5 | int leftSum = Integer.MIN_VALUE; 6 | int sum = 0; 7 | for (int i = m; i >= l; i--) { 8 | sum += a[i]; 9 | if (sum > leftSum) 10 | leftSum = sum; 11 | } 12 | int rightSum = Integer.MIN_VALUE; 13 | sum = 0; 14 | for (int i = m + 1; i <= h; i++) { 15 | sum += a[i]; 16 | if (sum > rightSum) 17 | rightSum = sum; 18 | } 19 | return leftSum + rightSum; 20 | } 21 | 22 | public int maxSubarrayAux(int[] a, int l, int h) { 23 | if (l == h) 24 | return a[l]; 25 | else { 26 | int m = (l + h) / 2; 27 | int bl = maxSubarrayAux(a, l, m); 28 | int br = maxSubarrayAux(a, m + 1, h); 29 | int bc = maxSubarrayCross(a, l, m, h); 30 | int best = Math.max(Math.max(bl, br), bc); 31 | return best; 32 | } 33 | } 34 | 35 | public Integer maxSubarray(int[] a) { 36 | return maxSubarrayAux(a, 0, a.length - 1); 37 | } 38 | 39 | public static void main(String[] args) { 40 | int[] a = {13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7}; 41 | MaximumSubarray maxSubarray = new MaximumSubarray(); 42 | System.out.println("Maximum subarray = " + maxSubarray.maxSubarray(a)); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson4/activityselection/ActivitySelection.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson4.activityselection; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.List; 6 | 7 | public class ActivitySelection { 8 | static class Activity { 9 | public int id; 10 | public int start; 11 | public int finish; 12 | 13 | public Activity(int i, int s, int f) { 14 | id = i; 15 | start = s; 16 | finish = f; 17 | } 18 | } 19 | 20 | public List select(List activities) { 21 | List selected = new ArrayList<>(); 22 | List sortedActivities = new ArrayList<>(activities); 23 | Collections.sort(sortedActivities, (o1, o2) -> Integer.signum(o1.finish - o2.finish)); 24 | if (sortedActivities.size() > 0) 25 | selected.add(sortedActivities.get(0)); 26 | for (int i = 1; i < sortedActivities.size(); i++) 27 | if (sortedActivities.get(i).start >= selected.get(selected.size() - 1).finish) 28 | selected.add(sortedActivities.get(i)); 29 | return selected; 30 | } 31 | 32 | public static void main(String[] args) { 33 | List activities = new ArrayList<>(); 34 | activities.add(new Activity(1, 600, 720)); 35 | activities.add(new Activity(2, 1200, 1380)); 36 | activities.add(new Activity(3, 1020, 1140)); 37 | activities.add(new Activity(4, 600, 630)); 38 | activities.add(new Activity(5, 1140, 1230)); 39 | activities.add(new Activity(6, 1290, 1380)); 40 | activities.add(new Activity(7, 750, 810)); 41 | activities.add(new Activity(8, 1200, 1320)); 42 | activities.add(new Activity(9, 1020, 1170)); 43 | activities.add(new Activity(10, 960, 1140)); 44 | activities.add(new Activity(11, 900, 1020)); 45 | 46 | ActivitySelection selection = new ActivitySelection(); 47 | List selected = selection.select(activities); 48 | for (int i = 0; i < selected.size(); i++) { 49 | System.out.print(selected.get(i).id); 50 | if (i + 1 < selected.size()) 51 | System.out.print(", "); 52 | else 53 | System.out.print("\n"); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson4/huffman/Huffman.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson4.huffman; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import java.util.PriorityQueue; 6 | 7 | public class Huffman { 8 | static class Node { 9 | public Node left; 10 | public Node right; 11 | public Integer frequency; 12 | public Character character; 13 | 14 | public Node() { 15 | left = right = null; 16 | frequency = 0; 17 | character = null; 18 | } 19 | } 20 | 21 | Node build(Map frequencies) { 22 | int N = frequencies.size(); 23 | PriorityQueue pq = new PriorityQueue<>(N, 24 | (o1, o2) -> Integer.signum(o1.frequency - o2.frequency)); 25 | for (Map.Entry entry : frequencies.entrySet()) { 26 | Node n = new Node(); 27 | n.character = entry.getKey(); 28 | n.frequency = entry.getValue(); 29 | pq.add(n); 30 | } 31 | for (int i = 0; i < N - 1; i++) { 32 | Node n = new Node(); 33 | n.left = pq.remove(); 34 | n.right = pq.remove(); 35 | n.frequency = n.left.frequency + n.right.frequency; 36 | pq.add(n); 37 | } 38 | return pq.remove(); 39 | } 40 | 41 | public static String decode(String encoding, Node current, Node code, String s) { 42 | if (current.character != null) 43 | return decode(encoding, code, code, s + current.character); 44 | if (encoding.isEmpty()) 45 | return s; 46 | if (encoding.charAt(0) == '0') 47 | return decode(encoding.substring(1), current.left, code, s); 48 | return decode(encoding.substring(1), current.right, code, s); 49 | } 50 | 51 | public static String decode(String encoding, Node code) { 52 | return decode(encoding, code, code, ""); 53 | } 54 | 55 | public static void main(String[] args) { 56 | Map frequencies = new HashMap<>(); 57 | frequencies.put('a', 45000); 58 | frequencies.put('b', 13000); 59 | frequencies.put('c', 12000); 60 | frequencies.put('d', 16000); 61 | frequencies.put('e', 9000); 62 | frequencies.put('f', 5000); 63 | 64 | Huffman huffman = new Huffman(); 65 | Node code = huffman.build(frequencies); 66 | 67 | System.out.println(Huffman.decode("001011101", code)); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson4/knapsack/Knapsack.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson4.knapsack; 2 | 3 | public class Knapsack { 4 | public int recursiveAux(int W, int weights[], int values[], int n) { 5 | if (n == 0 || W == 0) 6 | return 0; 7 | if (weights[n - 1] > W) 8 | return recursiveAux(W, weights, values, n - 1); 9 | return Math.max( 10 | values[n - 1] + 11 | recursiveAux(W - weights[n - 1], weights, values, n - 1), 12 | recursiveAux(W, weights, values, n - 1)); 13 | } 14 | 15 | public int recursive(int W, int weights[], int values[]) { 16 | return recursiveAux(W, weights, values, weights.length); 17 | } 18 | 19 | public int topDownWithMemoizationAux(int W, int weights[], int values[], int n, int[][] memo) { 20 | if (n == 0 || W == 0) 21 | return 0; 22 | if (memo[n][W] == -1) { 23 | if (weights[n - 1] > W) 24 | memo[n][W] = topDownWithMemoizationAux(W, weights, values, n - 1, memo); 25 | else 26 | memo[n][W] = Math.max( 27 | values[n - 1] + topDownWithMemoizationAux(W - weights[n - 1], weights, values, n - 1, memo), 28 | topDownWithMemoizationAux(W, weights, values, n - 1, memo)); 29 | } 30 | return memo[n][W]; 31 | } 32 | 33 | public int topDownWithMemoization(int W, int weights[], int values[]) { 34 | int[][] memo = new int[weights.length + 1][W + 1]; 35 | for (int i = 0; i <= weights.length; i++) 36 | for (int j = 0; j <= W; j++) 37 | memo[i][j] = -1; 38 | return topDownWithMemoizationAux(W, weights, values, weights.length, memo); 39 | } 40 | 41 | public int bottomUp(int weight, int weights[], int values[]) { 42 | int[][] dp = new int[values.length + 1][weight + 1]; 43 | for (int i = 0; i <= values.length; i++) { 44 | for (int w = 0; w <= weight; w++) { 45 | if (i == 0 || w == 0) 46 | dp[i][w] = 0; 47 | else if (weights[i - 1] <= w) 48 | dp[i][w] = Math.max(values[i - 1] + dp[i - 1][w - weights[i - 1]], dp[i - 1][w]); 49 | else 50 | dp[i][w] = dp[i - 1][w]; 51 | } 52 | } 53 | return dp[values.length][weight]; 54 | } 55 | 56 | public static void main(String[] args) { 57 | int[] weights = {1, 1, 1}; 58 | int[] values = {10, 20, 30}; 59 | Knapsack k = new Knapsack(); 60 | System.out.println("Maximum value = " + k.recursive(2, weights, values)); 61 | System.out.println("Maximum value = " + k.topDownWithMemoization(2, weights, values)); 62 | System.out.println("Maximum value = " + k.bottomUp(2, weights, values)); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson4/lcs/LongestCommonSubsequence.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson4.lcs; 2 | 3 | public class LongestCommonSubsequence { 4 | public int length(String x, String y) { 5 | int m = x.length(); 6 | int n = y.length(); 7 | int[][] c = new int[m + 1][n + 1]; 8 | for (int i = 1; i <= m; i++) { 9 | for (int j = 1; j <= n; j++) { 10 | if (x.charAt(i - 1) == y.charAt(j - 1)) 11 | c[i][j] = c[i - 1][j - 1] + 1; 12 | else 13 | c[i][j] = Math.max(c[i - 1][j], c[i][j - 1]); 14 | } 15 | } 16 | return c[m][n]; 17 | } 18 | 19 | public static void main(String[] args) { 20 | String s1 = "ACCGGTCGAGTGCGCGGAAGCCGGCCGAA"; 21 | String s2 = "GTCGTTCGGAATGCCGTTGCTCTGTAAA"; 22 | LongestCommonSubsequence lcs = new LongestCommonSubsequence(); 23 | System.out.println("Length of longest common subsequence = " + lcs.length(s1, s2)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson4/points/ClosestPairOfPoints.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson4.points; 2 | 3 | import java.util.*; 4 | 5 | public class ClosestPairOfPoints { 6 | static class Point { 7 | int x; 8 | int y; 9 | 10 | public Point(int _x, int _y) { 11 | x = _x; 12 | y = _y; 13 | } 14 | } 15 | 16 | static class PointPair { 17 | Point p; 18 | Point q; 19 | 20 | public PointPair(Point _p, Point _q) { 21 | p = _p; 22 | q = _q; 23 | } 24 | 25 | public double distance() { 26 | return Math.sqrt(Math.pow(p.x - q.x, 2) + Math.pow(p.y - q.y, 2)); 27 | } 28 | } 29 | 30 | PointPair bruteForce(List points) { 31 | PointPair best = new PointPair(points.get(0), points.get(1)); 32 | for (int i = 2; i < points.size(); i++) { 33 | for (int j = i - 1; j >= 0; j--) { 34 | PointPair candidate = new PointPair(points.get(i), points.get(j)); 35 | if (candidate.distance() < best.distance()) 36 | best = candidate; 37 | } 38 | } 39 | return best; 40 | } 41 | 42 | PointPair bestWithStrip(List points, PointPair bestSoFar) { 43 | PointPair best = bestSoFar; 44 | List sortedPoints = new ArrayList<>(points); 45 | Collections.sort(sortedPoints, (o1, o2) -> Integer.signum(o1.y - o2.y)); 46 | 47 | for (int i = 0; i < points.size(); i++) { 48 | for (int j = i + 1; j < points.size() && 49 | (points.get(j).y - points.get(i).y) < best.distance(); j++) { 50 | PointPair candidate = new PointPair(points.get(i), points.get(j)); 51 | if (candidate.distance() < best.distance()) 52 | best = candidate; 53 | } 54 | } 55 | 56 | return best; 57 | } 58 | 59 | PointPair divideAndConquerAux(List points) { 60 | int N = points.size(); 61 | if (N <= 3) 62 | return bruteForce(points); 63 | 64 | int mid = N / 2; 65 | Point midPoint = points.get(mid); 66 | 67 | PointPair bl = divideAndConquerAux(points.subList(0, mid)); 68 | PointPair br = divideAndConquerAux(points.subList(mid, N)); 69 | 70 | PointPair bestSoFar = bl; 71 | if (br.distance() < bl.distance()) 72 | bestSoFar = br; 73 | 74 | List strip = new ArrayList<>(); 75 | for (int i = 0; i < N; i++) { 76 | if (Math.abs(points.get(i).x - midPoint.x) < bestSoFar.distance()) 77 | strip.add(points.get(i)); 78 | } 79 | 80 | return bestWithStrip(strip, bestSoFar); 81 | } 82 | 83 | PointPair divideAndConquer(List points) { 84 | List sortedPoints = new ArrayList<>(points); 85 | Collections.sort(sortedPoints, (o1, o2) -> Integer.signum(o1.x - o2.x)); 86 | return divideAndConquerAux(sortedPoints); 87 | } 88 | 89 | public static void main(String[] args) { 90 | List points = new ArrayList<>(); 91 | points.add(new Point(2, 3)); 92 | points.add(new Point(12, 30)); 93 | points.add(new Point(40, 50)); 94 | points.add(new Point(5, 1)); 95 | points.add(new Point(12, 10)); 96 | points.add(new Point(3, 4)); 97 | 98 | ClosestPairOfPoints closest = new ClosestPairOfPoints(); 99 | PointPair best1 = closest.bruteForce(points); 100 | PointPair best2 = closest.divideAndConquer(points); 101 | 102 | System.out.println("Distance = " + best1.distance()); 103 | System.out.println("Distance = " + best2.distance()); 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson5/activity/badcharacterrule/BadCharacterRule.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson5.activity.badcharacterrule; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class BadCharacterRule { 7 | public List match(String P, String T) { 8 | int n = T.length(); 9 | int m = P.length(); 10 | 11 | int e = 256; 12 | int left[][] = new int[m][e]; 13 | // Populate left[][] with the correct values 14 | 15 | List shifts = new ArrayList<>(); 16 | int skip; 17 | for (int i = 0; i < n - m + 1; i += skip) { 18 | skip = 0; 19 | for (int j = m - 1; j >= 0; j--) { 20 | if (P.charAt(j) != T.charAt(i + j)) { 21 | skip = Math.max(1, j - left[j][T.charAt(i + j)]); 22 | break; 23 | } 24 | } 25 | if (skip == 0) { 26 | shifts.add(i); 27 | skip = 1; 28 | } 29 | } 30 | return shifts; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson5/activity/badcharacterrule/solution/BadCharacterRule.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson5.activity.badcharacterrule.solution; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class BadCharacterRule { 7 | public List match(String P, String T) { 8 | int n = T.length(); 9 | int m = P.length(); 10 | 11 | int e = 256; 12 | int left[][] = new int[m][e]; 13 | for (int i = 0; i < m; i++) 14 | for (int j = 0; j < e; j++) 15 | left[i][j] = -1; 16 | for (int i = 0; i < m; i++) { 17 | if (i != 0) 18 | for (int j = 0; j < e; j++) 19 | left[i][j] = left[i - 1][j]; 20 | left[i][P.charAt(i)] = i; 21 | } 22 | 23 | List shifts = new ArrayList<>(); 24 | int skip; 25 | for (int i = 0; i < n - m + 1; i += skip) { 26 | skip = 0; 27 | for (int j = m - 1; j >= 0; j--) { 28 | if (P.charAt(j) != T.charAt(i + j)) { 29 | skip = Math.max(1, j - left[j][T.charAt(i + j)]); 30 | break; 31 | } 32 | } 33 | if (skip == 0) { 34 | shifts.add(i); 35 | skip = 1; 36 | } 37 | } 38 | return shifts; 39 | } 40 | 41 | public static void main(String[] args) { 42 | BadCharacterRule bcr = new BadCharacterRule(); 43 | List matches = bcr.match("rabrabracad", "abacadabrabracabracadabrabrabracad"); 44 | for (Integer i : matches) 45 | System.out.println(i); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson5/activity/boyermoore/BoyerMoore.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson5.activity.boyermoore; 2 | 3 | import java.util.List; 4 | 5 | public class BoyerMoore { 6 | public List match(String P, String T) { return null; } 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson5/activity/boyermoore/solution/BoyerMoore.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson5.activity.boyermoore.solution; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class BoyerMoore { 7 | public List match(String P, String T) { 8 | int n = T.length(); 9 | int m = P.length(); 10 | 11 | int e = 256; 12 | int left[][] = new int[m][e]; 13 | for (int i = 0; i < m; i++) 14 | for (int j = 0; j < e; j++) 15 | left[i][j] = -1; 16 | for (int i = 0; i < m; i++) { 17 | if (i != 0) 18 | for (int j = 0; j < e; j++) 19 | left[i][j] = left[i - 1][j]; 20 | left[i][P.charAt(i)] = i; 21 | } 22 | 23 | int i = m, j = m + 1; 24 | int[] f = new int[m + 1]; 25 | int[] s = new int[m + 1]; 26 | f[i] = j; 27 | while (i > 0) { 28 | while (j <= m && P.charAt(i - 1) != P.charAt(j - 1)) { 29 | if (s[j] == 0) 30 | s[j] = j - i; 31 | j = f[j]; 32 | } 33 | i--; j--; 34 | f[i] = j; 35 | } 36 | 37 | j = f[0]; 38 | for (i = 0; i <= m; i++) { 39 | if (s[i] == 0) 40 | s[i] = j; 41 | if (i == j) 42 | j = f[j]; 43 | } 44 | 45 | List shifts = new ArrayList<>(); 46 | int skip; 47 | for (i = 0; i < n - m + 1; i += skip) { 48 | skip = 0; 49 | boolean hasMatch = true; 50 | for (j = m - 1; j >= 0; j--) { 51 | if (P.charAt(j) != T.charAt(i + j)) { 52 | hasMatch = false; 53 | skip = Math.max(s[j + 1], j - left[j][T.charAt(i + j)]); 54 | break; 55 | } 56 | } 57 | if (hasMatch) { 58 | shifts.add(i); 59 | skip = s[0]; 60 | } 61 | } 62 | return shifts; 63 | } 64 | 65 | public static void main(String[] args) { 66 | BoyerMoore bm = new BoyerMoore(); 67 | List matches = bm.match("rabrabracad", "abacadabrabracabracadabrabrabracad"); 68 | for (Integer i : matches) 69 | System.out.println(i); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson5/activity/naivestringmatching/NaiveStringMatching.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson5.activity.naivestringmatching; 2 | 3 | import java.util.List; 4 | 5 | public class NaiveStringMatching { 6 | public List match(String P, String T) { return null; } 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson5/activity/naivestringmatching/solution/NaiveStringMatching.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson5.activity.naivestringmatching.solution; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class NaiveStringMatching { 7 | public List match(String P, String T) { 8 | int n = T.length(); 9 | int m = P.length(); 10 | List shifts = new ArrayList<>(); 11 | for (int i = 0; i < n - m + 1; i++) { 12 | boolean hasMatch = true; 13 | for (int j = 0; j < m; j++) { 14 | if (P.charAt(j) != T.charAt(i + j)) { 15 | hasMatch = false; 16 | break; 17 | } 18 | } 19 | if (hasMatch) 20 | shifts.add(i); 21 | } 22 | return shifts; 23 | } 24 | 25 | public static void main(String[] args) { 26 | NaiveStringMatching nsm = new NaiveStringMatching(); 27 | List matches = nsm.match("aab", "acaabc"); 28 | for (Integer i : matches) 29 | System.out.println(i); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson5/goodsuffixrule/GoodSuffixRule.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson5.goodsuffixrule; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class GoodSuffixRule { 7 | public List match(String P, String T) { 8 | int n = T.length(); 9 | int m = P.length(); 10 | int i = m, j = m + 1; 11 | int[] f = new int[m + 1]; 12 | int[] s = new int[m + 1]; 13 | f[i] = j; 14 | while (i > 0) { 15 | while (j <= m && P.charAt(i - 1) != P.charAt(j - 1)) { 16 | if (s[j] == 0) 17 | s[j] = j - i; 18 | j = f[j]; 19 | } 20 | i--; j--; 21 | f[i] = j; 22 | } 23 | 24 | j = f[0]; 25 | for (i = 0; i <= m; i++) { 26 | if (s[i] == 0) 27 | s[i] = j; 28 | if (i == j) 29 | j = f[j]; 30 | } 31 | 32 | List shifts = new ArrayList<>(); 33 | int skip; 34 | for (i = 0; i < n - m + 1; i += skip) { 35 | boolean hasMatch = true; 36 | skip = 0; 37 | for (j = m - 1; j >= 0; j--) { 38 | if (P.charAt(j) != T.charAt(i + j)) { 39 | skip = s[j + 1]; 40 | hasMatch = false; 41 | break; 42 | } 43 | } 44 | if (hasMatch) { 45 | shifts.add(i); 46 | skip = s[0]; 47 | } 48 | } 49 | return shifts; 50 | } 51 | 52 | public static void main(String [] args) { 53 | GoodSuffixRule gsr = new GoodSuffixRule(); 54 | List matches = gsr.match("rabrabracad", "abacadabrabracabracadabrabrabracad"); 55 | for (Integer i : matches) 56 | System.out.println(i); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson5/rabinkarp/RabinKarp.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson5.rabinkarp; 2 | 3 | import java.math.BigInteger; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | import java.util.Random; 7 | 8 | public class RabinKarp { 9 | public List match(String P, String T) { 10 | // Good enough for ascii characters. 11 | int d = 256; 12 | int m = P.length(); 13 | int n = T.length(); 14 | long q = BigInteger.probablePrime(31, new Random()).longValue(); 15 | 16 | // Precompute d^(m-1) % q for use when removing leading digit 17 | long dm = 1; 18 | for (int i = 1; i <= m - 1; i++) 19 | dm = (d * dm) % q; 20 | 21 | // Precompute p and t0 22 | long ph = 0; 23 | long th = 0; 24 | for (int i = 0; i < m; i++) { 25 | ph = (d * ph + P.charAt(i)) % q; 26 | th = (d * th + T.charAt(i)) % q; 27 | } 28 | 29 | List shifts = new ArrayList<>(); 30 | for (int i = 0; i < n - m + 1; i++) { 31 | if (ph == th) { 32 | boolean hasMatch = true; 33 | for (int j = 0; j < m; j++) { 34 | if (P.charAt(j) != T.charAt(i + j)) { 35 | hasMatch = false; 36 | break; 37 | } 38 | } 39 | if (hasMatch) 40 | shifts.add(i); 41 | } 42 | 43 | if (i + m < n) { 44 | th = (th + q - dm * T.charAt(i) % q) % q; 45 | th = (th * d + T.charAt(i + m)) % q; 46 | } 47 | } 48 | return shifts; 49 | } 50 | 51 | public static void main(String[] args) { 52 | RabinKarp rk = new RabinKarp(); 53 | List matches = rk.match("rabrabracad", "abacadabrabracabracadabrabrabracad"); 54 | for (Integer i : matches) 55 | System.out.println(i); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson6/activity/floydwarshall/FloydWarshall.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson6.activity.floydwarshall; 2 | 3 | import java.util.List; 4 | 5 | public class FloydWarshall { 6 | int[][] adj; 7 | int[][] path; 8 | 9 | public FloydWarshall(int nodes) { 10 | this.adj = new int[nodes][nodes]; 11 | this.path = new int[nodes][nodes]; 12 | for (int i = 0; i < adj.length; i++) { 13 | for (int j = 0; j < adj[i].length; j++) { 14 | if (i == j) { 15 | this.adj[i][j] = 0; 16 | this.path[i][j] = i; 17 | } else { 18 | this.adj[i][j] = Integer.MAX_VALUE; 19 | this.path[i][j] = -1; 20 | } 21 | } 22 | } 23 | } 24 | 25 | public void addEdge(int u, int v, int weight) { 26 | if (weight < adj[u][v]) { 27 | adj[u][v] = weight; 28 | path[u][v] = u; 29 | } 30 | } 31 | 32 | public List path(int u, int v) { return null; } 33 | 34 | public void run() { } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson6/activity/floydwarshall/solution/FloydWarshall.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson6.activity.floydwarshall.solution; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class FloydWarshall { 7 | int[][] adj; 8 | int[][] path; 9 | 10 | public FloydWarshall(int nodes) { 11 | this.adj = new int[nodes][nodes]; 12 | this.path = new int[nodes][nodes]; 13 | for (int i = 0; i < adj.length; i++) { 14 | for (int j = 0; j < adj[i].length; j++) { 15 | if (i == j) { 16 | this.adj[i][j] = 0; 17 | this.path[i][j] = i; 18 | } else { 19 | this.adj[i][j] = Integer.MAX_VALUE; 20 | this.path[i][j] = -1; 21 | } 22 | } 23 | } 24 | } 25 | 26 | public void addEdge(int u, int v, int weight) { 27 | if (weight < adj[u][v]) { 28 | adj[u][v] = weight; 29 | path[u][v] = u; 30 | } 31 | } 32 | 33 | public List path(int u, int v) { 34 | List res = new ArrayList<>(); 35 | if (path[u][v] == -1) 36 | return res; 37 | int i = v; 38 | while (u != i) { 39 | res.add(0, i); 40 | i = path[u][i]; 41 | } 42 | res.add(0, u); 43 | return res; 44 | } 45 | 46 | public void run() { 47 | for (int k = 0; k < adj.length; k++) { 48 | for (int i = 0; i < adj.length; i++) { 49 | if (adj[i][k] >= Integer.MAX_VALUE) 50 | continue; 51 | for (int j = 0; j < adj.length; j++) { 52 | if (adj[k][j] >= Integer.MAX_VALUE) 53 | continue; 54 | if (adj[i][k] + adj[k][j] < adj[i][j]) { 55 | adj[i][j] = adj[i][k] + adj[k][j]; 56 | path[i][j] = path[k][j]; 57 | } 58 | } 59 | } 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson6/activity/maze/Maze.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson6.activity.maze; 2 | 3 | public class Maze { 4 | private int H; 5 | private int W; 6 | private int exitI; 7 | private int exitJ; 8 | private String[] maze; 9 | 10 | public Maze(String[] maze) { 11 | this.maze = maze; 12 | this.H = maze.length; 13 | this.W = maze[0].length(); 14 | for (int i = 0; i < W; i++) { 15 | if (maze[0].charAt(i) == '.') { 16 | this.exitI = 0; 17 | this.exitJ = i; 18 | return; 19 | } 20 | if (maze[H - 1].charAt(i) == '.') { 21 | this.exitI = H - 1; 22 | this.exitJ = i; 23 | return; 24 | } 25 | } 26 | for (int i = 1; i < H - 1; i++) { 27 | if (maze[i].charAt(0) == '.') { 28 | this.exitI = i; 29 | this.exitJ = 0; 30 | return; 31 | } 32 | if (maze[i].charAt(W - 1) == '.') { 33 | this.exitI = i; 34 | this.exitJ = W - 1; 35 | return; 36 | } 37 | } 38 | } 39 | 40 | public int distToExit(int i, int j) { 41 | return -1; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson6/activity/maze/solution/Maze.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson6.activity.maze.solution; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Queue; 5 | 6 | public class Maze { 7 | private int H; 8 | private int W; 9 | private int exitI; 10 | private int exitJ; 11 | private String[] maze; 12 | 13 | public Maze(String[] maze) { 14 | this.maze = maze; 15 | this.H = maze.length; 16 | this.W = maze[0].length(); 17 | for (int i = 0; i < W; i++) { 18 | if (maze[0].charAt(i) == '.') { 19 | this.exitI = 0; 20 | this.exitJ = i; 21 | return; 22 | } 23 | if (maze[H - 1].charAt(i) == '.') { 24 | this.exitI = H - 1; 25 | this.exitJ = i; 26 | return; 27 | } 28 | } 29 | for (int i = 1; i < H - 1; i++) { 30 | if (maze[i].charAt(0) == '.') { 31 | this.exitI = i; 32 | this.exitJ = 0; 33 | return; 34 | } 35 | if (maze[i].charAt(W - 1) == '.') { 36 | this.exitI = i; 37 | this.exitJ = W - 1; 38 | return; 39 | } 40 | } 41 | } 42 | 43 | private class Pos { 44 | int i; 45 | int j; 46 | public Pos(int i, int j) { 47 | this.i = i; 48 | this.j = j; 49 | } 50 | } 51 | 52 | public int distToExit(int i, int j) { 53 | int[][] dist = new int[H][W]; 54 | int[][] directions = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; 55 | 56 | for (int h = 0; h < H; h++) { 57 | for (int w = 0; w < W; w++) { 58 | dist[h][w] = -1; 59 | } 60 | } 61 | 62 | Queue q = new LinkedList<>(); 63 | dist[i][j] = 0; 64 | q.add(new Pos(i, j)); 65 | while (!q.isEmpty()) { 66 | Pos current = q.remove(); 67 | if (current.i == this.exitI && current.j == this.exitJ) 68 | return dist[current.i][current.j]; 69 | for (int d = 0; d < directions.length; d++) { 70 | int ni = current.i + directions[d][0]; 71 | int nj = current.j + directions[d][1]; 72 | if (this.maze[ni].charAt(nj) == '.' && dist[ni][nj] == -1) { 73 | dist[ni][nj] = dist[current.i][current.j] + 1; 74 | q.add(new Pos(ni, nj)); 75 | } 76 | } 77 | } 78 | return -1; 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson6/activity/weightedundirected/AdjacencyMatrixWeightedUndirected.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson6.activity.weightedundirected; 2 | 3 | public class AdjacencyMatrixWeightedUndirected { 4 | int[][] adj; 5 | 6 | public AdjacencyMatrixWeightedUndirected(int nodes) { 7 | this.adj = new int[nodes][nodes]; 8 | } 9 | 10 | public void addEdge(int u, int v, int weight) { } 11 | 12 | public int edgeWeight(int u, int v) { return 0; } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson6/activity/weightedundirected/solution/AdjacencyMatrixWeightedUndirected.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson6.activity.weightedundirected.solution; 2 | 3 | public class AdjacencyMatrixWeightedUndirected { 4 | int[][] adj; 5 | 6 | public AdjacencyMatrixWeightedUndirected(int nodes) { 7 | this.adj = new int[nodes][nodes]; 8 | } 9 | 10 | public void addEdge(int u, int v, int weight) { 11 | this.adj[u][v] = this.adj[v][u] = weight; 12 | } 13 | 14 | public int edgeWeight(int u, int v) { 15 | return this.adj[u][v]; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson6/bfs/Graph.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson6.bfs; 2 | 3 | import java.util.ArrayList; 4 | import java.util.LinkedList; 5 | import java.util.Queue; 6 | 7 | public class Graph { 8 | ArrayList adj[]; 9 | 10 | public Graph(int nodes) { 11 | this.adj = new ArrayList[nodes]; 12 | for (int i = 0; i < nodes; i++) { 13 | this.adj[i] = new ArrayList<>(); 14 | } 15 | } 16 | 17 | public void addEdge(int u, int v) { 18 | this.adj[u].add(v); 19 | } 20 | 21 | public int[] bfs(int start) { 22 | int[] parent = new int[this.adj.length]; 23 | boolean[] visited = new boolean[this.adj.length]; 24 | 25 | for (int i = 0; i < this.adj.length; i++) { 26 | parent[i] = -1; 27 | visited[i] = false; 28 | } 29 | 30 | visited[start] = true; 31 | Queue q = new LinkedList<>(); 32 | q.add(start); 33 | while (!q.isEmpty()) { 34 | int current = q.remove(); 35 | for (int i = 0; i < this.adj[current].size(); i++) { 36 | int next = this.adj[current].get(i); 37 | if (!visited[next]) { 38 | visited[next] = true; 39 | parent[next] = current; 40 | q.add(next); 41 | } 42 | } 43 | } 44 | return parent; 45 | } 46 | 47 | public static void main(String [] args) { 48 | Graph g = new Graph(6); 49 | g.addEdge(0, 1); 50 | g.addEdge(0, 3); 51 | g.addEdge(1, 4); 52 | g.addEdge(2, 4); 53 | g.addEdge(2, 5); 54 | g.addEdge(3, 1); 55 | g.addEdge(4, 3); 56 | g.addEdge(5, 5); 57 | int[] parent = g.bfs(2); 58 | for (int i = 0; i < 6; i++) { 59 | System.out.print("Path from 2 to " + i + ":"); 60 | if (parent[i] == -1 && i != 2) 61 | System.out.println(" None"); 62 | else { 63 | String path = ""; 64 | int j = i; 65 | while (j != -1) { 66 | path = (" " + j) + path; 67 | j = parent[j]; 68 | } 69 | System.out.println(path); 70 | } 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson6/dfs/Graph.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson6.dfs; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class Graph { 6 | ArrayList adj[]; 7 | 8 | public Graph(int nodes) { 9 | this.adj = new ArrayList[nodes]; 10 | for (int i = 0; i < nodes; i++) { 11 | this.adj[i] = new ArrayList<>(); 12 | } 13 | } 14 | 15 | public void addEdge(int u, int v) { 16 | this.adj[u].add(v); 17 | } 18 | 19 | public int[] dfs() { 20 | boolean[] visited = new boolean[adj.length]; 21 | int[] parent = new int[adj.length]; 22 | for (int i = 0; i < adj.length; i++) { 23 | visited[i] = false; 24 | parent[i] = -1; 25 | } 26 | for (int i = 0; i < adj.length; i++) { 27 | if (!visited[i]) 28 | dfsVisit(i, visited, parent); 29 | } 30 | return parent; 31 | } 32 | 33 | public void dfsVisit(int u, boolean[] visited, int[] parent) { 34 | visited[u] = true; 35 | for (int i = 0; i < adj[u].size(); i++) { 36 | int next = adj[u].get(i); 37 | if (!visited[next]) { 38 | parent[next] = u; 39 | dfsVisit(next, visited, parent); 40 | } 41 | } 42 | } 43 | 44 | public static void main(String[] args) { 45 | Graph g = new Graph(6); 46 | g.addEdge(0, 1); 47 | g.addEdge(0, 3); 48 | g.addEdge(1, 4); 49 | g.addEdge(2, 4); 50 | g.addEdge(2, 5); 51 | g.addEdge(3, 1); 52 | g.addEdge(4, 3); 53 | g.addEdge(5, 5); 54 | int[] p = g.dfs(); 55 | for (int i = 0; i < 6; i++) { 56 | System.out.println("Parent of " + i + " in DFS forest is " + p[i]); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson6/dijkstra/Dijkstra.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson6.dijkstra; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashSet; 5 | import java.util.List; 6 | import java.util.Set; 7 | 8 | public class Dijkstra { 9 | private class Edge { 10 | int v; 11 | int weight; 12 | 13 | Edge(int v, int weight) { 14 | this.v = v; 15 | this.weight = weight; 16 | } 17 | } 18 | 19 | private class Vertex { 20 | int u; 21 | int distance; 22 | 23 | Vertex(int u, int distance) { 24 | this.distance = distance; 25 | this.u = u; 26 | } 27 | } 28 | 29 | public class Path { 30 | int from; 31 | int to; 32 | int distance; 33 | List path; 34 | 35 | Path(int from, int to, int distance, List path) { 36 | this.from = from; 37 | this.to = to; 38 | this.distance = distance; 39 | this.path = path; 40 | } 41 | } 42 | 43 | List adj[]; 44 | 45 | public Dijkstra(int nodes) { 46 | this.adj = new ArrayList[nodes]; 47 | for (int i = 0; i < nodes; i++) 48 | this.adj[i] = new ArrayList<>(); 49 | } 50 | 51 | public void addEdge(int u, int v, int weight) { 52 | adj[u].add(new Edge(v, weight)); 53 | } 54 | 55 | private Vertex getBestEstimate(Set vertices) { 56 | Vertex best = null; 57 | for (Vertex v : vertices) { 58 | if (best == null || v.distance < best.distance) 59 | best = v; 60 | } 61 | return best; 62 | } 63 | 64 | public Path[] dijkstra(int source) { 65 | Set notVisited = new HashSet<>(); 66 | Set visited = new HashSet<>(); 67 | Vertex vertices[] = new Vertex[adj.length]; 68 | int parent[] = new int[adj.length]; 69 | for (int i = 0; i < adj.length; i++) { 70 | Vertex v = new Vertex(i, Integer.MAX_VALUE); 71 | vertices[i] = v; 72 | parent[i] = -1; 73 | notVisited.add(v); 74 | } 75 | 76 | vertices[source].distance = 0; 77 | while (!notVisited.isEmpty()) { 78 | Vertex v = getBestEstimate(notVisited); 79 | notVisited.remove(v); 80 | visited.add(v); 81 | for (Edge e : adj[v.u]) { 82 | if (!visited.contains(e.v)) { 83 | Vertex next = vertices[e.v]; 84 | if (v.distance + e.weight < next.distance) { 85 | next.distance = v.distance + e.weight; 86 | parent[next.u] = v.u; 87 | } 88 | } 89 | } 90 | } 91 | 92 | Path[] paths = new Path[adj.length]; 93 | 94 | for (int i = 0; i < adj.length; i++) { 95 | List path = new ArrayList<>(); 96 | Path p = new Path(source, i, vertices[i].distance, path); 97 | int j = i; 98 | while (parent[j] != -1) { 99 | path.add(0, j); 100 | j = parent[j]; 101 | } 102 | paths[i] = p; 103 | } 104 | 105 | return paths; 106 | } 107 | 108 | public static void main(String [] args) { 109 | Dijkstra d = new Dijkstra(5); 110 | d.addEdge(0, 1, 10); 111 | d.addEdge(0, 3, 5); 112 | d.addEdge(1, 3, 2); 113 | d.addEdge(1, 2, 1); 114 | d.addEdge(2, 4, 4); 115 | d.addEdge(3, 1, 3); 116 | d.addEdge(3, 2, 9); 117 | d.addEdge(3, 4, 2); 118 | d.addEdge(4, 2, 6); 119 | 120 | Path[] paths = d.dijkstra(0); 121 | for (int i = 0; i < paths.length; i++) { 122 | Path p = paths[i]; 123 | System.out.print("Path from " + p.from + " to " + p.to + " (" + p.distance + ")"); 124 | for (int j = 0; j < p.path.size(); j++) { 125 | System.out.print(" " + p.path.get(j)); 126 | } 127 | System.out.println(); 128 | } 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson6/dijkstra/DijkstraWithPQ.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson6.dijkstra; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.PriorityQueue; 6 | import java.util.Set; 7 | 8 | public class DijkstraWithPQ { 9 | private class Edge { 10 | int v; 11 | int weight; 12 | 13 | Edge(int v, int weight) { 14 | this.v = v; 15 | this.weight = weight; 16 | } 17 | } 18 | 19 | private class Vertex { 20 | int u; 21 | int distance; 22 | boolean visited; 23 | 24 | Vertex(int u, int distance) { 25 | this.distance = distance; 26 | this.u = u; 27 | this.visited = false; 28 | } 29 | } 30 | 31 | public class Path { 32 | int from; 33 | int to; 34 | int distance; 35 | List path; 36 | 37 | Path(int from, int to, int distance, List path) { 38 | this.from = from; 39 | this.to = to; 40 | this.distance = distance; 41 | this.path = path; 42 | } 43 | } 44 | 45 | public class Node implements Comparable { 46 | int u; 47 | int distance; 48 | 49 | Node(int u, int distance) { 50 | this.distance = distance; 51 | this.u = u; 52 | } 53 | 54 | public int compareTo(Node o) { 55 | return (int) Math.signum(distance - o.distance); 56 | } 57 | } 58 | 59 | List adj[]; 60 | 61 | public DijkstraWithPQ(int nodes) { 62 | this.adj = new ArrayList[nodes]; 63 | for (int i = 0; i < nodes; i++) 64 | this.adj[i] = new ArrayList<>(); 65 | } 66 | 67 | public void addEdge(int u, int v, int weight) { 68 | adj[u].add(new Edge(v, weight)); 69 | } 70 | 71 | public Path[] dijkstra(int source) { 72 | Vertex vertices[] = new Vertex[adj.length]; 73 | int parent[] = new int[adj.length]; 74 | for (int i = 0; i < adj.length; i++) { 75 | Vertex v = new Vertex(i, Integer.MAX_VALUE); 76 | vertices[i] = v; 77 | parent[i] = -1; 78 | } 79 | 80 | vertices[source].distance = 0; 81 | PriorityQueue pq = new PriorityQueue<>(); 82 | pq.add(new Node(source, 0)); 83 | while (!pq.isEmpty()) { 84 | Node v = pq.remove(); 85 | if (!vertices[v.u].visited) { 86 | vertices[v.u].visited = true; 87 | for (Edge e : adj[v.u]) { 88 | Vertex next = vertices[e.v]; 89 | if (v.distance + e.weight < next.distance) { 90 | next.distance = v.distance + e.weight; 91 | parent[next.u] = v.u; 92 | pq.add(new Node(next.u, next.distance)); 93 | } 94 | } 95 | } 96 | } 97 | 98 | Path[] paths = new Path[adj.length]; 99 | 100 | for (int i = 0; i < adj.length; i++) { 101 | List path = new ArrayList<>(); 102 | Path p = new Path(source, i, vertices[i].distance, path); 103 | int j = i; 104 | while (parent[j] != -1) { 105 | path.add(0, j); 106 | j = parent[j]; 107 | } 108 | paths[i] = p; 109 | } 110 | 111 | return paths; 112 | } 113 | 114 | public static void main(String [] args) { 115 | DijkstraWithPQ d = new DijkstraWithPQ(5); 116 | d.addEdge(0, 1, 10); 117 | d.addEdge(0, 3, 5); 118 | d.addEdge(1, 3, 2); 119 | d.addEdge(1, 2, 1); 120 | d.addEdge(2, 4, 4); 121 | d.addEdge(3, 1, 3); 122 | d.addEdge(3, 2, 9); 123 | d.addEdge(3, 4, 2); 124 | d.addEdge(4, 2, 6); 125 | 126 | Path[] paths = d.dijkstra(0); 127 | for (int i = 0; i < paths.length; i++) { 128 | Path p = paths[i]; 129 | System.out.print("Path from " + p.from + " to " + p.to + " (" + p.distance + ")"); 130 | for (int j = 0; j < p.path.size(); j++) { 131 | System.out.print(" " + p.path.get(j)); 132 | } 133 | System.out.println(); 134 | } 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson6/floydwarshall/FloydWarshall.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson6.floydwarshall; 2 | 3 | public class FloydWarshall { 4 | int[][] adj; 5 | 6 | public FloydWarshall(int nodes) { 7 | this.adj = new int[nodes][nodes]; 8 | for (int i = 0; i < adj.length; i++) { 9 | for (int j = 0; j < adj[i].length; j++) { 10 | if (i == j) 11 | this.adj[i][j] = 0; 12 | else 13 | this.adj[i][j] = Integer.MAX_VALUE; 14 | } 15 | } 16 | } 17 | 18 | public void addEdge(int u, int v, int weight) { 19 | adj[u][v] = Math.min(adj[u][v], weight); 20 | } 21 | 22 | @Override 23 | public String toString() { 24 | String res = ""; 25 | for (int i = 0; i < this.adj.length; i++) { 26 | res += (i + ":"); 27 | for (int j = 0; j < this.adj[i].length; j++) 28 | res += (" " + adj[i][j]); 29 | if (i + 1 < adj.length) 30 | res += "\n"; 31 | } 32 | return res; 33 | } 34 | 35 | public void run() { 36 | for (int k = 0; k < adj.length; k++) { 37 | for (int i = 0; i < adj.length; i++) { 38 | if (adj[i][k] >= Integer.MAX_VALUE) 39 | continue; 40 | for (int j = 0; j < adj.length; j++) { 41 | if (adj[k][j] >= Integer.MAX_VALUE) 42 | continue; 43 | adj[i][j] = Math.min(adj[i][j], adj[i][k] + adj[k][j]); 44 | } 45 | } 46 | } 47 | } 48 | 49 | public static void main(String [] args) { 50 | FloydWarshall g = new FloydWarshall(5); 51 | g.addEdge(0, 1, 10); 52 | g.addEdge(0, 3, 5); 53 | g.addEdge(1, 3, 2); 54 | g.addEdge(1, 2, 1); 55 | g.addEdge(2, 4, 4); 56 | g.addEdge(3, 1, 3); 57 | g.addEdge(3, 2, 9); 58 | g.addEdge(3, 4, 2); 59 | g.addEdge(4, 2, 6); 60 | g.run(); 61 | System.out.println(g); 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson6/graph/AdjacencyListGraph.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson6.graph; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class AdjacencyListGraph { 6 | ArrayList[] adj; 7 | 8 | public AdjacencyListGraph(int nodes) { 9 | this.adj = new ArrayList[nodes]; 10 | for (int i = 0; i < nodes; i++) 11 | this.adj[i] = new ArrayList<>(); 12 | } 13 | 14 | public void addEdge(int u, int v) { 15 | adj[u].add(v); 16 | } 17 | 18 | @Override 19 | public String toString() { 20 | String res = ""; 21 | for (int i = 0; i < adj.length; i++) { 22 | res += (i + ":"); 23 | for (int j = 0; j < adj[i].size(); j++) 24 | res += (" " + adj[i].get(j)); 25 | if (i + 1 < adj.length) 26 | res += "\n"; 27 | } 28 | return res; 29 | } 30 | 31 | public static void main(String [] args) { 32 | AdjacencyListGraph g = new AdjacencyListGraph(6); 33 | g.addEdge(0, 1); 34 | g.addEdge(0, 3); 35 | g.addEdge(1, 4); 36 | g.addEdge(2, 4); 37 | g.addEdge(2, 5); 38 | g.addEdge(3, 1); 39 | g.addEdge(4, 3); 40 | g.addEdge(5, 5); 41 | System.out.println(g); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson6/graph/AdjacencyListWeightedGraph.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson6.graph; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class AdjacencyListWeightedGraph { 6 | private class Edge { 7 | int u, v, weight; 8 | 9 | public Edge(int u, int v, int weight) { 10 | this.u = u; 11 | this.v = v; 12 | this.weight = weight; 13 | } 14 | } 15 | 16 | ArrayList[] adj; 17 | 18 | public AdjacencyListWeightedGraph(int nodes) { 19 | this.adj = new ArrayList[nodes]; 20 | for (int i = 0; i < nodes; i++) 21 | this.adj[i] = new ArrayList<>(); 22 | } 23 | 24 | public void addEdge(int u, int v, int weight) { 25 | this.adj[u].add(new Edge(u, v, weight)); 26 | } 27 | 28 | @Override 29 | public String toString() { 30 | String res = ""; 31 | for (int i = 0; i < adj.length; i++) { 32 | res += (i + ":"); 33 | for (int j = 0; j < adj[i].size(); j++) { 34 | Edge edge = adj[i].get(j); 35 | res += (" " + edge.v + "(" + edge.weight + ")"); 36 | } 37 | if (i + 1 < adj.length) 38 | res += "\n"; 39 | } 40 | return res; 41 | } 42 | 43 | public static void main(String [] args) { 44 | AdjacencyListWeightedGraph g = new AdjacencyListWeightedGraph(6); 45 | g.addEdge(0, 1, 1); 46 | g.addEdge(0, 3, 4); 47 | g.addEdge(1, 4, 3); 48 | g.addEdge(2, 4, 10); 49 | g.addEdge(2, 5, 4); 50 | g.addEdge(3, 1, 5); 51 | g.addEdge(4, 3, 1); 52 | g.addEdge(5, 5, 2); 53 | System.out.println(g); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson6/graph/AdjacencyMatrixGraph.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson6.graph; 2 | 3 | public class AdjacencyMatrixGraph { 4 | int[][] adj; 5 | 6 | public AdjacencyMatrixGraph(int nodes) { 7 | this.adj = new int[nodes][nodes]; 8 | } 9 | 10 | public void addEdge(int u, int v) { 11 | this.adj[u][v] = 1; 12 | } 13 | 14 | @Override 15 | public String toString() { 16 | String res = ""; 17 | for (int i = 0; i < this.adj.length; i++) { 18 | res += (i + ":"); 19 | for (int j = 0; j < this.adj[i].length; j++) 20 | res += (" " + adj[i][j]); 21 | if (i + 1 < adj.length) 22 | res += "\n"; 23 | } 24 | return res; 25 | } 26 | 27 | public static void main(String [] args) { 28 | AdjacencyMatrixGraph g = new AdjacencyMatrixGraph(6); 29 | g.addEdge(0, 1); 30 | g.addEdge(0, 3); 31 | g.addEdge(1, 4); 32 | g.addEdge(2, 4); 33 | g.addEdge(2, 5); 34 | g.addEdge(3, 1); 35 | g.addEdge(4, 3); 36 | g.addEdge(5, 5); 37 | System.out.println(g); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson7/activity/sieve/SieveOfEratosthenes.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson7.activity.sieve; 2 | 3 | public class SieveOfEratosthenes { 4 | public SieveOfEratosthenes(int maxValue) { 5 | // Build the sieve here 6 | } 7 | 8 | public boolean isPrime(int value) { 9 | return false; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/lesson7/activity/sieve/solution/SieveOfEratosthenes.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson7.activity.sieve.solution; 2 | 3 | import java.util.Arrays; 4 | 5 | public class SieveOfEratosthenes { 6 | private boolean[] prime; 7 | 8 | public SieveOfEratosthenes(int maxValue) { 9 | prime = new boolean[maxValue + 1]; 10 | Arrays.fill(prime, true); 11 | prime[0] = prime[1] = false; 12 | int l = (int) Math.sqrt(maxValue); 13 | for (int i = 2; i <= l; i++) { 14 | if (prime[i]) { 15 | for (int j = i * i; j <= maxValue; j += i) { 16 | prime[j] = false; 17 | } 18 | } 19 | } 20 | } 21 | 22 | public boolean isPrime(int value) { 23 | return prime[value]; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/packt/datastructuresandalg/setup/HelloWorld.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.setup; 2 | 3 | public class HelloWorld { 4 | public String seyHello() { 5 | return "Hello World!"; 6 | } 7 | 8 | public static void main(String []args) { 9 | System.out.println((new HelloWorld()).seyHello()); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/test/java/com/packt/datastructuresandalg/lesson1/activity/improveintersection/IntersectionTest.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson1.activity.improveintersection; 2 | 3 | import junit.framework.TestCase; 4 | 5 | import java.util.Arrays; 6 | import java.util.HashSet; 7 | import java.util.List; 8 | 9 | public class IntersectionTest extends TestCase { 10 | Intersection interstection = new Intersection(); 11 | 12 | public void testInterstection() { 13 | int[] numbers1 = new int[]{66, 24, 75, 22, 12, 87}; 14 | int[] numbers2 = new int[]{32, 41, 98, 66, 39, 24}; 15 | 16 | List result = interstection.intersectionFast(numbers1, numbers2); 17 | 18 | List expected = Arrays.asList(66, 24); 19 | 20 | assertEquals(new HashSet<>(expected), new HashSet<>(result)); 21 | } 22 | 23 | public void testFullInterstection() { 24 | int[] numbers1 = new int[]{66, 24, 75, 22, 12, 87}; 25 | int[] numbers2 = new int[]{66, 24, 75, 22, 12, 87}; 26 | 27 | List result = interstection.intersectionFast(numbers1, numbers2); 28 | 29 | List expected = Arrays.asList(66, 24, 75, 22, 12, 87); 30 | 31 | assertEquals(new HashSet<>(expected), new HashSet<>(result)); 32 | } 33 | 34 | public void testEqualInterstection() { 35 | int[] numbers1 = new int[]{2, 2, 2, 2}; 36 | int[] numbers2 = new int[]{2, 2, 2, 2}; 37 | 38 | List result = interstection.intersectionFast(numbers1, numbers2); 39 | 40 | List expected = Arrays.asList(2, 2, 2, 2); 41 | 42 | assertEquals(expected, result); 43 | } 44 | 45 | public void testEmptyInterstection() { 46 | int[] numbers1 = new int[]{2, 4, 1, 3, 5}; 47 | int[] numbers2 = new int[]{7, 6, 9, 0, 8}; 48 | 49 | List result = interstection.intersectionFast(numbers1, numbers2); 50 | 51 | List expected = Arrays.asList(); 52 | 53 | assertEquals(expected, result); 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /src/test/java/com/packt/datastructuresandalg/lesson1/activity/octaltodecimal/OctalToDecimalTest.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson1.activity.octaltodecimal; 2 | 3 | import junit.framework.TestCase; 4 | 5 | public class OctalToDecimalTest extends TestCase { 6 | public void testZeroOctal() { 7 | OctalToDecimal octalToDecimal = new OctalToDecimal(); 8 | assertEquals(octalToDecimal.convertToDecimal("0"), 0); 9 | } 10 | 11 | public void testOneOctal() { 12 | OctalToDecimal octalToDecimal = new OctalToDecimal(); 13 | assertEquals(octalToDecimal.convertToDecimal("1"), 1); 14 | } 15 | 16 | public void testFiveOctal() { 17 | OctalToDecimal octalToDecimal = new OctalToDecimal(); 18 | assertEquals(octalToDecimal.convertToDecimal("5"), 5); 19 | } 20 | 21 | public void test17Octal() { 22 | OctalToDecimal octalToDecimal = new OctalToDecimal(); 23 | assertEquals(octalToDecimal.convertToDecimal("17"), 15); 24 | } 25 | 26 | public void test72625Octal() { 27 | OctalToDecimal octalToDecimal = new OctalToDecimal(); 28 | assertEquals(octalToDecimal.convertToDecimal("72625"), 30101); 29 | } 30 | 31 | public void test55142Octal() { 32 | OctalToDecimal octalToDecimal = new OctalToDecimal(); 33 | assertEquals(octalToDecimal.convertToDecimal("55142"), 23138); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/test/java/com/packt/datastructuresandalg/lesson2/activity/mergesort/MergeSortTest.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson2.activity.mergesort; 2 | 3 | import junit.framework.TestCase; 4 | 5 | import static org.junit.Assert.assertArrayEquals; 6 | 7 | public class MergeSortTest extends TestCase { 8 | MergeSort sort = new MergeSort(); 9 | 10 | public void testEvenElements() { 11 | int[] numbers = new int[]{5,3,5,1,6,8,1,9,0,1,3,12}; 12 | sort.mergeSort(numbers); 13 | assertArrayEquals(new int[]{0,1,1,1,3,3,5,5,6,8,9,12}, numbers); 14 | } 15 | 16 | public void testOddsElements() { 17 | int[] numbers = new int[]{5,3,5,1,6,8,1,9,0,1,16,3,12}; 18 | sort.mergeSort(numbers); 19 | assertArrayEquals(new int[]{0,1,1,1,3,3,5,5,6,8,9,12,16}, numbers); 20 | } 21 | 22 | public void testAlreadySorted() { 23 | int[] numbers = new int[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}; 24 | sort.mergeSort(numbers); 25 | assertArrayEquals(new int[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}, numbers); 26 | } 27 | 28 | public void testSameNumber() { 29 | int[] numbers = new int[]{3,3,3,3,3}; 30 | sort.mergeSort(numbers); 31 | assertArrayEquals(new int[]{3,3,3,3,3}, numbers); 32 | } 33 | 34 | public void testEmpty() { 35 | int[] numbers = new int[]{}; 36 | sort.mergeSort(numbers); 37 | assertArrayEquals(new int[]{}, numbers); 38 | } 39 | 40 | public void testOneElement() { 41 | int[] numbers = new int[]{8}; 42 | sort.mergeSort(numbers); 43 | assertArrayEquals(new int[]{8}, numbers); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/test/java/com/packt/datastructuresandalg/lesson2/activity/postfix/EvalPostfixTest.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson2.activity.postfix; 2 | 3 | import junit.framework.TestCase; 4 | 5 | public class EvalPostfixTest extends TestCase { 6 | private EvalPostfix evalPostfix = new EvalPostfix(); 7 | 8 | public void testEvalSimpleAddition() { 9 | assertEquals(3.0, evalPostfix.evaluate("1 2 +")); 10 | } 11 | 12 | public void testEvalMultipleOperands() { 13 | assertEquals(7.0, evalPostfix.evaluate("1 2 3 * +")); 14 | } 15 | 16 | public void testEvalPlusPrecedence() { 17 | assertEquals(9.0, evalPostfix.evaluate("1 2 + 3 *")); 18 | } 19 | 20 | public void testEvalDiv() { 21 | assertEquals(11.0, evalPostfix.evaluate("5 4 2 / 3 * +")); 22 | } 23 | 24 | public void testEdgeCaseNumber() { 25 | assertEquals(9.0, evalPostfix.evaluate("9")); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/test/java/com/packt/datastructuresandalg/lesson2/activity/selectionsort/SelectionSortTest.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson2.activity.selectionsort; 2 | 3 | import junit.framework.TestCase; 4 | 5 | import static org.junit.Assert.assertArrayEquals; 6 | 7 | public class SelectionSortTest extends TestCase { 8 | 9 | SelectionSort selectionSort = new SelectionSort(); 10 | 11 | public void testEvenElements() { 12 | int[] numbers = new int[]{5, 3, 5, 1, 6, 8, 1, 9, 0, 1, 3, 12}; 13 | selectionSort.sort(numbers); 14 | assertArrayEquals(new int[]{0, 1, 1, 1, 3, 3, 5, 5, 6, 8, 9, 12}, numbers); 15 | } 16 | 17 | public void testOddsElements() { 18 | int[] numbers = new int[]{5, 3, 5, 1, 6, 8, 1, 9, 0, 1, 16, 3, 12}; 19 | selectionSort.sort(numbers); 20 | assertArrayEquals(new int[]{0, 1, 1, 1, 3, 3, 5, 5, 6, 8, 9, 12, 16}, numbers); 21 | } 22 | 23 | public void testAlreadySorted() { 24 | int[] numbers = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 25 | selectionSort.sort(numbers); 26 | assertArrayEquals(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, numbers); 27 | } 28 | 29 | public void testSameNumber() { 30 | int[] numbers = new int[]{3, 3, 3, 3, 3}; 31 | selectionSort.sort(numbers); 32 | assertArrayEquals(new int[]{3, 3, 3, 3, 3}, numbers); 33 | } 34 | 35 | public void testEmpty() { 36 | int[] numbers = new int[]{}; 37 | selectionSort.sort(numbers); 38 | assertArrayEquals(new int[]{}, numbers); 39 | } 40 | 41 | public void testOneElement() { 42 | int[] numbers = new int[]{8}; 43 | selectionSort.sort(numbers); 44 | assertArrayEquals(new int[]{8}, numbers); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/test/java/com/packt/datastructuresandalg/lesson3/activity/inordersuccessor/InOrderSuccessorBinaryTreeTest.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson3.activity.inordersuccessor; 2 | 3 | import junit.framework.TestCase; 4 | 5 | import java.util.Optional; 6 | 7 | public class InOrderSuccessorBinaryTreeTest extends TestCase { 8 | 9 | public void testSuccesorEmptyTree(){ 10 | InOrderSuccessorBinaryTree binaryTree = new InOrderSuccessorBinaryTree<>(); 11 | assertEquals(Optional.empty(), binaryTree.inOrderSuccessorKey(100)); 12 | } 13 | 14 | public void testSuccesorKeyNotFound(){ 15 | InOrderSuccessorBinaryTree binaryTree = new InOrderSuccessorBinaryTree<>(); 16 | binaryTree.put(50,"Test50"); 17 | binaryTree.put(150,"Test150"); 18 | binaryTree.put(180,"Test180"); 19 | binaryTree.put(120,"Test120"); 20 | binaryTree.put(130,"Test130"); 21 | binaryTree.put(110,"Test110"); 22 | assertEquals(Optional.of(110), binaryTree.inOrderSuccessorKey(100)); 23 | } 24 | 25 | public void testSuccesorEmtpyRootOnly(){ 26 | InOrderSuccessorBinaryTree binaryTree = new InOrderSuccessorBinaryTree<>(); 27 | binaryTree.put(100,"Test100"); 28 | assertEquals(Optional.empty(), binaryTree.inOrderSuccessorKey(100)); 29 | } 30 | 31 | public void testSuccesorEmtpyRootOnlyHigherValue(){ 32 | InOrderSuccessorBinaryTree binaryTree = new InOrderSuccessorBinaryTree<>(); 33 | binaryTree.put(105,"Test105"); 34 | assertEquals(Optional.of(105), binaryTree.inOrderSuccessorKey(100)); 35 | } 36 | 37 | public void testSuccesorMaxItem(){ 38 | InOrderSuccessorBinaryTree binaryTree = new InOrderSuccessorBinaryTree<>(); 39 | binaryTree.put(10,"Test10"); 40 | binaryTree.put(100,"Test100"); 41 | binaryTree.put(30,"Test30"); 42 | binaryTree.put(70,"Test70"); 43 | assertEquals(Optional.empty(), binaryTree.inOrderSuccessorKey(100)); 44 | } 45 | 46 | public void testSuccesorTreeBelow(){ 47 | InOrderSuccessorBinaryTree binaryTree = new InOrderSuccessorBinaryTree<>(); 48 | binaryTree.put(50,"Test10"); 49 | binaryTree.put(70,"Test70"); 50 | binaryTree.put(30,"Test30"); 51 | binaryTree.put(40,"Test40"); 52 | binaryTree.put(80,"Test80"); 53 | binaryTree.put(75,"Test75"); 54 | assertEquals(Optional.of(75), binaryTree.inOrderSuccessorKey(70)); 55 | } 56 | 57 | public void testSuccesorTreeAbove(){ 58 | InOrderSuccessorBinaryTree binaryTree = new InOrderSuccessorBinaryTree<>(); 59 | binaryTree.put(50,"Test10"); 60 | binaryTree.put(45,"Test45"); 61 | binaryTree.put(47,"Test47"); 62 | binaryTree.put(40,"Test40"); 63 | binaryTree.put(30,"Test30"); 64 | binaryTree.put(80,"Test80"); 65 | binaryTree.put(75,"Test75"); 66 | assertEquals(Optional.of(40), binaryTree.inOrderSuccessorKey(30)); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/test/java/com/packt/datastructuresandalg/lesson3/activity/openaddressing/OpenAddrHashTableTest.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson3.activity.openaddressing; 2 | 3 | import com.packt.datastructuresandalg.lesson3.hashtable.RemainderHashing; 4 | import junit.framework.TestCase; 5 | 6 | import java.util.Optional; 7 | 8 | public class OpenAddrHashTableTest extends TestCase { 9 | 10 | public void testEmptyHashTable() { 11 | OpenAddrHashTable hashTable = new OpenAddrHashTable<>(10, new RemainderHashing()); 12 | assertEquals(Optional.empty(), hashTable.get(123)); 13 | } 14 | 15 | public void testItemExistHashTable() { 16 | OpenAddrHashTable hashTable = new OpenAddrHashTable<>(10, new RemainderHashing()); 17 | hashTable.put(5, "Test"); 18 | assertEquals(Optional.of("Test"), hashTable.get(5)); 19 | } 20 | 21 | public void testItemExistAfterCollisionHashTable() { 22 | OpenAddrHashTable hashTable = new OpenAddrHashTable<>(10, new RemainderHashing()); 23 | hashTable.put(5, "Test1"); 24 | hashTable.put(15, "Test2"); 25 | assertEquals(Optional.of("Test1"), hashTable.get(5)); 26 | assertEquals(Optional.of("Test2"), hashTable.get(15)); 27 | } 28 | 29 | public void testItemOnOccupiedSlotHashTable() { 30 | OpenAddrHashTable hashTable = new OpenAddrHashTable<>(10, new RemainderHashing()); 31 | hashTable.put(5, "Test5"); 32 | hashTable.put(15, "Test15"); 33 | hashTable.put(6, "Test6"); 34 | assertEquals(Optional.of("Test6"), hashTable.get(6)); 35 | } 36 | 37 | public void testGetItemAfterRemove() { 38 | OpenAddrHashTable hashTable = new OpenAddrHashTable<>(10, new RemainderHashing()); 39 | hashTable.put(5, "Test5"); 40 | hashTable.put(15, "Test15"); 41 | hashTable.put(6, "Test6"); 42 | hashTable.remove(6); 43 | assertEquals(Optional.empty(), hashTable.get(6)); 44 | } 45 | 46 | public void testInsertItemAfterRemove() { 47 | OpenAddrHashTable hashTable = new OpenAddrHashTable<>(10, new RemainderHashing()); 48 | hashTable.put(5, "Test5"); 49 | hashTable.put(15, "Test15"); 50 | hashTable.put(6, "Test6"); 51 | hashTable.remove(6); 52 | hashTable.put(25, "Test25"); 53 | assertEquals(Optional.of("Test25"), hashTable.get(25)); 54 | } 55 | 56 | 57 | public void testItemWrapsAroundHashTable() { 58 | OpenAddrHashTable hashTable = new OpenAddrHashTable<>(10, new RemainderHashing()); 59 | hashTable.put(8, "Test8"); 60 | hashTable.put(18, "Test18"); 61 | hashTable.put(28, "Test28"); 62 | hashTable.put(38, "Test38"); 63 | hashTable.put(48, "Test48"); 64 | hashTable.put(9, "Test9"); 65 | hashTable.put(19, "Test19"); 66 | hashTable.put(0, "Test0"); 67 | assertEquals(Optional.of("Test8"), hashTable.get(8)); 68 | assertEquals(Optional.of("Test18"), hashTable.get(18)); 69 | assertEquals(Optional.of("Test28"), hashTable.get(28)); 70 | assertEquals(Optional.of("Test38"), hashTable.get(38)); 71 | assertEquals(Optional.of("Test48"), hashTable.get(48)); 72 | assertEquals(Optional.of("Test9"), hashTable.get(9)); 73 | assertEquals(Optional.of("Test19"), hashTable.get(19)); 74 | assertEquals(Optional.of("Test0"), hashTable.get(0)); 75 | assertEquals(Optional.empty(), hashTable.get(58)); 76 | } 77 | 78 | public void testRemoveItemWrapsAroundHashTable() { 79 | OpenAddrHashTable hashTable = new OpenAddrHashTable<>(10, new RemainderHashing()); 80 | hashTable.put(8, "Test8"); 81 | hashTable.put(18, "Test18"); 82 | hashTable.put(28, "Test28"); 83 | hashTable.put(38, "Test38"); 84 | hashTable.put(48, "Test48"); 85 | hashTable.put(9, "Test9"); 86 | hashTable.put(19, "Test19"); 87 | hashTable.put(0, "Test0"); 88 | hashTable.remove(9); 89 | hashTable.put(58, "Test58"); 90 | assertEquals(Optional.empty(), hashTable.get(9)); 91 | assertEquals(Optional.of("Test0"), hashTable.get(0)); 92 | assertEquals(Optional.of("Test58"), hashTable.get(58)); 93 | } 94 | 95 | 96 | public void testSearchItemOnFullHashTable() { 97 | OpenAddrHashTable hashTable = new OpenAddrHashTable<>(10, new RemainderHashing()); 98 | hashTable.put(2, "Test2"); 99 | hashTable.put(12, "Test12"); 100 | hashTable.put(22, "Test22"); 101 | hashTable.put(32, "Test32"); 102 | hashTable.put(42, "Test42"); 103 | hashTable.put(52, "Test52"); 104 | hashTable.put(62, "Test62"); 105 | hashTable.put(72, "Test72"); 106 | hashTable.put(82, "Test82"); 107 | hashTable.put(92, "Test92"); 108 | assertEquals(Optional.empty(), hashTable.get(102)); 109 | } 110 | 111 | public void testPutItemOnFullHashTable() { 112 | OpenAddrHashTable hashTable = new OpenAddrHashTable<>(10, new RemainderHashing()); 113 | hashTable.put(1, "Test1"); 114 | hashTable.put(11, "Test11"); 115 | hashTable.put(21, "Test21"); 116 | hashTable.put(31, "Test31"); 117 | hashTable.put(41, "Test41"); 118 | hashTable.put(51, "Test51"); 119 | hashTable.put(61, "Test61"); 120 | hashTable.put(71, "Test71"); 121 | hashTable.put(81, "Test81"); 122 | hashTable.put(91, "Test91"); 123 | hashTable.put(101, "Test101"); 124 | assertEquals(Optional.empty(), hashTable.get(101)); 125 | assertEquals(Optional.of("Test1"), hashTable.get(1)); 126 | } 127 | 128 | 129 | 130 | } 131 | -------------------------------------------------------------------------------- /src/test/java/com/packt/datastructuresandalg/lesson4/activity/coinchange/CoinChangeTest.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson4.activity.coinchange; 2 | 3 | import junit.framework.TestCase; 4 | 5 | public class CoinChangeTest extends TestCase { 6 | CoinChange change = new CoinChange(); 7 | 8 | public void test1() { 9 | int[] coins = {1, 2, 3}; 10 | assertTrue(change.ways(4, coins) == 4); 11 | } 12 | 13 | public void test2() { 14 | int[] coins = {2, 3, 5, 6}; 15 | assertTrue(change.ways(10, coins) == 5); 16 | } 17 | 18 | public void test3() { 19 | int[] coins = {1, 5, 10, 25}; 20 | assertTrue(change.ways(63, coins) == 73); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/test/java/com/packt/datastructuresandalg/lesson4/activity/egyptian/EgyptianFractionsTest.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson4.activity.egyptian; 2 | 3 | import junit.framework.TestCase; 4 | 5 | import java.util.Arrays; 6 | 7 | public class EgyptianFractionsTest extends TestCase { 8 | EgyptianFractions fractions = new EgyptianFractions(); 9 | 10 | public void test1() { 11 | assertTrue(fractions.build(2l, 3l).equals(Arrays.asList(2l, 6l))); 12 | } 13 | 14 | public void test2() { 15 | assertTrue(fractions.build(6l, 14l).equals(Arrays.asList(3l, 11l, 231l))); 16 | } 17 | 18 | public void test3() { 19 | assertTrue(fractions.build(12l, 13l).equals(Arrays.asList(2l, 3l, 12l, 156l))); 20 | } 21 | 22 | public void test4() { 23 | assertTrue(fractions.build(3l, 4l).equals(Arrays.asList(2l, 4l))); 24 | } 25 | 26 | public void test5() { 27 | assertTrue(fractions.build(6l, 7l).equals(Arrays.asList(2l, 3l, 42l))); 28 | } 29 | 30 | public void test6() { 31 | assertTrue(fractions.build(5l, 8l).equals(Arrays.asList(2l, 8l))); 32 | } 33 | 34 | public void test7() { 35 | assertTrue(fractions.build(123l, 1500l).equals(Arrays.asList(13l, 197l, 1280500l))); 36 | } 37 | 38 | public void test8() { 39 | assertTrue(fractions.build(6123l, 7451l).equals(Arrays.asList(2l, 4l, 14l, 2939l, 14955066l, 654986696590548l))); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/test/java/com/packt/datastructuresandalg/lesson5/activity/badcharacterrule/BadCharacterRuleTest.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson5.activity.badcharacterrule; 2 | 3 | import junit.framework.TestCase; 4 | 5 | import java.util.ArrayList; 6 | import java.util.Arrays; 7 | 8 | public class BadCharacterRuleTest extends TestCase { 9 | BadCharacterRule bcr = new BadCharacterRule(); 10 | 11 | public void test1() { 12 | assertTrue(bcr.match("abc", "abc").equals(Arrays.asList(0))); 13 | } 14 | 15 | public void test2() { 16 | assertTrue(bcr.match("abd", "abc").equals(new ArrayList<>())); 17 | } 18 | 19 | public void test3() { 20 | assertTrue(bcr.match("abcde", "abc").equals(new ArrayList<>())); 21 | } 22 | 23 | public void test4() { 24 | assertTrue(bcr.match("aab", "acaabc").equals(Arrays.asList(2))); 25 | } 26 | 27 | public void test5() { 28 | assertTrue(bcr.match("aab", "acaabcaab").equals(Arrays.asList(2, 6))); 29 | } 30 | 31 | public void test6() { 32 | assertTrue(bcr.match("rabrabracad", "abacadabrabracabracadabrabrabracad").equals(Arrays.asList(23))); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/com/packt/datastructuresandalg/lesson5/activity/boyermoore/BoyerMooreTest.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson5.activity.boyermoore; 2 | 3 | import junit.framework.TestCase; 4 | 5 | import java.util.ArrayList; 6 | import java.util.Arrays; 7 | 8 | public class BoyerMooreTest extends TestCase { 9 | BoyerMoore bm = new BoyerMoore(); 10 | 11 | public void test1() { 12 | assertTrue(bm.match("abc", "abc").equals(Arrays.asList(0))); 13 | } 14 | 15 | public void test2() { 16 | assertTrue(bm.match("abd", "abc").equals(new ArrayList<>())); 17 | } 18 | 19 | public void test3() { 20 | assertTrue(bm.match("abcde", "abc").equals(new ArrayList<>())); 21 | } 22 | 23 | public void test4() { 24 | assertTrue(bm.match("aab", "acaabc").equals(Arrays.asList(2))); 25 | } 26 | 27 | public void test5() { 28 | assertTrue(bm.match("aab", "acaabcaab").equals(Arrays.asList(2, 6))); 29 | } 30 | 31 | public void test6() { 32 | assertTrue(bm.match("rabrabracad", "abacadabrabracabracadabrabrabracad").equals(Arrays.asList(23))); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/test/java/com/packt/datastructuresandalg/lesson5/activity/naivestringmatching/NaiveStringMatchingTest.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson5.activity.naivestringmatching; 2 | 3 | import junit.framework.TestCase; 4 | 5 | import java.util.ArrayList; 6 | import java.util.Arrays; 7 | 8 | public class NaiveStringMatchingTest extends TestCase { 9 | NaiveStringMatching nsm = new NaiveStringMatching(); 10 | 11 | public void test1() { 12 | assertTrue(nsm.match("abc", "abc").equals(Arrays.asList(0))); 13 | } 14 | 15 | public void test2() { 16 | assertTrue(nsm.match("abd", "abc").equals(new ArrayList<>())); 17 | } 18 | 19 | public void test3() { 20 | assertTrue(nsm.match("abcde", "abc").equals(new ArrayList<>())); 21 | } 22 | 23 | public void test4() { 24 | assertTrue(nsm.match("aab", "acaabc").equals(Arrays.asList(2))); 25 | } 26 | 27 | public void test5() { 28 | assertTrue(nsm.match("aab", "acaabcaab").equals(Arrays.asList(2, 6))); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/test/java/com/packt/datastructuresandalg/lesson6/activity/floydwarshall/FloydWarshallTest.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson6.activity.floydwarshall; 2 | 3 | import junit.framework.TestCase; 4 | 5 | import java.util.Arrays; 6 | 7 | public class FloydWarshallTest extends TestCase { 8 | public void test() { 9 | FloydWarshall f = new FloydWarshall(5); 10 | f.addEdge(0, 1, 10); 11 | f.addEdge(0, 3, 5); 12 | f.addEdge(1, 3, 2); 13 | f.addEdge(1, 2, 1); 14 | f.addEdge(2, 4, 4); 15 | f.addEdge(3, 1, 3); 16 | f.addEdge(3, 2, 9); 17 | f.addEdge(3, 4, 2); 18 | f.addEdge(4, 2, 6); 19 | f.run(); 20 | 21 | assertTrue(f.path(0, 0).equals(Arrays.asList(0))); 22 | assertTrue(f.path(0, 1).equals(Arrays.asList(0, 3, 1))); 23 | assertTrue(f.path(0, 2).equals(Arrays.asList(0, 3, 1, 2))); 24 | assertTrue(f.path(0, 3).equals(Arrays.asList(0, 3))); 25 | assertTrue(f.path(0, 4).equals(Arrays.asList(0, 3, 4))); 26 | assertTrue(f.path(1, 4).equals(Arrays.asList(1, 3, 4))); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/test/java/com/packt/datastructuresandalg/lesson6/activity/maze/MazeTest.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson6.activity.maze; 2 | 3 | import junit.framework.TestCase; 4 | 5 | public class MazeTest extends TestCase { 6 | public void test1() { 7 | Maze m = new Maze(new String[]{ 8 | "####.##", 9 | "#....##", 10 | "#.#.#.#", 11 | "#.#...#", 12 | "#.###.#", 13 | "#.....#", 14 | "#######" 15 | }); 16 | assertTrue(m.distToExit(1, 1) == 4); 17 | assertTrue(m.distToExit(5, 1) == 8); 18 | assertTrue(m.distToExit(2, 5) == 7); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/test/java/com/packt/datastructuresandalg/lesson6/activity/weightedundirected/AdjacencyMatrixWeightedUndirectedTest.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson6.activity.weightedundirected; 2 | 3 | import junit.framework.TestCase; 4 | 5 | public class AdjacencyMatrixWeightedUndirectedTest extends TestCase { 6 | public void test1() { 7 | AdjacencyMatrixWeightedUndirected g = new AdjacencyMatrixWeightedUndirected(5); 8 | g.addEdge(0, 1, 10); 9 | g.addEdge(0, 4, 5); 10 | g.addEdge(1, 2, 3); 11 | g.addEdge(2, 3, 1); 12 | g.addEdge(4, 3, 2); 13 | 14 | assertTrue(g.edgeWeight(4, 0) == 5); 15 | assertTrue(g.edgeWeight(0, 4) == 5); 16 | assertTrue(g.edgeWeight(0, 1) == 10); 17 | assertTrue(g.edgeWeight(1, 0) == 10); 18 | assertTrue(g.edgeWeight(3, 4) == 2); 19 | assertTrue(g.edgeWeight(1, 3) == 0); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/test/java/com/packt/datastructuresandalg/lesson7/activity/sieve/SieveOfEratosthenesTest.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.lesson7.activity.sieve; 2 | 3 | import junit.framework.TestCase; 4 | 5 | public class SieveOfEratosthenesTest extends TestCase { 6 | SieveOfEratosthenes sieve = new SieveOfEratosthenes(1000000); 7 | 8 | public void test0() { 9 | assertFalse(sieve.isPrime(0)); 10 | } 11 | 12 | public void test1() { 13 | assertFalse(sieve.isPrime(1)); 14 | } 15 | 16 | public void test2() { 17 | assertTrue(sieve.isPrime(2)); 18 | } 19 | 20 | public void test289049() { 21 | assertTrue(sieve.isPrime(289049)); 22 | } 23 | 24 | public void test690997() { 25 | assertTrue(sieve.isPrime(690997)); 26 | } 27 | 28 | public void test690998() { 29 | assertFalse(sieve.isPrime(690998)); 30 | } 31 | 32 | public void test999983() { 33 | assertTrue(sieve.isPrime(999983)); 34 | } 35 | 36 | public void test999999() { 37 | assertFalse(sieve.isPrime(999999)); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/test/java/com/packt/datastructuresandalg/setup/HelloWorldTest.java: -------------------------------------------------------------------------------- 1 | package com.packt.datastructuresandalg.setup; 2 | 3 | import junit.framework.TestCase; 4 | 5 | public class HelloWorldTest extends TestCase { 6 | public void testHelloWorld() { 7 | HelloWorld helloWorld = new HelloWorld(); 8 | assertEquals(helloWorld.seyHello(), "Hello World!"); 9 | } 10 | } 11 | --------------------------------------------------------------------------------