├── .gitignore ├── 1-Fundamentals ├── .classpath ├── .project ├── 1-1-BasicProgModel │ ├── Average.java │ ├── BinarySearch.java │ ├── BouncingBall.java │ ├── Cat.java │ ├── Ex_1_1_06.java │ ├── Ex_1_1_07.java │ ├── Ex_1_1_09.java │ ├── Ex_1_1_15.java │ ├── Ex_1_1_16.java │ ├── Ex_1_1_18.java │ ├── Ex_1_1_19.java │ ├── Ex_1_1_22a.java │ ├── Ex_1_1_22b.java │ ├── Ex_1_1_27a.java │ ├── Ex_1_1_27b.java │ ├── Ex_1_1_29.java │ ├── Ex_1_1_31.java │ ├── Ex_1_1_32.java │ ├── Ex_1_1_35.java │ ├── Ex_1_1_36.java │ ├── Ex_1_1_37.java │ ├── Ex_1_1_39.java │ ├── RandomSeq.java │ ├── Shuffle.java │ ├── cards.txt │ ├── in1.txt │ ├── in2.txt │ ├── tinyT.txt │ └── tinyW.txt ├── 1-2-DataAbstraction │ ├── Accumulator.java │ ├── Counter.java │ ├── Date.java │ ├── Interval1D.java │ ├── Interval2D.java │ ├── MyRational.java │ ├── Point2D.java │ ├── Rational.java │ ├── StaticSETofInts.java │ ├── TestVisualAccumulator.java │ ├── Transaction.java │ ├── VarianceAccumulator.java │ ├── Vector.java │ ├── VisualAccumulator.java │ ├── Whitelist.java │ ├── tinyT.txt │ └── tinyW.txt ├── 1-3-BagsQueuesStacks │ ├── Bag.java │ ├── DoublyLinkedList.java │ ├── Evaluate.java │ ├── EvaluatePostfix.java │ ├── Ex_1_3_03.java │ ├── Ex_1_3_04.java │ ├── Ex_1_3_09.java │ ├── Ex_1_3_29.java │ ├── Ex_1_3_37.java │ ├── FixedCapacityStack.java │ ├── FixedCapacityStackOfStrings.java │ ├── InfixToPostfix.java │ ├── List.java │ ├── Parentheses.java │ ├── Queue.java │ ├── ResizingArrayQueue.java │ ├── ResizingArrayStack.java │ ├── Stack.java │ ├── Stats.java │ └── tobe.txt ├── 1-4-AnalysisOfAlgorithms │ ├── 1Kints.txt │ ├── 2Kints.txt │ ├── 4Kints.txt │ ├── 8Kints.txt │ ├── DoublingRatio.java │ ├── DoublingTest.java │ ├── Stopwatch.java │ ├── ThreeSum.java │ └── ThreeSumFast.java └── 1-5-UnionFind │ ├── QuickFindUF.java │ ├── QuickUnionUF.java │ ├── UF.java │ ├── WeightedQuickUnionUF.java │ ├── mediumUF.txt │ └── tinyUF.txt ├── 2-Sorting ├── 2-1-ElementarySorts │ ├── Insertion.java │ ├── Selection.java │ ├── Shell.java │ ├── tiny.txt │ └── words3.txt ├── 2-2-Mergesort │ ├── Merge.java │ ├── MergeBU.java │ ├── tiny.txt │ └── words3.txt ├── 2-3-Quicksort │ ├── Quick.java │ ├── Quick3way.java │ ├── tiny.txt │ └── words3.txt └── 2-4-PriorityQueues │ ├── Heap.java │ ├── IndexMaxPQ.java │ ├── IndexMinPQ.java │ ├── MaxPQ.java │ ├── MinPQ.java │ ├── Multiway.java │ ├── TopM.java │ ├── m1.txt │ ├── m2.txt │ ├── m3.txt │ ├── tiny.txt │ ├── tinyBatch.txt │ ├── tinyPQ.txt │ └── words3.txt ├── 3-Searching ├── 3-1-SymbolTables │ ├── BinarySearchST.java │ ├── FrequencyCounter.java │ ├── SequentialSearchST.java │ ├── tale.txt │ ├── tinyST.txt │ └── tinyTale.txt ├── 3-2-BinarySearchTrees │ ├── BST.java │ └── tinyST.txt ├── 3-3-BalancedSearchTrees │ ├── RedBlackBST.java │ └── tinyST.txt ├── 3-4-HashTables │ ├── LinearProbingHashST.java │ ├── SeparateChainingHashST.java │ └── tinyST.txt ├── 3-5-Applications │ ├── BlackFilter.java │ ├── DeDup.java │ ├── FileIndex.java │ ├── LookupCSV.java │ ├── LookupIndex.java │ ├── SparseVector.java │ ├── WhiteFilter.java │ ├── amino.csv │ ├── aminoI.txt │ ├── ex1.txt │ ├── ex2.txt │ ├── ex3.txt │ ├── ex4.txt │ ├── ip.csv │ ├── list.txt │ └── tinyTale.txt ├── SET.java └── ST.java ├── 4-Graphs ├── 4-1-UndirectedGraphs │ ├── Bipartite.java │ ├── BreadthFirstPaths.java │ ├── CC.java │ ├── Cycle.java │ ├── DegreesOfSeparation.java │ ├── DepthFirstPaths.java │ ├── DepthFirstSearch.java │ ├── Graph.java │ ├── SymbolGraph.java │ ├── mediumG.txt │ ├── routes.txt │ ├── tinyCG.txt │ └── tinyG.txt ├── 4-2-DirectedGraphs │ ├── BreadthFirstDirectedPaths.java │ ├── DepthFirstDirectedPaths.java │ ├── DepthFirstOrder.java │ ├── Digraph.java │ ├── DirectedCycle.java │ ├── DirectedDFS.java │ ├── KosarajuSCC.java │ ├── SymbolDigraph.java │ ├── Topological.java │ ├── TransitiveClosure.java │ ├── jobs.txt │ ├── tinyDAG.txt │ └── tinyDG.txt ├── 4-3-MinSpanningTrees │ ├── BoruvkaMST.java │ ├── Edge.java │ ├── EdgeWeightedGraph.java │ ├── KruskalMST.java │ ├── LazyPrimMST.java │ ├── PrimMST.java │ ├── mediumEWG.txt │ └── tinyEWG.txt └── 4-4-ShortestPaths │ ├── AcyclicLP.java │ ├── AcyclicSP.java │ ├── Arbitrage.java │ ├── BellmanFordSP.java │ ├── CPM.java │ ├── DijkstraAllPairsSP.java │ ├── DijkstraSP.java │ ├── DirectedEdge.java │ ├── EdgeWeightedDigraph.java │ ├── EdgeWeightedDirectedCycle.java │ ├── jobsPC.txt │ ├── mediumEWD.txt │ ├── rates.txt │ ├── tinyEWD.txt │ ├── tinyEWDAG.txt │ ├── tinyEWDn.txt │ └── tinyEWDnc.txt ├── 5-Strings ├── 5-1-StringSorts │ ├── LSD.java │ ├── MSD.java │ ├── Quick3string.java │ ├── shells.txt │ └── words3.txt ├── 5-2-Tries │ ├── TST.java │ ├── TrieST.java │ └── shellsST.txt ├── 5-3-SubstringSearch │ ├── BoyerMoore.java │ ├── KMP.java │ └── RabinKarp.java ├── 5-4-RegularExpressions │ ├── GREP.java │ ├── NFA.java │ └── tinyL.txt └── 5-5-DataCompression │ ├── 4runs.bin │ ├── Alphabet.java │ ├── BinaryDump.java │ ├── Count.java │ ├── Genome.java │ ├── HexDump.java │ ├── Huffman.java │ ├── LZW.java │ ├── PictureDump.java │ ├── RunLength.java │ ├── ababLZW.txt │ ├── abra.txt │ ├── abraLZW.txt │ ├── genomeTiny.txt │ ├── genomeVirus.txt │ ├── medTale.txt │ ├── pi.txt │ ├── q32x48.bin │ ├── q64x96.bin │ ├── tale.txt │ └── tinytinyTale.txt ├── 6-Context ├── 6-1-EventDrivenSim │ ├── CollisionSystem.java │ ├── Particle.java │ ├── brownian.txt │ └── diffusion.txt ├── 6-2-BTrees │ └── BTree.java ├── 6-3-SuffixArrays │ ├── KWIK.java │ ├── LRS.java │ ├── SuffixArray.java │ ├── abra.txt │ ├── tale.txt │ └── tinyTale.txt ├── 6-4-Maxflow │ ├── FlowEdge.java │ ├── FlowNetwork.java │ ├── FordFulkerson.java │ └── tinyFN.txt └── 6-5-Reductions │ ├── AssignmentProblem.java │ ├── BipartiteMatching.java │ └── Simplex.java ├── Beyond ├── ClosestPair.java ├── Complex.java ├── FFT.java ├── FarthestPair.java ├── GaussianElimination.java ├── GrahamScan.java └── rs1423.txt ├── Readme.txt ├── StdLib ├── .classpath ├── .project ├── BinaryDump.java ├── BinaryIn.java ├── BinaryOut.java ├── BinaryStdIn.java ├── BinaryStdInTester.java ├── BinaryStdOut.java ├── BinaryStdOutTester.java ├── Copy.java ├── Draw.java ├── DrawListener.java ├── HexDump.java ├── In.java ├── InTest.txt ├── Out.java ├── Picture.java ├── PictureDump.java ├── StdArrayIO.java ├── StdAudio.java ├── StdDraw.java ├── StdDraw3D.java ├── StdIn.java ├── StdOut.java ├── StdRandom.java ├── StdStats.java ├── Stopwatch.java └── mandrill.jpg ├── algs4.jar └── stdlib.jar /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | *~ 3 | *# 4 | #* 5 | 6 | *.class 7 | bin/ 8 | doc/ 9 | 10 | .metadata/ 11 | 12 | out.txt 13 | 14 | leipzig1M.txt 15 | UPC.csv 16 | largeUF.txt 17 | largeT.txt 18 | largeW.txt 19 | movies.txt 20 | mobydick.txt 21 | DJIA.csv 22 | -------------------------------------------------------------------------------- /1-Fundamentals/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /1-Fundamentals/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | 1-Fundamentals 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /1-Fundamentals/1-1-BasicProgModel/Average.java: -------------------------------------------------------------------------------- 1 | 2 | /************************************************************************* 3 | * Compilation: javac Average.java 4 | * Execution: java Average < data.txt 5 | * Dependencies: StdIn.java StdOut.java 6 | * 7 | * Reads in a sequence of real numbers, and computes their average. 8 | * 9 | * % java Average 10 | * 10.0 5.0 6.0 11 | * 3.0 7.0 32.0 12 | * 13 | * Average is 10.5 14 | 15 | * Note signifies the end of file on Unix. 16 | * On windows use . 17 | * 18 | *************************************************************************/ 19 | 20 | public class Average { 21 | public static void main(String[] args) { 22 | int count = 0; // number input values 23 | double sum = 0.0; // sum of input values 24 | 25 | // read data and compute statistics 26 | while (!StdIn.isEmpty()) { 27 | double value = StdIn.readDouble(); 28 | sum += value; 29 | count++; 30 | } 31 | 32 | // compute the average 33 | double average = sum / count; 34 | 35 | // print results 36 | StdOut.println("Average is " + average); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /1-Fundamentals/1-1-BasicProgModel/BinarySearch.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac BinarySearch.java 3 | * Execution: java BinarySearch whitelist.txt < input.txt 4 | * Data files: http://algs4.cs.princeton.edu/11model/tinyW.txt 5 | * http://algs4.cs.princeton.edu/11model/tinyT.txt 6 | * http://algs4.cs.princeton.edu/11model/largeW.txt 7 | * http://algs4.cs.princeton.edu/11model/largeT.txt 8 | * 9 | * % java BinarySearch tinyW.txt < tinyT.txt 10 | * 50 11 | * 99 12 | * 13 13 | * 14 | * % java BinarySearch largeW.txt < largeT.txt | more 15 | * 499569 16 | * 984875 17 | * 295754 18 | * 207807 19 | * 140925 20 | * 161828 21 | * [3,675,966 total values] 22 | * 23 | *************************************************************************/ 24 | 25 | import java.util.Arrays; 26 | 27 | public class BinarySearch { 28 | 29 | // precondition: array a[] is sorted 30 | public static int rank(int key, int[] a) { 31 | int lo = 0; 32 | int hi = a.length - 1; 33 | while (lo <= hi) { 34 | // Key is in a[lo..hi] or not present. 35 | int mid = lo + (hi - lo) / 2; 36 | if (key < a[mid]) hi = mid - 1; 37 | else if (key > a[mid]) lo = mid + 1; 38 | else return mid; 39 | } 40 | return -1; 41 | } 42 | 43 | public static void main(String[] args) { 44 | int[] whitelist = In.readInts(args[0]); 45 | 46 | Arrays.sort(whitelist); 47 | 48 | // read key; print if not in whitelist 49 | while (!StdIn.isEmpty()) { 50 | int key = StdIn.readInt(); 51 | if (rank(key, whitelist) == -1) 52 | StdOut.println(key); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /1-Fundamentals/1-1-BasicProgModel/BouncingBall.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac BouncingBall.java 3 | * Execution: java BouncingBall 4 | * Dependencies: StdDraw.java 5 | * 6 | * Implementation of a 2-d bouncing ball in the box from (-1, -1) to (1, 1). 7 | * 8 | * % java BouncingBall 9 | * 10 | *************************************************************************/ 11 | 12 | public class BouncingBall { 13 | public static void main(String[] args) { 14 | 15 | // set the scale of the coordinate system 16 | StdDraw.setXscale(-1.0, 1.0); 17 | StdDraw.setYscale(-1.0, 1.0); 18 | 19 | // initial values 20 | double rx = 0.480, ry = 0.860; // position 21 | double vx = 0.015, vy = 0.023; // velocity 22 | double radius = 0.05; // radius 23 | 24 | // main animation loop 25 | while (true) { 26 | 27 | // bounce off wall according to law of elastic collision 28 | if (Math.abs(rx + vx) > 1.0 - radius) vx = -vx; 29 | if (Math.abs(ry + vy) > 1.0 - radius) vy = -vy; 30 | 31 | // update position 32 | rx = rx + vx; 33 | ry = ry + vy; 34 | 35 | // clear the background 36 | StdDraw.setPenColor(StdDraw.GRAY); 37 | StdDraw.filledSquare(0, 0, 1.0); 38 | 39 | // draw ball on the screen 40 | StdDraw.setPenColor(StdDraw.BLACK); 41 | StdDraw.filledCircle(rx, ry, radius); 42 | 43 | // display and pause for 20 ms 44 | StdDraw.show(20); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /1-Fundamentals/1-1-BasicProgModel/Cat.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac Cat.java 3 | * Execution: java Cat input0.txt input1.txt ... output.txt 4 | * Dependencies: In.java Out.java 5 | * 6 | * Reads in text files specified as the first command-line 7 | * parameters, concatenates them, and writes the result to 8 | * filename specified as the last command line parameter. 9 | * 10 | * % more in1.txt 11 | * This is 12 | * 13 | * % more in2.txt 14 | * a tiny 15 | * test. 16 | * 17 | * % java Cat in1.txt in2.txt out.txt 18 | * 19 | * % more out.txt 20 | * This is 21 | * a tiny 22 | * test. 23 | * 24 | *************************************************************************/ 25 | 26 | public class Cat { 27 | 28 | public static void main(String[] args) { 29 | Out out = new Out(args[args.length - 1]); 30 | for (int i = 0; i < args.length - 1; i++) { 31 | In in = new In(args[i]); 32 | String s = in.readAll(); 33 | out.println(s); 34 | in.close(); 35 | } 36 | out.close(); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /1-Fundamentals/1-1-BasicProgModel/Ex_1_1_06.java: -------------------------------------------------------------------------------- 1 | 2 | public class Ex_1_1_06 { 3 | 4 | public static void main(String[] args) { 5 | 6 | int f = 0; 7 | int g = 1; 8 | for (int i = 0; i <= 15; i++) 9 | { 10 | StdOut.println(f); 11 | f = f + g; 12 | g = f - g; 13 | } 14 | 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /1-Fundamentals/1-1-BasicProgModel/Ex_1_1_07.java: -------------------------------------------------------------------------------- 1 | 2 | public class Ex_1_1_07 { 3 | 4 | public static void main(String[] args) 5 | { 6 | double t = 9.0; 7 | while (Math.abs(t - 9.0/t) > .00001) 8 | { 9 | t = (9.0/t + t) / 2.0; 10 | StdOut.printf("%.5f\n", t); 11 | } 12 | 13 | // System.out.println('b' + 'c'); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /1-Fundamentals/1-1-BasicProgModel/Ex_1_1_09.java: -------------------------------------------------------------------------------- 1 | 2 | public class Ex_1_1_09 { 3 | 4 | public static void main(String[] args) 5 | { 6 | int N = 234245; 7 | 8 | StdOut.println(Integer.toBinaryString(N)); 9 | 10 | String s = ""; 11 | for (int n = N; n > 0; n /= 2) 12 | s = (n % 2) + s; 13 | StdOut.println(s); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /1-Fundamentals/1-1-BasicProgModel/Ex_1_1_15.java: -------------------------------------------------------------------------------- 1 | 2 | public class Ex_1_1_15 3 | { 4 | public static int[] histogram(int[] a, int M) 5 | { 6 | int[] h = new int[M]; 7 | int N = a.length; 8 | 9 | for (int i = 0; i < N; i++) 10 | if (a[i] < M) 11 | h[a[i]]++; 12 | 13 | return h; 14 | } 15 | 16 | public static void main(String[] args) 17 | { 18 | int N = 30; 19 | int M = 10; 20 | 21 | int[] a = new int[N]; 22 | for (int i = 0; i < N; i++) 23 | a[i] = StdRandom.uniform(M); 24 | 25 | for (int i = 0; i < N; i++) 26 | StdOut.printf("%2d", a[i]); 27 | 28 | int[] h = histogram(a, M); 29 | 30 | StdOut.println("\n"); 31 | for (int i = 0; i < M; i++) 32 | StdOut.printf("%4d", h[i]); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /1-Fundamentals/1-1-BasicProgModel/Ex_1_1_16.java: -------------------------------------------------------------------------------- 1 | 2 | public class Ex_1_1_16 3 | { 4 | public static String exR1(int n) 5 | { 6 | if (n <= 0) return ""; 7 | return exR1(n-3) + n + exR1(n-2) + n; 8 | } 9 | 10 | public static void main(String[] args) 11 | { 12 | StdOut.println(exR1(6)); 13 | // 311361142246 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /1-Fundamentals/1-1-BasicProgModel/Ex_1_1_18.java: -------------------------------------------------------------------------------- 1 | 2 | public class Ex_1_1_18 3 | { 4 | public static int mystery1(int a, int b) 5 | { 6 | StdOut.printf("%3d, %3d\n", a, b); 7 | if (b == 0) return 0; 8 | if (b % 2 == 0) return mystery1(a+a, b/2); 9 | return mystery1(a+a, b/2) + a; 10 | } 11 | 12 | public static int mystery2(int a, int b) 13 | { 14 | StdOut.printf("%7d, %3d\n", a, b); 15 | if (b == 0) return 1; 16 | if (b % 2 == 0) return mystery2(a*a, b/2); 17 | return mystery2(a*a, b/2) * a; 18 | } 19 | 20 | public static void main(String[] args) 21 | { 22 | StdOut.println("Result: " + mystery1(5, 7)); 23 | StdOut.println(); 24 | StdOut.println("Result: " + mystery2(5, 7)); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /1-Fundamentals/1-1-BasicProgModel/Ex_1_1_19.java: -------------------------------------------------------------------------------- 1 | 2 | public class Ex_1_1_19 3 | { 4 | public static long F(int N) 5 | { 6 | if (N == 0) return 0; 7 | if (N == 1) return 1; 8 | return F(N-1) + F(N-2); 9 | } 10 | 11 | public static long Fib(int N) 12 | { 13 | long[] f = new long[N+1]; 14 | return Fib(N, f); 15 | } 16 | 17 | public static long Fib(int N, long[] f) 18 | { 19 | if (f[N] == 0) 20 | { 21 | if (N == 1) 22 | f[N] = 1; 23 | else if (N > 1) 24 | f[N] = Fib(N-1, f) + Fib(N-2, f); 25 | } 26 | 27 | return f[N]; 28 | } 29 | 30 | public static void main(String[] args) 31 | { 32 | // for (int N = 0; N < 100; N++) 33 | // StdOut.println(N + " " + F(N)); 34 | for (int N = 0; N < 100; N++) 35 | StdOut.println(N + " " + Fib(N)); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /1-Fundamentals/1-1-BasicProgModel/Ex_1_1_22a.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Arrays; 3 | 4 | // Based on class BinarySearch 5 | public class Ex_1_1_22a 6 | { 7 | // precondition: array a[] is sorted 8 | public static int rank(int key, int[] a) 9 | { 10 | int lo = 0, 11 | hi = a.length - 1, 12 | indent = 0; 13 | while (lo <= hi) { 14 | StdOut.printf("%s%-4d%d\n", repeat(4*indent++, ' '), lo, hi); 15 | 16 | // Key is in a[lo..hi] or not present. 17 | int mid = lo + (hi - lo) / 2; 18 | if (key < a[mid]) hi = mid - 1; 19 | else if (key > a[mid]) lo = mid + 1; 20 | else return mid; 21 | } 22 | return -1; 23 | } 24 | 25 | private static String repeat(int n, char c) 26 | { 27 | String s = ""; 28 | for (int i = 0; i < n; i++) 29 | s += c; 30 | return s; 31 | } 32 | 33 | public static void main(String[] args) 34 | { 35 | int[] whitelist = In.readInts(args[0]); 36 | 37 | Arrays.sort(whitelist); 38 | 39 | // read key; print if not in whitelist 40 | while (!StdIn.isEmpty()) { 41 | int key = StdIn.readInt(); 42 | if (rank(key, whitelist) == -1) 43 | StdOut.println(key); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /1-Fundamentals/1-1-BasicProgModel/Ex_1_1_22b.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Arrays; 3 | 4 | // Based on class BinarySearch 5 | public class Ex_1_1_22b 6 | { 7 | 8 | 9 | public static int rank(int key, int[] a) 10 | { 11 | return rank(key, a, 0, a.length - 1, 0); 12 | } 13 | 14 | public static int rank(int key, int[] a, int lo, int hi, int indent) 15 | { 16 | StdOut.printf("%s%-4d%d\n", repeat(4*indent, ' '), lo, hi); 17 | 18 | if (lo > hi) return -1; 19 | 20 | int mid = lo + (hi - lo) / 2; 21 | if (key < a[mid]) return rank(key, a, lo, mid - 1, indent + 1); 22 | else if (key > a[mid]) return rank(key, a, mid + 1, hi, indent + 1); 23 | else return mid; 24 | } 25 | 26 | private static String repeat(int n, char c) 27 | { 28 | String s = ""; 29 | for (int i = 0; i < n; i++) 30 | s += c; 31 | return s; 32 | } 33 | 34 | public static void main(String[] args) 35 | { 36 | int[] whitelist = In.readInts(args[0]); 37 | 38 | Arrays.sort(whitelist); 39 | 40 | // read key; print if not in whitelist 41 | while (!StdIn.isEmpty()) { 42 | int key = StdIn.readInt(); 43 | if (rank(key, whitelist) == -1) 44 | StdOut.println(key); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /1-Fundamentals/1-1-BasicProgModel/Ex_1_1_27a.java: -------------------------------------------------------------------------------- 1 | 2 | public class Ex_1_1_27a 3 | { 4 | public static double binomial(int n, int k, double p, Counter c) 5 | { 6 | if (n == 0 && k == 0) return 1.0; 7 | if (n < 0 || k < 0) return 0.0; 8 | 9 | c.increment(); 10 | 11 | return (1.0 - p) * binomial(n-1, k, p, c) + p * binomial(n-1, k-1, p, c); 12 | } 13 | 14 | public static void main(String[] args) 15 | { 16 | int n = Integer.parseInt(args[0]), 17 | k = Integer.parseInt(args[1]); 18 | double p = Double.parseDouble(args[2]); 19 | 20 | Counter c = new Counter("calls"); 21 | 22 | double b = binomial(n, k, p, c); 23 | 24 | StdOut.println(b); 25 | StdOut.println(c); 26 | // java Ex_1_1_27a 10 5 0.5: 1,233 calls 27 | // java Ex_1_1_27a 20 10 0.5: 1,216,535 calls 28 | // java Ex_1_1_27a 30 15 0.5: 1,219,164,498 calls 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /1-Fundamentals/1-1-BasicProgModel/Ex_1_1_27b.java: -------------------------------------------------------------------------------- 1 | 2 | public class Ex_1_1_27b 3 | { 4 | public static double binomial(int n, int k, double p, Counter c) 5 | { 6 | double[][] v = new double[n+1][k+1]; 7 | for (int i = 0; i <= n; i++) 8 | for (int j = 0; j <= k; j++) 9 | v[i][j] = -1; 10 | 11 | return binomial(v, n, k, p, c); 12 | } 13 | 14 | public static double binomial(double[][] v, int n, int k, double p, Counter c) 15 | { 16 | if (n == 0 && k == 0) return 1.0; 17 | if (n < 0 || k < 0) return 0.0; 18 | 19 | if (v[n][k] == -1) 20 | { 21 | c.increment(); 22 | v[n][k] = (1.0 - p) * binomial(v, n-1, k, p, c) + p * binomial(v, n-1, k-1, p, c); 23 | } 24 | 25 | return v[n][k]; 26 | } 27 | 28 | public static void main(String[] args) 29 | { 30 | int n = Integer.parseInt(args[0]), 31 | k = Integer.parseInt(args[1]); 32 | double p = Double.parseDouble(args[2]); 33 | 34 | Counter c = new Counter("calls"); 35 | 36 | double b = binomial(n, k, p, c); 37 | 38 | StdOut.println(b); 39 | StdOut.println(c); 40 | // java Ex_1_1_27b 10 5 0.5: 50 calls 41 | // java Ex_1_1_27b 20 10 0.5: 175 calls 42 | // java Ex_1_1_27b 30 15 0.5: 375 calls 43 | // java Ex_1_1_27b 100 50 0.5: 3,875 calls 44 | // java Ex_1_1_27b 1000 500 0.5: 376,250 calls 45 | // java Ex_1_1_27b 4000 2000 0.5: 6,005,000 calls 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /1-Fundamentals/1-1-BasicProgModel/Ex_1_1_29.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Arrays; 3 | 4 | public class Ex_1_1_29 5 | { 6 | public static int rank(int key, int[] a) 7 | { 8 | return rank(key, a, true); 9 | } 10 | 11 | public static int rank(int key, int[] a, boolean trace) 12 | { 13 | int lo = 0; 14 | int hi = a.length - 1; 15 | 16 | while (lo <= hi) { 17 | int mid = lo + (hi - lo) / 2; 18 | 19 | // if (trace) 20 | // StdOut.printf("%4d%4d -> %4d\n", lo, hi, mid); 21 | 22 | if (key < a[mid]) hi = mid - 1; 23 | else if (key > a[mid]) lo = mid + 1; 24 | else 25 | { 26 | while (--mid >= 0 && a[mid] == key); 27 | return mid+1; 28 | } 29 | } 30 | return 0; 31 | } 32 | 33 | public static int count(int key, int[] a) 34 | { 35 | int c = 0; 36 | for (int i = rank(key, a, false); i < a.length && a[i] == key; i++) 37 | c++; 38 | return c; 39 | } 40 | 41 | private static boolean verify(int r, int c, int key, int[] a) 42 | { 43 | for (int i = 0; i < a.length; i++) 44 | if ((i < r || i > r+c-1) && a[i] == key || 45 | (i >= r && i <= r+c-1) && a[i] != key) 46 | return false; 47 | return true; 48 | } 49 | 50 | public static void main(String[] args) 51 | { 52 | int[] whitelist = In.readInts(args[0]); 53 | 54 | Arrays.sort(whitelist); 55 | 56 | String indices = "", 57 | values = ""; 58 | for (int i = 0; i < whitelist.length; i++) 59 | { 60 | indices += String.format("%4d", i); 61 | values += String.format("%4d", whitelist[i]); 62 | } 63 | StdOut.println(indices + "\n" + values); 64 | 65 | while (!StdIn.isEmpty()) { 66 | int key = StdIn.readInt(); 67 | int r = rank(key, whitelist); 68 | int c = count(key, whitelist); 69 | StdOut.printf("(%d, %d) - %s\n", r, c, verify(r, c, key, whitelist)); 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /1-Fundamentals/1-1-BasicProgModel/Ex_1_1_31.java: -------------------------------------------------------------------------------- 1 | 2 | public class Ex_1_1_31 3 | { 4 | public static void drawRandConn(int N, double p) 5 | { 6 | StdDraw.setCanvasSize(1024, 1024); 7 | StdDraw.setScale(-1.0, 1.0); 8 | StdDraw.setPenRadius(.015); 9 | 10 | double[][] d = new double[N][2]; 11 | for (int i = 0; i < N; i++) 12 | { 13 | d[i][0] = Math.cos(2 * Math.PI * i / N); 14 | d[i][1] = Math.sin(2 * Math.PI * i / N); 15 | StdDraw.point(d[i][0], d[i][1]); 16 | } 17 | 18 | StdDraw.setPenRadius(); 19 | 20 | for (int i = 0; i < N - 1; i++) 21 | for (int j = i + 1; j < N; j++) 22 | if (StdRandom.bernoulli(p)) 23 | StdDraw.line(d[i][0], d[i][1], d[j][0], d[j][1]); 24 | } 25 | 26 | public static void main(String[] args) 27 | { 28 | int N = Integer.parseInt(args[0]); 29 | double p = Double.parseDouble(args[1]); 30 | p = Math.max(0, Math.min(1, p)); 31 | 32 | drawRandConn(N, p); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /1-Fundamentals/1-1-BasicProgModel/Ex_1_1_32.java: -------------------------------------------------------------------------------- 1 | /************************************************* 2 | * 3 | * % java Ex_1_1_32 500 0 1000000 < largeT.txt 4 | * 5 | *************************************************/ 6 | 7 | public class Ex_1_1_32 8 | { 9 | public static void histogram(double[] values, int n, double l, double r) 10 | { 11 | int[] counts = new int[n]; 12 | 13 | for (int i = 0; i < values.length; i++) 14 | { 15 | int k = getInterval(values[i], n, l, r); 16 | if (k >= 0) 17 | counts[k]++; 18 | } 19 | 20 | int maxCount = StdStats.max(counts); 21 | 22 | StdDraw.setCanvasSize(1024, 512); 23 | StdDraw.setXscale(l, r); 24 | StdDraw.setYscale(0, maxCount); 25 | 26 | double w = (r - l) / n; 27 | 28 | for (int i = 0; i < n; i++) 29 | { 30 | double x = l + (i + 0.5) * w, 31 | y = counts[i] / 2.0, 32 | rw = 0.5 * w, 33 | rh = counts[i] / 2.0; 34 | StdDraw.filledRectangle(x, y, rw, rh); 35 | } 36 | } 37 | 38 | private static int getInterval(double v, int n, double l, double r) 39 | { 40 | if (v < l || v >= r) 41 | return -1; 42 | else 43 | return (int)(n * (v - l) / (r - l)); 44 | } 45 | 46 | public static void main(String[] args) 47 | { 48 | int n = Integer.parseInt(args[0]); 49 | double l = Double.parseDouble(args[1]), 50 | r = Double.parseDouble(args[2]); 51 | 52 | double[] values = In.readDoubles(); 53 | 54 | histogram(values, n, l, r); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /1-Fundamentals/1-1-BasicProgModel/Ex_1_1_35.java: -------------------------------------------------------------------------------- 1 | 2 | public class Ex_1_1_35 3 | { 4 | private static int SIDES = 6; 5 | 6 | public static double[] getExact() 7 | { 8 | double[] dist = new double[2*SIDES+1]; 9 | 10 | for (int i = 1; i <= SIDES; i++) 11 | for (int j = 1; j <= SIDES; j++) 12 | dist[i+j] += 1.0; 13 | 14 | for (int k = 2; k <= 2*SIDES; k++) 15 | dist[k] /= SIDES*SIDES; 16 | 17 | return dist; 18 | } 19 | 20 | public static double[] getExperim(int n) 21 | { 22 | double[] dist = new double[2*SIDES+1]; 23 | 24 | for (int i = 0; i < n; i++) 25 | dist[throwDice()]++; 26 | 27 | for (int k = 2; k <= 2*SIDES; k++) 28 | dist[k] /= n; 29 | 30 | return dist; 31 | } 32 | 33 | public static int throwDice() 34 | { 35 | return StdRandom.uniform(1, SIDES+1) + StdRandom.uniform(1, SIDES+1); 36 | } 37 | 38 | public static void main(String[] args) 39 | { 40 | int n = Integer.parseInt(args[0]); 41 | 42 | double[] exact = getExact(); 43 | 44 | for (int i = 2; i <= 2*SIDES; i++) 45 | StdOut.printf("%7d", i); 46 | StdOut.println(); 47 | 48 | for (int i = 2; i <= 2*SIDES; i++) 49 | StdOut.printf("%7.3f", exact[i]); 50 | StdOut.println(); 51 | 52 | double[] experim = getExperim(n); 53 | 54 | for (int i = 2; i <= 2*SIDES; i++) 55 | StdOut.printf("%7.3f", experim[i]); 56 | StdOut.println(); 57 | 58 | // Empirical results match exact ones to 3 decimal places when 59 | // n >= 10,000,000 (< 1 sec.) 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /1-Fundamentals/1-1-BasicProgModel/Ex_1_1_36.java: -------------------------------------------------------------------------------- 1 | 2 | public class Ex_1_1_36 3 | { 4 | public interface IShuffle 5 | { 6 | public void shuffle(int[] a); 7 | } 8 | 9 | public static void ShuffleTest(IShuffle shuffle, int m, int n) 10 | { 11 | int[][] s = new int[m][m]; 12 | 13 | for (int k = 0; k < n; k++) 14 | { 15 | int[] a = new int[m]; 16 | for (int i = 0; i < m; i++) 17 | a[i] = i; 18 | 19 | shuffle.shuffle(a); 20 | 21 | for (int i = 0; i < m; i++) 22 | s[i][a[i]]++; 23 | } 24 | 25 | for (int i = 0; i < m; i++) 26 | { 27 | for (int j = 0; j < m; j++) 28 | StdOut.printf("%7d", s[i][j]); 29 | StdOut.println(); 30 | } 31 | } 32 | 33 | public static void main(String[] args) 34 | { 35 | int m = Integer.parseInt(args[0]); 36 | int n = Integer.parseInt(args[1]); 37 | 38 | // closure 39 | IShuffle shuffle = new IShuffle() 40 | { 41 | public void shuffle(int[] a) 42 | { 43 | StdRandom.shuffle(a); 44 | } 45 | }; 46 | 47 | ShuffleTest(shuffle, m, n); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /1-Fundamentals/1-1-BasicProgModel/Ex_1_1_37.java: -------------------------------------------------------------------------------- 1 | 2 | public class Ex_1_1_37 3 | { 4 | public static void badShuffle(int[] a) { 5 | int N = a.length; 6 | for (int i = 0; i < N; i++) { 7 | int r = StdRandom.uniform(N); // between 0 and N-1 8 | int temp = a[i]; 9 | a[i] = a[r]; 10 | a[r] = temp; 11 | } 12 | } 13 | 14 | public static void main(String[] args) 15 | { 16 | int m = Integer.parseInt(args[0]); 17 | int n = Integer.parseInt(args[1]); 18 | 19 | // closure 20 | Ex_1_1_36.IShuffle shuffle = new Ex_1_1_36.IShuffle() 21 | { 22 | public void shuffle(int[] a) 23 | { 24 | badShuffle(a); 25 | } 26 | }; 27 | 28 | Ex_1_1_36.ShuffleTest(shuffle, m, n); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /1-Fundamentals/1-1-BasicProgModel/Ex_1_1_39.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Arrays; 3 | 4 | public class Ex_1_1_39 5 | { 6 | public static int experiment(int n) 7 | { 8 | int[] a = new int[n], 9 | b = new int[n]; 10 | 11 | for (int i = 0; i < n; i++) 12 | { 13 | a[i] = StdRandom.uniform(100000, 1000000); 14 | b[i] = StdRandom.uniform(100000, 1000000); 15 | } 16 | 17 | Arrays.sort(b); 18 | 19 | int count = 0; 20 | for (int i = 0; i < n; i++) 21 | if (BinarySearch.rank(a[i], b) >= 0) 22 | count++; 23 | 24 | return count; 25 | } 26 | 27 | public static void batch(int t, int n) 28 | { 29 | long count = 0; 30 | for (int i = 0; i < t; i++) 31 | count += experiment(n); 32 | 33 | double avg = 1.0 * count / t; 34 | 35 | StdOut.printf("%8d: %9.2f\n", n, avg); 36 | } 37 | 38 | public static void main(String[] args) 39 | { 40 | int t = Integer.parseInt(args[0]); 41 | 42 | int[] ns = { 1000, 10000, 100000, 1000000 }; 43 | 44 | for (int i = 0; i < ns.length; i++) 45 | batch(t, ns[i]); 46 | 47 | /* 48 | 1000: 0.96 49 | 10000: 110.68 50 | 100000: 10527.36 51 | 1000000: 670822.20 52 | */ 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /1-Fundamentals/1-1-BasicProgModel/RandomSeq.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac RandomSeq.java 3 | * Execution: java RandomSeq N lo hi 4 | * 5 | * Prints N numbers between lo and hi. 6 | * 7 | * % java RandomSeq 5 100.0 200.0 8 | * 123.43 9 | * 153.13 10 | * 144.38 11 | * 155.18 12 | * 104.02 13 | * 14 | *************************************************************************/ 15 | 16 | public class RandomSeq { 17 | public static void main(String[] args) { 18 | 19 | // command-line arguments 20 | int N = Integer.parseInt(args[0]); 21 | double lo = Double.parseDouble(args[1]); 22 | double hi = Double.parseDouble(args[2]); 23 | 24 | // generate and print N numbers between lo and hi 25 | for (int i = 0; i < N; i++) { 26 | double x = StdRandom.uniform(lo, hi); 27 | StdOut.printf("%.2f\n", x); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /1-Fundamentals/1-1-BasicProgModel/Shuffle.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac Shuffle.java 3 | * Execution: java Shuffle < list.txt 4 | * Data files: http://algs4.cs.princeton.edu/11model/cards.txt 5 | * 6 | * Reads in a list of strings and prints them in random order. 7 | * The Knuth (or Fisher-Yates) shuffling algorithm guarantees 8 | * to rearrange the elements in uniformly random order, under 9 | * the assumption that Math.random() generates independent and 10 | * uniformly distributed numbers between 0 and 1. 11 | * 12 | * % more cards.txt 13 | * 2C 3C 4C 5C 6C 7C 8C 9C 10C JC QC KC AC 14 | * 2D 3D 4D 5D 6D 7D 8D 9D 10D JD QD KD AD 15 | * 2H 3H 4H 5H 6H 7H 8H 9H 10H JH QH KH AH 16 | * 2S 3S 4S 5S 6S 7S 8S 9S 10S JS QS KS AS 17 | * 18 | * % java Shuffle < cards.txt 19 | * 6H 20 | * 9C 21 | * 8H 22 | * 7C 23 | * JS 24 | * ... 25 | * KH 26 | * 27 | *************************************************************************/ 28 | 29 | public class Shuffle { 30 | public static void main(String[] args) { 31 | 32 | // read in the data 33 | String[] a = StdIn.readAll().split("\\s+"); 34 | int N = a.length; 35 | 36 | // shuffle 37 | for (int i = 0; i < N; i++) { 38 | // int from remainder of deck 39 | int r = i + (int) (Math.random() * (N - i)); 40 | String swap = a[r]; 41 | a[r] = a[i]; 42 | a[i] = swap; 43 | } 44 | 45 | // print permutation 46 | for (int i = 0; i < N; i++) 47 | StdOut.println(a[i]); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /1-Fundamentals/1-1-BasicProgModel/cards.txt: -------------------------------------------------------------------------------- 1 | 2C 3C 4C 5C 6C 7C 8C 9C 10C JC QC KC AC 2 | 2D 3D 4D 5D 6D 7D 8D 9D 10D JD QD KD AD 3 | 2H 3H 4H 5H 6H 7H 8H 9H 10H JH QH KH AH 4 | 2S 3S 4S 5S 6S 7S 8S 9S 10S JS QS KS AS 5 | -------------------------------------------------------------------------------- /1-Fundamentals/1-1-BasicProgModel/in1.txt: -------------------------------------------------------------------------------- 1 | This is -------------------------------------------------------------------------------- /1-Fundamentals/1-1-BasicProgModel/in2.txt: -------------------------------------------------------------------------------- 1 | a tiny 2 | test. -------------------------------------------------------------------------------- /1-Fundamentals/1-1-BasicProgModel/tinyT.txt: -------------------------------------------------------------------------------- 1 | 23 2 | 50 3 | 10 4 | 99 5 | 18 6 | 23 7 | 98 8 | 84 9 | 11 10 | 10 11 | 48 12 | 77 13 | 13 14 | 54 15 | 98 16 | 77 17 | 77 18 | 68 19 | -------------------------------------------------------------------------------- /1-Fundamentals/1-1-BasicProgModel/tinyW.txt: -------------------------------------------------------------------------------- 1 | 84 2 | 48 3 | 68 4 | 10 5 | 18 6 | 98 7 | 12 8 | 23 9 | 54 10 | 57 11 | 48 12 | 33 13 | 16 14 | 77 15 | 11 16 | 29 17 | -------------------------------------------------------------------------------- /1-Fundamentals/1-2-DataAbstraction/Accumulator.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac Accumulator.java 3 | * 4 | * Mutable data type that calculates mean of data values. 5 | * 6 | *************************************************************************/ 7 | 8 | 9 | public class Accumulator { 10 | private double total; 11 | private int N; 12 | 13 | public void addDataValue(double val) { 14 | N++; 15 | total += val; 16 | } 17 | 18 | public double mean() { 19 | return total / N; 20 | } 21 | 22 | public String toString() { 23 | return "Mean (" + N + " values): " + String.format("%7.5f", mean()); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /1-Fundamentals/1-2-DataAbstraction/Counter.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac Counter.java 3 | * Execution: java Counter N T 4 | * Dependencies: StdRandom.java StdOut.java 5 | * 6 | * A mutable data type for an integer counter. 7 | * 8 | * The test clients create N counters and performs T increment 9 | * operations on random counters. 10 | * 11 | * % java Counter 6 600000 12 | * 0: 99870 13 | * 1: 99948 14 | * 2: 99738 15 | * 3: 100283 16 | * 4: 100185 17 | * 5: 99976 18 | * 19 | *************************************************************************/ 20 | 21 | public class Counter implements Comparable { 22 | 23 | private final String name; // counter name 24 | private int count; // current value 25 | 26 | // create a new counter 27 | public Counter(String id) { 28 | name = id; 29 | } 30 | 31 | // increment the counter by 1 32 | public void increment() { 33 | count++; 34 | } 35 | 36 | // return the current count 37 | public int tally() { 38 | return count; 39 | } 40 | 41 | // return a string representation of this counter 42 | public String toString() { 43 | return count + " " + name; 44 | } 45 | 46 | // compare two Counter objects based on their count 47 | public int compareTo(Counter that) { 48 | if (this.count < that.count) return -1; 49 | else if (this.count > that.count) return +1; 50 | else return 0; 51 | } 52 | 53 | 54 | // test client 55 | public static void main(String[] args) { 56 | int N = Integer.parseInt(args[0]); 57 | int T = Integer.parseInt(args[1]); 58 | 59 | // create N counters 60 | Counter[] hits = new Counter[N]; 61 | for (int i = 0; i < N; i++) { 62 | hits[i] = new Counter("counter" + i); 63 | } 64 | 65 | // increment T counters at random 66 | for (int t = 0; t < T; t++) { 67 | hits[StdRandom.uniform(N)].increment(); 68 | } 69 | 70 | // print results 71 | for (int i = 0; i < N; i++) { 72 | StdOut.println(hits[i]); 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /1-Fundamentals/1-2-DataAbstraction/Interval2D.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac Interval2D.java 3 | * Execution: java Interval2D 4 | * 5 | * 2-dimensional interval data type. 6 | * 7 | *************************************************************************/ 8 | 9 | public class Interval2D { 10 | private final Interval1D x; 11 | private final Interval1D y; 12 | 13 | public Interval2D(Interval1D x, Interval1D y) { 14 | this.x = x; 15 | this.y = y; 16 | } 17 | 18 | // does this interval intersect that one? 19 | public boolean intersects(Interval2D that) { 20 | if (!this.x.intersects(that.x)) return false; 21 | if (!this.y.intersects(that.y)) return false; 22 | return true; 23 | } 24 | 25 | // does this interval contain x? 26 | public boolean contains(Point2D p) { 27 | return x.contains(p.x()) && y.contains(p.y()); 28 | } 29 | 30 | // area of this interval 31 | public double area() { 32 | return x.length() * y.length(); 33 | } 34 | 35 | public String toString() { 36 | return x + " x " + y; 37 | } 38 | 39 | // test client 40 | public static void main(String[] args) { 41 | double xlo = Double.parseDouble(args[0]); 42 | double xhi = Double.parseDouble(args[1]); 43 | double ylo = Double.parseDouble(args[2]); 44 | double yhi = Double.parseDouble(args[3]); 45 | int T = Integer.parseInt(args[4]); 46 | 47 | Interval1D xinterval = new Interval1D(xlo, xhi); 48 | Interval1D yinterval = new Interval1D(ylo, yhi); 49 | Interval2D box = new Interval2D(xinterval, yinterval); 50 | 51 | double xc = (xhi + xlo) / 2.0; 52 | double yc = (yhi + ylo) / 2.0; 53 | StdDraw.rectangle(xc, yc, (xhi - xlo) / 2.0, (yhi - ylo) / 2.0); 54 | 55 | Counter counter = new Counter("hits"); 56 | for (int t = 0; t < T; t++) { 57 | double x = StdRandom.random(); 58 | double y = StdRandom.random(); 59 | Point2D p = new Point2D(x, y); 60 | 61 | if (box.contains(p)) counter.increment(); 62 | else p.draw(); 63 | } 64 | 65 | StdOut.println(counter); 66 | StdOut.printf("box area = %.2f\n", box.area()); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /1-Fundamentals/1-2-DataAbstraction/StaticSETofInts.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac StaticSetOfInts.java 3 | * 4 | * Data type to store a set of integers. 5 | * 6 | *************************************************************************/ 7 | 8 | import java.util.Arrays; 9 | 10 | public class StaticSETofInts { 11 | private int[] a; 12 | public StaticSETofInts(int[] keys) { 13 | // defensive copy 14 | a = new int[keys.length]; 15 | for (int i = 0; i < keys.length; i++) 16 | a[i] = keys[i]; 17 | 18 | Arrays.sort(a); 19 | 20 | // probably should check that no duplicates 21 | } 22 | 23 | public boolean contains(int key) { 24 | return rank(key) != -1; 25 | } 26 | 27 | // Binary search. 28 | public int rank(int key) { 29 | int lo = 0; 30 | int hi = a.length - 1; 31 | while (lo <= hi) { 32 | // Key is in a[lo..hi] or not present. 33 | int mid = lo + (hi - lo) / 2; 34 | if (key < a[mid]) hi = mid - 1; 35 | else if (key > a[mid]) lo = mid + 1; 36 | else return mid; 37 | } 38 | return -1; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /1-Fundamentals/1-2-DataAbstraction/TestVisualAccumulator.java: -------------------------------------------------------------------------------- 1 | 2 | public class TestVisualAccumulator 3 | { 4 | public static void main(String[] args) 5 | { 6 | int t = Integer.parseInt(args[0]); 7 | VisualAccumulator a = new VisualAccumulator(t, 1.0); 8 | for (int i = 0; i < t; i++) 9 | a.addDataValue(StdRandom.random()); 10 | StdOut.println(a); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /1-Fundamentals/1-2-DataAbstraction/VarianceAccumulator.java: -------------------------------------------------------------------------------- 1 | 2 | // Exercise 1.2.18 3 | public class VarianceAccumulator 4 | { 5 | private double m; 6 | private double s; 7 | private int n; 8 | 9 | public void addDataValue(double x) 10 | { 11 | n++; 12 | s = s + 1.0 * (n-1) / n * (x - m) * (x - m); 13 | m = m + (x - m) / n; 14 | } 15 | 16 | public double mean() 17 | { 18 | return m; 19 | } 20 | 21 | public double var() 22 | { 23 | return s/(n - 1); 24 | } 25 | 26 | public double stddev() 27 | { 28 | return Math.sqrt(var()); 29 | } 30 | 31 | public String toString() 32 | { 33 | return "Mean (" + n + " values): " + String.format("%7.5f", mean()); 34 | } 35 | 36 | public static void main(String[] args) 37 | { 38 | int n = Integer.parseInt(args[0]); 39 | 40 | VarianceAccumulator a = new VarianceAccumulator(); 41 | 42 | double[] v = new double[n]; 43 | double total = 0; 44 | 45 | for (int i = 0; i < n; i++) 46 | { 47 | double x = StdRandom.uniform(); 48 | v[i] = x; 49 | total += x; 50 | a.addDataValue(x); 51 | } 52 | 53 | double mean = total / n; 54 | 55 | double s = 0; 56 | for (int i = 0; i < n; i++) 57 | { 58 | double d = v[i] - mean; 59 | s += d * d; 60 | } 61 | 62 | double stddev = Math.sqrt(s / (n-1)); 63 | 64 | StdOut.println(a.mean() - mean); 65 | StdOut.println(a.stddev() - stddev); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /1-Fundamentals/1-2-DataAbstraction/VisualAccumulator.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac VisualAccumulator.java 3 | * 4 | *************************************************************************/ 5 | 6 | 7 | public class VisualAccumulator { 8 | private double total; 9 | private int N; 10 | 11 | public VisualAccumulator(int trials, double max) { 12 | StdDraw.setXscale(0, trials); 13 | StdDraw.setYscale(0, max); 14 | StdDraw.setPenRadius(.005); 15 | } 16 | 17 | public void addDataValue(double val) { 18 | N++; 19 | total += val; 20 | StdDraw.setPenColor(StdDraw.DARK_GRAY); 21 | StdDraw.point(N, val); 22 | StdDraw.setPenColor(StdDraw.RED); 23 | StdDraw.point(N, mean()); 24 | } 25 | 26 | public double mean() { 27 | return total / N; 28 | } 29 | 30 | public String toString() { 31 | return "Mean (" + N + " values): " + String.format("%8.5f", mean()); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /1-Fundamentals/1-2-DataAbstraction/Whitelist.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac Whitelist.java 3 | * Execution: java Whitelist whitelist.txt < data.txt 4 | * Dependencies: StaticSetOfInts.java In.java StdOut.java 5 | * Data files: http://algs4.cs.princeton.edu/11model/tinyW.txt 6 | * http://algs4.cs.princeton.edu/11model/tinyT.txt 7 | * http://algs4.cs.princeton.edu/11model/largeW.txt 8 | * http://algs4.cs.princeton.edu/11model/largeT.txt 9 | * 10 | * Whitelist filter. 11 | * 12 | * 13 | * % java Whitelist tinyW.txt < tinyT.txt 14 | * 50 15 | * 99 16 | * 13 17 | * 18 | * % java Whitelist largeW.txt < largeT.txt | more 19 | * 499569 20 | * 984875 21 | * 295754 22 | * 207807 23 | * 140925 24 | * 161828 25 | * [367,966 total values] 26 | * 27 | *************************************************************************/ 28 | 29 | public class Whitelist { 30 | public static void main(String[] args) { 31 | int[] w = In.readInts(args[0]); 32 | StaticSETofInts set = new StaticSETofInts(w); 33 | 34 | // Read key, print if not in whitelist. 35 | while (!StdIn.isEmpty()) { 36 | int key = StdIn.readInt(); 37 | if (!set.contains(key)) 38 | StdOut.println(key); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /1-Fundamentals/1-2-DataAbstraction/tinyT.txt: -------------------------------------------------------------------------------- 1 | 23 2 | 50 3 | 10 4 | 99 5 | 18 6 | 23 7 | 98 8 | 84 9 | 11 10 | 10 11 | 48 12 | 77 13 | 13 14 | 54 15 | 98 16 | 77 17 | 77 18 | 68 19 | -------------------------------------------------------------------------------- /1-Fundamentals/1-2-DataAbstraction/tinyW.txt: -------------------------------------------------------------------------------- 1 | 84 2 | 48 3 | 68 4 | 10 5 | 18 6 | 98 7 | 12 8 | 23 9 | 54 10 | 57 11 | 48 12 | 33 13 | 16 14 | 77 15 | 11 16 | 29 17 | -------------------------------------------------------------------------------- /1-Fundamentals/1-3-BagsQueuesStacks/Bag.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac Bag.java 3 | * Execution: java Bag < input.txt 4 | * 5 | * A generic bag or multiset, implemented using a linked list. 6 | * 7 | *************************************************************************/ 8 | 9 | import java.util.Iterator; 10 | import java.util.NoSuchElementException; 11 | 12 | /** 13 | * The Bag class represents a bag (or multiset) of 14 | * generic items. It supports insertion and iterating over the 15 | * items in arbitrary order. 16 | *

17 | * The add, isEmpty, and size operation 18 | * take constant time. Iteration takes time proportional to the number of items. 19 | *

20 | * For additional documentation, see Section 1.3 of 21 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 22 | */ 23 | public class Bag implements Iterable { 24 | private int N; // number of elements in bag 25 | private Node first; // beginning of bag 26 | 27 | // helper linked list class 28 | private class Node { 29 | private Item item; 30 | private Node next; 31 | } 32 | 33 | /** 34 | * Create an empty stack. 35 | */ 36 | public Bag() { 37 | first = null; 38 | N = 0; 39 | } 40 | 41 | /** 42 | * Is the BAG empty? 43 | */ 44 | public boolean isEmpty() { 45 | return first == null; 46 | } 47 | 48 | /** 49 | * Return the number of items in the bag. 50 | */ 51 | public int size() { 52 | return N; 53 | } 54 | 55 | /** 56 | * Add the item to the bag. 57 | */ 58 | public void add(Item item) { 59 | Node oldfirst = first; 60 | first = new Node(); 61 | first.item = item; 62 | first.next = oldfirst; 63 | N++; 64 | } 65 | 66 | 67 | /** 68 | * Return an iterator that iterates over the items in the bag. 69 | */ 70 | public Iterator iterator() { 71 | return new ListIterator(); 72 | } 73 | 74 | // an iterator, doesn't implement remove() since it's optional 75 | private class ListIterator implements Iterator { 76 | private Node current = first; 77 | 78 | public boolean hasNext() { return current != null; } 79 | public void remove() { throw new UnsupportedOperationException(); } 80 | 81 | public Item next() { 82 | if (!hasNext()) throw new NoSuchElementException(); 83 | Item item = current.item; 84 | current = current.next; 85 | return item; 86 | } 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /1-Fundamentals/1-3-BagsQueuesStacks/Evaluate.java: -------------------------------------------------------------------------------- 1 | 2 | /************************************************************************* 3 | * Compilation: javac Evaluate.java 4 | * Execution: java Evaluate 5 | * Dependencies: Stack.java 6 | * 7 | * Evaluates (fully parenthesized) arithmetic expressions using 8 | * Dijkstra's two-stack algorithm. 9 | * 10 | * % java Evaluate 11 | * ( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ) ) 12 | * 101.0 13 | * 14 | * % java Evaulate 15 | * ( ( 1 + sqrt ( 5 ) ) / 2.0 ) 16 | * 1.618033988749895 17 | * 18 | * 19 | * 20 | * Remarkably, Dijkstra's algorithm computes the same 21 | * answer if we put each operator *after* its two operands 22 | * instead of *between* them. 23 | * 24 | * % java Evaluate 25 | * ( 1 ( ( 2 3 + ) ( 4 5 * ) * ) + ) 26 | * 101.0 27 | * 28 | * Moreover, in such expressions, all parentheses are redundant! 29 | * Removing them yields an expression known as a postfix expression. 30 | * 1 2 3 + 4 5 * * + 31 | * 32 | * 33 | *************************************************************************/ 34 | 35 | public class Evaluate { 36 | public static void main(String[] args) { 37 | Stack ops = new Stack(); 38 | Stack vals = new Stack(); 39 | 40 | while (!StdIn.isEmpty()) { 41 | String s = StdIn.readString(); 42 | if (s.equals("(")) ; 43 | else if (s.equals("+")) ops.push(s); 44 | else if (s.equals("-")) ops.push(s); 45 | else if (s.equals("*")) ops.push(s); 46 | else if (s.equals("/")) ops.push(s); 47 | else if (s.equals("sqrt")) ops.push(s); 48 | else if (s.equals(")")) { 49 | String op = ops.pop(); 50 | double v = vals.pop(); 51 | if (op.equals("+")) v = vals.pop() + v; 52 | else if (op.equals("-")) v = vals.pop() - v; 53 | else if (op.equals("*")) v = vals.pop() * v; 54 | else if (op.equals("/")) v = vals.pop() / v; 55 | else if (op.equals("sqrt")) v = Math.sqrt(v); 56 | vals.push(v); 57 | } 58 | else vals.push(Double.parseDouble(s)); 59 | } 60 | StdOut.println(vals.pop()); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /1-Fundamentals/1-3-BagsQueuesStacks/EvaluatePostfix.java: -------------------------------------------------------------------------------- 1 | 2 | /************************************************************************* 3 | * Exercise 1.3.11 4 | * 5 | * % java EvaluatePostfix 6 | * 1 2 3 + 4 5 * * + 7 | * 101.0 8 | * 9 | * % java EvaluatePostfix 10 | * 1 5 sqrt + 2.0 / 11 | * 1.618033988749895 12 | * 13 | * % java EvaluatePostfix 14 | * 12 9 - 105 7 / * 15 | * 45.0 16 | * 17 | * % java InfixToPostfix | java EvaluatePostfix 18 | * ( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ) ) 19 | * 101.0 20 | * 21 | * % java InfixToPostfix | java EvaluatePostfix 22 | * ( ( 1 + sqrt ( 5 ) ) / 2.0 ) 23 | * 1.618033988749895 24 | * 25 | *************************************************************************/ 26 | 27 | public class EvaluatePostfix 28 | { 29 | public static void main(String[] args) 30 | { 31 | Stack vals = new Stack(); 32 | 33 | while (!StdIn.isEmpty()) 34 | { 35 | String s = StdIn.readString(); 36 | 37 | if (s.equals("(") || 38 | s.equals(")")) ; 39 | else if (s.equals("+") || 40 | s.equals("-") || 41 | s.equals("*") || 42 | s.equals("/") || 43 | s.equals("sqrt")) 44 | { 45 | double v = vals.pop(); 46 | 47 | if (s.equals("+")) v = vals.pop() + v; 48 | else if (s.equals("-")) v = vals.pop() - v; 49 | else if (s.equals("*")) v = vals.pop() * v; 50 | else if (s.equals("/")) v = vals.pop() / v; 51 | else if (s.equals("sqrt")) v = Math.sqrt(v); 52 | 53 | vals.push(v); 54 | } 55 | else 56 | vals.push(Double.parseDouble(s)); 57 | } 58 | 59 | StdOut.println(vals.pop()); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /1-Fundamentals/1-3-BagsQueuesStacks/Ex_1_3_03.java: -------------------------------------------------------------------------------- 1 | 2 | /************************************************************************* 3 | * Simulate a sequence of push and pop operations to find out 4 | * whether a certain sequence of pop's can occur 5 | * 6 | * % java Ex_1_3_03 7 | * 9 8 7 6 5 4 3 2 1 0 8 | * true (Unprinted: 0; Stack: [ ]) 9 | * 10 | * 4 3 2 1 0 9 8 7 6 5 11 | * true (Unprinted: 0; Stack: [ ]) 12 | * 13 | * 4 6 8 7 5 3 2 9 0 1 14 | * false (Unprinted: 2; Stack: [ 1 0 ]) 15 | * 16 | * 2 5 6 7 4 8 9 3 1 0 17 | * true (Unprinted: 0; Stack: [ ]) 18 | * 19 | * 4 3 2 1 0 5 6 7 8 9 20 | * true (Unprinted: 0; Stack: [ ]) 21 | * 22 | * 1 2 3 4 5 6 9 8 7 0 23 | * true (Unprinted: 0; Stack: [ ]) 24 | * 25 | * 0 4 6 5 3 8 1 7 2 9 26 | * false (Unprinted: 4; Stack: [ 9 7 2 1 ]) 27 | * 28 | * 1 4 7 9 8 6 5 3 0 2 29 | * false (Unprinted: 2; Stack: [ 2 0 ]) 30 | * 31 | * 2 1 4 3 6 5 8 7 9 0 32 | * true (Unprinted: 0; Stack: [ ]) 33 | * 34 | *************************************************************************/ 35 | 36 | public class Ex_1_3_03 37 | { 38 | public static void checkSequence(int[] v) 39 | { 40 | Stack s = new Stack(); 41 | int n = v.length; 42 | 43 | int i = 0, j = 0; 44 | while (i < n && j <= n) 45 | { 46 | if (!s.isEmpty() && s.peek() == v[i]) 47 | { 48 | StdOut.print(s.pop() + " "); 49 | i++; 50 | } 51 | else 52 | { 53 | if (j < n) 54 | s.push(j); 55 | j++; 56 | } 57 | } 58 | StdOut.println(); 59 | 60 | StdOut.printf("%s (Unprinted: %d; Stack: [ %s])\n", 61 | i == n && s.isEmpty(), n - i, s); 62 | } 63 | 64 | public static void main(String[] args) 65 | { 66 | String[] a = StdIn.readAll().split("\\s+"); 67 | 68 | int[] v = new int[a.length]; 69 | for (int i = 0; i < a.length; i++) 70 | v[i] = Integer.parseInt(a[i]); 71 | 72 | checkSequence(v); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /1-Fundamentals/1-3-BagsQueuesStacks/Ex_1_3_04.java: -------------------------------------------------------------------------------- 1 | 2 | /************************************************************************* 3 | * 4 | * % java Ex_1_3_04 5 | * [()]{}{[()()]()} 6 | * true 7 | * 8 | * % java Ex_1_3_04 9 | * [(]) 10 | * false 11 | * 12 | *************************************************************************/ 13 | 14 | public class Ex_1_3_04 15 | { 16 | public static boolean isBalanced(String s) 17 | { 18 | Stack open = new Stack(); 19 | int n = s.length(); 20 | 21 | for (int i = 0; i < n; i++) 22 | { 23 | char c = s.charAt(i); 24 | 25 | if (c == '(' || c == '[' || c == '{') 26 | open.push(c); 27 | else if ((c == ')' && (open.isEmpty() || open.pop() != '(')) || 28 | (c == ']' && (open.isEmpty() || open.pop() != '[')) || 29 | (c == '}' && (open.isEmpty() || open.pop() != '{'))) 30 | return false; 31 | } 32 | 33 | return open.isEmpty(); 34 | } 35 | 36 | public static void main(String[] args) 37 | { 38 | String s = StdIn.readAll().trim(); 39 | 40 | StdOut.println(isBalanced(s)); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /1-Fundamentals/1-3-BagsQueuesStacks/Ex_1_3_09.java: -------------------------------------------------------------------------------- 1 | 2 | /************************************************************************* 3 | * 4 | * % java Ex_1_3_09 5 | * 1 + 2 ) * 3 - 4 ) * 5 - 6 ) ) ) 6 | * ( ( 1 + 2 ) * ( ( 3 - 4 ) * ( 5 - 6 ) ) ) 7 | * 8 | * % java Ex_1_3_09 9 | * sqrt 1 + 2 ) ) 10 | * ( sqrt ( 1 + 2 ) ) 11 | * 12 | *************************************************************************/ 13 | 14 | public class Ex_1_3_09 15 | { 16 | public static void main(String[] args) 17 | { 18 | Stack ops = new Stack(); 19 | Stack vals = new Stack(); 20 | 21 | while (!StdIn.isEmpty()) 22 | { 23 | String s = StdIn.readString(); 24 | 25 | if (s.equals("(")) ; 26 | else if (s.equals("+") || 27 | s.equals("-") || 28 | s.equals("*") || 29 | s.equals("/") || 30 | s.equals("sqrt")) ops.push(s); 31 | else if (s.equals(")")) 32 | { 33 | String op = ops.pop(); 34 | String v = vals.pop(); 35 | 36 | if (op.equals("+") || 37 | op.equals("-") || 38 | op.equals("*") || 39 | op.equals("/")) 40 | v = String.format("( %s %s %s )", vals.pop(), op, v); 41 | else if (op.equals("sqrt")) 42 | v = String.format("( %s %s )", op, v); 43 | 44 | vals.push(v); 45 | } 46 | else vals.push(s); 47 | //else vals.push(((Double)Double.parseDouble(s)).toString()); 48 | } 49 | 50 | StdOut.println(vals.pop()); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /1-Fundamentals/1-3-BagsQueuesStacks/Ex_1_3_37.java: -------------------------------------------------------------------------------- 1 | 2 | /************************************************************************* 3 | * 4 | * Josephus problem 5 | * 6 | * % java Ex_1_3_37 7 2 7 | * 1 3 5 0 4 2 6 8 | * 9 | *************************************************************************/ 10 | 11 | public class Ex_1_3_37 12 | { 13 | public static void main(String[] args) 14 | { 15 | int n = Integer.parseInt(args[0]), 16 | m = Integer.parseInt(args[1]); 17 | 18 | Queue q = new Queue(); 19 | for (int i = 0; i < n; i++) 20 | q.enqueue(new Integer(i)); 21 | 22 | int k = 0; 23 | while (!q.isEmpty()) 24 | { 25 | int x = q.dequeue(); 26 | 27 | if (++k % m == 0) 28 | StdOut.print(x + " "); 29 | else 30 | q.enqueue(x); 31 | } 32 | StdOut.println(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /1-Fundamentals/1-3-BagsQueuesStacks/FixedCapacityStack.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac FixedCapacityStack.java 3 | * Execution: java FixedCapacityStack 4 | * 5 | * Generic stack implementation with a fixed-size array. 6 | * 7 | * % more tobe.txt 8 | * to be or not to - be - - that - - - is 9 | * 10 | * % java FixedCapacityStack 5 < tobe.txt 11 | * to be not that or be 12 | * 13 | * Remark: bare-bones implementation. Does not do repeated 14 | * doubling or null out empty array entries to avoid loitering. 15 | * 16 | *************************************************************************/ 17 | 18 | import java.util.Iterator; 19 | 20 | public class FixedCapacityStack implements Iterable { 21 | private Item[] a; // holds the items 22 | private int N; // number of items in stack 23 | 24 | // create an empty stack with given capacity 25 | public FixedCapacityStack(int capacity) { 26 | a = (Item[]) new Object[capacity]; // no generic array creation 27 | } 28 | 29 | public boolean isEmpty() { return (N == 0); } 30 | public void push(Item item) { a[N++] = item; } 31 | public Item pop() { return a[--N]; } 32 | public Iterator iterator() { return new ReverseArrayIterator(); } 33 | 34 | 35 | public class ReverseArrayIterator implements Iterator { 36 | private int i = N-1; 37 | 38 | public boolean hasNext() { return i >= 0; } 39 | public Item next() { return a[i--]; } 40 | public void remove() { throw new UnsupportedOperationException(); } 41 | } 42 | 43 | 44 | public static void main(String[] args) { 45 | int max = Integer.parseInt(args[0]); 46 | FixedCapacityStack stack = new FixedCapacityStack(max); 47 | while (!StdIn.isEmpty()) { 48 | String item = StdIn.readString(); 49 | if (!item.equals("-")) stack.push(item); 50 | else if (stack.isEmpty()) StdOut.println("BAD INPUT"); 51 | else StdOut.print(stack.pop() + " "); 52 | } 53 | StdOut.println(); 54 | 55 | // print what's left on the stack 56 | StdOut.print("Left on stack: "); 57 | for (String s : stack) { 58 | StdOut.print(s + " "); 59 | } 60 | StdOut.println(); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /1-Fundamentals/1-3-BagsQueuesStacks/FixedCapacityStackOfStrings.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac FixedCapacityStackOfStrings.java 3 | * Execution: java FixedCapacityStackOfStrings 4 | * 5 | * Stack of strings implementation with a fixed-size array. 6 | * 7 | * % more tobe.txt 8 | * to be or not to - be - - that - - - is 9 | * 10 | * % java FixedCapacityStackOfStrings 5 < tobe.txt 11 | * to be not that or be 12 | * 13 | * Remark: bare-bones implementation. Does not do repeated 14 | * doubling or null out empty array entries to avoid loitering. 15 | * 16 | *************************************************************************/ 17 | 18 | import java.util.Iterator; 19 | 20 | public class FixedCapacityStackOfStrings implements Iterable { 21 | private String[] a; // holds the items 22 | private int N; // number of items in stack 23 | 24 | // create an empty stack with given capacity 25 | public FixedCapacityStackOfStrings(int capacity) { 26 | a = new String[capacity]; 27 | } 28 | 29 | public boolean isEmpty() { return (N == 0); } 30 | public boolean isFull() { return (N == a.length); } 31 | public void push(String item) { a[N++] = item; } 32 | public String pop() { return a[--N]; } 33 | public Iterator iterator() { return new ReverseArrayIterator(); } 34 | 35 | 36 | public class ReverseArrayIterator implements Iterator { 37 | private int i = N-1; 38 | 39 | public boolean hasNext() { return i >= 0; } 40 | public String next() { return a[i--]; } 41 | public void remove() { throw new UnsupportedOperationException(); } 42 | } 43 | 44 | 45 | public static void main(String[] args) { 46 | int max = Integer.parseInt(args[0]); 47 | FixedCapacityStackOfStrings stack = new FixedCapacityStackOfStrings(max); 48 | while (!StdIn.isEmpty()) { 49 | String item = StdIn.readString(); 50 | if (!item.equals("-")) stack.push(item); 51 | else if (stack.isEmpty()) StdOut.println("BAD INPUT"); 52 | else StdOut.print(stack.pop() + " "); 53 | } 54 | StdOut.println(); 55 | 56 | // print what's left on the stack 57 | StdOut.print("Left on stack: "); 58 | for (String s : stack) { 59 | StdOut.print(s + " "); 60 | } 61 | StdOut.println(); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /1-Fundamentals/1-3-BagsQueuesStacks/InfixToPostfix.java: -------------------------------------------------------------------------------- 1 | 2 | /************************************************************************* 3 | * Exercise 1.3.10 4 | * 5 | * % java InfixToPostfix 6 | * ( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ) ) 7 | * 1 2 3 + 4 5 * * + 8 | * 9 | * % java InfixToPostfix 10 | * ( sqrt ( 1 + 2 ) ) 11 | * 1 2 + sqrt 12 | * 13 | *************************************************************************/ 14 | 15 | public class InfixToPostfix 16 | { 17 | public static void main(String[] args) 18 | { 19 | Stack ops = new Stack(); 20 | Stack vals = new Stack(); 21 | 22 | while (!StdIn.isEmpty()) 23 | { 24 | String s = StdIn.readString(); 25 | 26 | if (s.equals("(")) ; 27 | else if (s.equals("+") || 28 | s.equals("-") || 29 | s.equals("*") || 30 | s.equals("/") || 31 | s.equals("sqrt")) ops.push(s); 32 | else if (s.equals(")")) 33 | { 34 | String op = ops.pop(); 35 | String v = vals.pop(); 36 | 37 | if (op.equals("+") || 38 | op.equals("-") || 39 | op.equals("*") || 40 | op.equals("/")) 41 | v = String.format("%s %s %s", vals.pop(), v, op); 42 | else if (op.equals("sqrt")) 43 | v = String.format("%s %s", v, op); 44 | 45 | vals.push(v); 46 | } 47 | else vals.push(s); 48 | } 49 | 50 | StdOut.println(vals.pop()); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /1-Fundamentals/1-3-BagsQueuesStacks/Parentheses.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac Parentheses.java 3 | * Execution: java Parentheses 4 | * Dependencies: In.java Stack.java 5 | * 6 | * Reads in a text file and checks to see if the parentheses are balanced. 7 | * 8 | * % java Parentheses 9 | * [()]{}{[()()]()} 10 | * true 11 | * 12 | * % java Parentheses 13 | * [(]) 14 | * false 15 | * 16 | *************************************************************************/ 17 | 18 | public class Parentheses { 19 | private static final char LEFT_PAREN = '('; 20 | private static final char RIGHT_PAREN = ')'; 21 | private static final char LEFT_BRACE = '{'; 22 | private static final char RIGHT_BRACE = '}'; 23 | private static final char LEFT_BRACKET = '['; 24 | private static final char RIGHT_BRACKET = ']'; 25 | 26 | public static boolean isBalanced(String s) { 27 | Stack stack = new Stack(); 28 | for (int i = 0; i < s.length(); i++) { 29 | if (s.charAt(i) == LEFT_PAREN) stack.push(LEFT_PAREN); 30 | if (s.charAt(i) == LEFT_BRACE) stack.push(LEFT_BRACE); 31 | if (s.charAt(i) == LEFT_BRACKET) stack.push(LEFT_BRACKET); 32 | 33 | if (s.charAt(i) == RIGHT_PAREN) { 34 | if (stack.isEmpty()) return false; 35 | if (stack.pop() != LEFT_PAREN) return false; 36 | } 37 | 38 | else if (s.charAt(i) == RIGHT_BRACE) { 39 | if (stack.isEmpty()) return false; 40 | if (stack.pop() != LEFT_BRACE) return false; 41 | } 42 | 43 | else if (s.charAt(i) == RIGHT_BRACKET) { 44 | if (stack.isEmpty()) return false; 45 | if (stack.pop() != LEFT_BRACKET) return false; 46 | } 47 | } 48 | return stack.isEmpty(); 49 | } 50 | 51 | 52 | public static void main(String[] args) { 53 | In in = new In(); 54 | String s = in.readAll().trim(); 55 | StdOut.println(isBalanced(s)); 56 | } 57 | } 58 | 59 | -------------------------------------------------------------------------------- /1-Fundamentals/1-3-BagsQueuesStacks/ResizingArrayStack.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac ResizingArrayStack.java 3 | * Execution: java ResizingArrayStack < input.txt 4 | * Data files: http://algs4.cs.princeton.edu/13stacks/tobe.txt 5 | * 6 | * Stack implementation with a resizing array. 7 | * 8 | * % more tobe.txt 9 | * to be or not to - be - - that - - - is 10 | * 11 | * % java ResizingArrayStack < tobe.txt 12 | * to be not that or be (2 left on stack) 13 | * 14 | *************************************************************************/ 15 | 16 | import java.util.Iterator; 17 | import java.util.NoSuchElementException; 18 | 19 | // suppress unchecked warnings in Java 1.5.0_6 and later 20 | @SuppressWarnings("unchecked") 21 | 22 | public class ResizingArrayStack implements Iterable { 23 | private Item[] a; // array of items 24 | private int N = 0; // number of elements on stack 25 | 26 | // create an empty stack 27 | public ResizingArrayStack() { 28 | a = (Item[]) new Object[2]; 29 | } 30 | 31 | public boolean isEmpty() { return N == 0; } 32 | public int size() { return N; } 33 | 34 | 35 | 36 | // resize the underlying array holding the elements 37 | private void resize(int capacity) { 38 | assert capacity >= N; 39 | Item[] temp = (Item[]) new Object[capacity]; 40 | for (int i = 0; i < N; i++) 41 | temp[i] = a[i]; 42 | a = temp; 43 | } 44 | 45 | // push a new item onto the stack 46 | public void push(Item item) { 47 | if (N == a.length) resize(2*a.length); // double size of array if necessary 48 | a[N++] = item; // add item 49 | } 50 | 51 | // delete and return the item most recently added 52 | public Item pop() { 53 | if (isEmpty()) { throw new RuntimeException("Stack underflow error"); } 54 | Item item = a[N-1]; 55 | a[N-1] = null; // to avoid loitering 56 | N--; 57 | // shrink size of array if necessary 58 | if (N > 0 && N == a.length/4) resize(a.length/2); 59 | return item; 60 | } 61 | 62 | 63 | public Iterator iterator() { return new LIFOIterator(); } 64 | 65 | // an iterator, doesn't implement remove() since it's optional 66 | private class LIFOIterator implements Iterator { 67 | private int i = N; 68 | public boolean hasNext() { return i > 0; } 69 | public void remove() { throw new UnsupportedOperationException(); } 70 | 71 | public Item next() { 72 | if (!hasNext()) throw new NoSuchElementException(); 73 | return a[--i]; 74 | } 75 | } 76 | 77 | 78 | 79 | /*********************************************************************** 80 | * Test routine. 81 | **********************************************************************/ 82 | public static void main(String[] args) { 83 | ResizingArrayStack s = new ResizingArrayStack(); 84 | while (!StdIn.isEmpty()) { 85 | String item = StdIn.readString(); 86 | if (!item.equals("-")) s.push(item); 87 | else if (!s.isEmpty()) StdOut.print(s.pop() + " "); 88 | } 89 | StdOut.println("(" + s.size() + " left on stack)"); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /1-Fundamentals/1-3-BagsQueuesStacks/Stats.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac Stats.java 3 | * Execution: java Stats < input.txt 4 | * Dependencies: Bag.java StdIn.java StdOut.java 5 | * 6 | * Reads in a sequence of real numbers from standard input and 7 | * computes their mean and standard deviation. 8 | * 9 | * % java Stats 10 | * 100 99 101 120 98 107 109 81 101 90 11 | * Mean: 100.60 12 | * Std dev: 10.51 13 | * 14 | *************************************************************************/ 15 | 16 | public class Stats { 17 | public static void main(String[] args) { 18 | 19 | // read in numbers 20 | Bag numbers = new Bag(); 21 | while (!StdIn.isEmpty()) { 22 | numbers.add(StdIn.readDouble()); 23 | } 24 | int N = numbers.size(); 25 | 26 | // compute mean 27 | double sum = 0.0; 28 | for (double x : numbers) 29 | sum += x; 30 | double mean = sum/N; 31 | 32 | // compute standard deviation 33 | sum = 0.0; 34 | for (double x : numbers) { 35 | sum += (x - mean) * (x - mean); 36 | } 37 | double std = Math.sqrt(sum/(N-1)); 38 | 39 | StdOut.printf("Mean: %.2f\n", mean); 40 | StdOut.printf("Std dev: %.2f\n", std); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /1-Fundamentals/1-3-BagsQueuesStacks/tobe.txt: -------------------------------------------------------------------------------- 1 | to be or not to - be - - that - - - is 2 | -------------------------------------------------------------------------------- /1-Fundamentals/1-4-AnalysisOfAlgorithms/DoublingRatio.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac DoublingRatio.java 3 | * Execution: java DoublingRatio 4 | * Dependencies: ThreeSum.java Stopwatch.java StdRandom.java StdOut.java 5 | * 6 | * 7 | * % java DoublingTest 8 | * 512 6.48 9 | * 1024 8.30 10 | * 2048 7.75 11 | * 4096 8.00 12 | * 8192 8.05 13 | * ... 14 | * 15 | *************************************************************************/ 16 | 17 | public class DoublingRatio { 18 | 19 | public static double timeTrial(int N) { 20 | int MAX = 1000000; 21 | int[] a = new int[N]; 22 | for (int i = 0; i < N; i++) { 23 | a[i] = StdRandom.uniform(-MAX, MAX); 24 | } 25 | Stopwatch s = new Stopwatch(); 26 | int cnt = ThreeSum.count(a); 27 | return s.elapsedTime(); 28 | } 29 | 30 | 31 | public static void main(String[] args) { 32 | double prev = timeTrial(125); 33 | for (int N = 250; true; N += N) { 34 | double time = timeTrial(N); 35 | StdOut.printf("%6d %7.1f %5.1f\n", N, time, time/prev); 36 | prev = time; 37 | } 38 | } 39 | } 40 | 41 | -------------------------------------------------------------------------------- /1-Fundamentals/1-4-AnalysisOfAlgorithms/DoublingTest.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac DoublingTest.java 3 | * Execution: java DoublingTest 4 | * Dependencies: ThreeSum.java Stopwatch.java StdRandom.java StdOut.java 5 | * 6 | * % java DoublingTest 7 | * 512 6.48 8 | * 1024 8.30 9 | * 2048 7.75 10 | * 4096 8.00 11 | * 8192 8.05 12 | * ... 13 | * 14 | *************************************************************************/ 15 | 16 | public class DoublingTest { 17 | 18 | public static double timeTrial(int N) { 19 | int MAX = 1000000; 20 | int[] a = new int[N]; 21 | for (int i = 0; i < N; i++) { 22 | a[i] = StdRandom.uniform(-MAX, MAX); 23 | } 24 | Stopwatch s = new Stopwatch(); 25 | int cnt = ThreeSum.count(a); 26 | return s.elapsedTime(); 27 | } 28 | 29 | 30 | public static void main(String[] args) { 31 | for (int N = 250; true; N += N) { 32 | double time = timeTrial(N); 33 | StdOut.printf("%7d %5.1f\n", N, time); 34 | } 35 | } 36 | } 37 | 38 | -------------------------------------------------------------------------------- /1-Fundamentals/1-4-AnalysisOfAlgorithms/Stopwatch.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac Stopwatch.java 3 | * 4 | * 5 | *************************************************************************/ 6 | 7 | /** 8 | * Stopwatch. This class is a data type for measuring 9 | * the running time (wall clock) of a program. 10 | *

11 | * For additional documentation, see 12 | * Section 3.2 of 13 | * Introduction to Programming in Java: An Interdisciplinary Approach 14 | * by Robert Sedgewick and Kevin Wayne. 15 | */ 16 | 17 | 18 | 19 | public class Stopwatch { 20 | 21 | private final long start; 22 | 23 | /** 24 | * Create a stopwatch object. 25 | */ 26 | public Stopwatch() { 27 | start = System.currentTimeMillis(); 28 | } 29 | 30 | 31 | /** 32 | * Return elapsed time (in seconds) since this object was created. 33 | */ 34 | public double elapsedTime() { 35 | long now = System.currentTimeMillis(); 36 | return (now - start) / 1000.0; 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /1-Fundamentals/1-4-AnalysisOfAlgorithms/ThreeSum.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac ThreeSum.java 3 | * Execution: java ThreeSum input.txt 4 | * Data files: http://algs4.cs.princeton.edu/14analysis/1Kints.txt 5 | * http://algs4.cs.princeton.edu/14analysis/2Kints.txt 6 | * http://algs4.cs.princeton.edu/14analysis/4Kints.txt 7 | * http://algs4.cs.princeton.edu/14analysis/8Kints.txt 8 | * http://algs4.cs.princeton.edu/14analysis/16Kints.txt 9 | * http://algs4.cs.princeton.edu/14analysis/32Kints.txt 10 | * http://algs4.cs.princeton.edu/14analysis/1Mints.txt 11 | * 12 | * A program with cubic running time. Read in N integers 13 | * and counts the number of triples that sum to exactly 0 14 | * (ignoring integer overflow). 15 | * 16 | * % java ThreeSum 1Kints.txt 17 | * 70 18 | * 19 | * % java ThreeSum 2Kints.txt 20 | * 528 21 | * 22 | * % java ThreeSum 4Kints.txt 23 | * 4039 24 | * 25 | *************************************************************************/ 26 | 27 | public class ThreeSum { 28 | 29 | // print distinct triples (i, j, k) such that a[i] + a[j] + a[k] = 0 30 | public static void printAll(int[] a) { 31 | int N = a.length; 32 | for (int i = 0; i < N; i++) { 33 | for (int j = i+1; j < N; j++) { 34 | for (int k = j+1; k < N; k++) { 35 | if (a[i] + a[j] + a[k] == 0) { 36 | StdOut.println(a[i] + " " + a[j] + " " + a[k]); 37 | } 38 | } 39 | } 40 | } 41 | } 42 | 43 | // return number of distinct triples (i, j, k) such that a[i] + a[j] + a[k] = 0 44 | public static int count(int[] a) { 45 | int N = a.length; 46 | int cnt = 0; 47 | for (int i = 0; i < N; i++) { 48 | for (int j = i+1; j < N; j++) { 49 | for (int k = j+1; k < N; k++) { 50 | if (a[i] + a[j] + a[k] == 0) { 51 | cnt++; 52 | } 53 | } 54 | } 55 | } 56 | return cnt; 57 | } 58 | 59 | public static void main(String[] args) { 60 | int[] a = In.readInts(args[0]); 61 | 62 | Stopwatch timer = new Stopwatch(); 63 | int cnt = count(a); 64 | StdOut.println("elapsed time = " + timer.elapsedTime()); 65 | StdOut.println(cnt); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /1-Fundamentals/1-4-AnalysisOfAlgorithms/ThreeSumFast.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac ThreeSumFast.java 3 | * Execution: java ThreeSumFast input.txt 4 | * Data files: http://algs4.cs.princeton.edu/14analysis/1Kints.txt 5 | * http://algs4.cs.princeton.edu/14analysis/2Kints.txt 6 | * http://algs4.cs.princeton.edu/14analysis/4Kints.txt 7 | * http://algs4.cs.princeton.edu/14analysis/8Kints.txt 8 | * http://algs4.cs.princeton.edu/14analysis/16Kints.txt 9 | * http://algs4.cs.princeton.edu/14analysis/32Kints.txt 10 | * http://algs4.cs.princeton.edu/14analysis/1Mints.txt 11 | * 12 | * A program with N^2 log N running time. Read in N integers 13 | * and counts the number of triples that sum to exactly 0. 14 | * 15 | * Limitations 16 | * ----------- 17 | * - we ignore integer overflow 18 | * - doesn't handle case when input has duplicates 19 | * 20 | * 21 | * % java ThreeSumFast 1Kints.txt 22 | * 70 23 | * 24 | * % java ThreeSumFast 2Kints.txt 25 | * 528 26 | * 27 | * % java ThreeSumFast 4Kints.txt 28 | * 4039 29 | * 30 | * % java ThreeSumFast 8Kints.txt 31 | * 32074 32 | * 33 | * % java ThreeSumFast 16Kints.txt 34 | * 255181 35 | * 36 | * % java ThreeSumFast 32Kints.txt 37 | * 2052358 38 | * 39 | *************************************************************************/ 40 | 41 | import java.util.Arrays; 42 | 43 | public class ThreeSumFast { 44 | 45 | // print distinct triples (i, j, k) such that a[i] + a[j] + a[k] = 0 46 | public static void printAll(int[] a) { 47 | int N = a.length; 48 | Arrays.sort(a); 49 | for (int i = 0; i < N; i++) { 50 | for (int j = i+1; j < N; j++) { 51 | int k = Arrays.binarySearch(a, -(a[i] + a[j])); 52 | if (k > j) StdOut.println(a[i] + " " + a[j] + " " + a[k]); 53 | } 54 | } 55 | } 56 | 57 | // return number of distinct triples (i, j, k) such that a[i] + a[j] + a[k] = 0 58 | public static int count(int[] a) { 59 | int N = a.length; 60 | Arrays.sort(a); 61 | int cnt = 0; 62 | for (int i = 0; i < N; i++) { 63 | for (int j = i+1; j < N; j++) { 64 | int k = Arrays.binarySearch(a, -(a[i] + a[j])); 65 | if (k > j) cnt++; 66 | } 67 | } 68 | return cnt; 69 | } 70 | 71 | public static void main(String[] args) { 72 | int[] a = In.readInts(args[0]); 73 | int cnt = count(a); 74 | StdOut.println(cnt); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /1-Fundamentals/1-5-UnionFind/QuickFindUF.java: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * Compilation: javac QuickFindUF.java 3 | * Execution: java QuickFindUF < input.txt 4 | * Dependencies: StdIn.java StdOut.java 5 | * 6 | * Quick-find algorithm. 7 | * 8 | ****************************************************************************/ 9 | 10 | public class QuickFindUF { 11 | private int[] id; 12 | private int count; 13 | 14 | // instantiate N isolated components 0 through N-1 15 | public QuickFindUF(int N) { 16 | count = N; 17 | id = new int[N]; 18 | for (int i = 0; i < N; i++) 19 | id[i] = i; 20 | } 21 | 22 | // return number of connected components 23 | public int count() { 24 | return count; 25 | } 26 | 27 | // Return component identifier for component containing p 28 | public int find(int p) { 29 | return id[p]; 30 | } 31 | 32 | // are elements p and q in the same component? 33 | public boolean connected(int p, int q) { 34 | return id[p] == id[q]; 35 | } 36 | 37 | // merge components containing p and q 38 | public void union(int p, int q) { 39 | if (connected(p, q)) return; 40 | int pid = id[p]; 41 | for (int i = 0; i < id.length; i++) 42 | if (id[i] == pid) id[i] = id[q]; 43 | count--; 44 | } 45 | 46 | public static void main(String[] args) { 47 | int N = StdIn.readInt(); 48 | QuickFindUF uf = new QuickFindUF(N); 49 | 50 | // read in a sequence of pairs of integers (each in the range 0 to N-1), 51 | // calling find() for each pair: If the members of the pair are not already 52 | // call union() and print the pair. 53 | while (!StdIn.isEmpty()) { 54 | int p = StdIn.readInt(); 55 | int q = StdIn.readInt(); 56 | if (uf.connected(p, q)) continue; 57 | uf.union(p, q); 58 | StdOut.println(p + " " + q); 59 | } 60 | StdOut.println("# components: " + uf.count()); 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /1-Fundamentals/1-5-UnionFind/QuickUnionUF.java: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * Compilation: javac QuickUnionUF.java 3 | * Execution: java QuickUnionUF < input.txt 4 | * Dependencies: StdIn.java StdOut.java 5 | * 6 | * Quick-union algorithm. 7 | * 8 | ****************************************************************************/ 9 | 10 | public class QuickUnionUF { 11 | private int[] id; // id[i] = parent of i 12 | private int count; // number of components 13 | 14 | // instantiate N isolated components 0 through N-1 15 | public QuickUnionUF(int N) { 16 | id = new int[N]; 17 | count = N; 18 | for (int i = 0; i < N; i++) { 19 | id[i] = i; 20 | } 21 | } 22 | 23 | // return number of connected components 24 | public int count() { 25 | return count; 26 | } 27 | 28 | // return root of component corresponding to element p 29 | public int find(int p) { 30 | while (p != id[p]) 31 | p = id[p]; 32 | return p; 33 | } 34 | 35 | // are elements p and q in the same component? 36 | public boolean connected(int p, int q) { 37 | return find(p) == find(q); 38 | } 39 | 40 | // merge components containing p and q 41 | public void union(int p, int q) { 42 | int i = find(p); 43 | int j = find(q); 44 | if (i == j) return; 45 | id[i] = j; 46 | count--; 47 | } 48 | 49 | public static void main(String[] args) { 50 | int N = StdIn.readInt(); 51 | QuickUnionUF uf = new QuickUnionUF(N); 52 | 53 | // read in a sequence of pairs of integers (each in the range 0 to N-1), 54 | // calling find() for each pair: If the members of the pair are not already 55 | // call union() and print the pair. 56 | while (!StdIn.isEmpty()) { 57 | int p = StdIn.readInt(); 58 | int q = StdIn.readInt(); 59 | if (uf.connected(p, q)) continue; 60 | uf.union(p, q); 61 | StdOut.println(p + " " + q); 62 | } 63 | StdOut.println("# components: " + uf.count()); 64 | } 65 | 66 | 67 | } 68 | -------------------------------------------------------------------------------- /1-Fundamentals/1-5-UnionFind/WeightedQuickUnionUF.java: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * Compilation: javac WeightedQuickUnionUF.java 3 | * Execution: java WeightedQuickUnionUF < input.txt 4 | * Dependencies: StdIn.java StdOut.java 5 | * 6 | * Weighted quick-union (without path compression). 7 | * 8 | ****************************************************************************/ 9 | 10 | public class WeightedQuickUnionUF { 11 | private int[] id; // id[i] = parent of i 12 | private int[] sz; // sz[i] = number of objects in subtree rooted at i 13 | private int count; // number of components 14 | 15 | // Create an empty union find data structure with N isolated sets. 16 | public WeightedQuickUnionUF(int N) { 17 | count = N; 18 | id = new int[N]; 19 | sz = new int[N]; 20 | for (int i = 0; i < N; i++) { 21 | id[i] = i; 22 | sz[i] = 1; 23 | } 24 | } 25 | 26 | // Return the number of disjoint sets. 27 | public int count() { 28 | return count; 29 | } 30 | 31 | // Return component identifier for component containing p 32 | public int find(int p) { 33 | while (p != id[p]) 34 | p = id[p]; 35 | return p; 36 | } 37 | 38 | // Are objects p and q in the same set? 39 | public boolean connected(int p, int q) { 40 | return find(p) == find(q); 41 | } 42 | 43 | 44 | // Replace sets containing p and q with their union. 45 | public void union(int p, int q) { 46 | int i = find(p); 47 | int j = find(q); 48 | if (i == j) return; 49 | 50 | // make smaller root point to larger one 51 | if (sz[i] < sz[j]) { id[i] = j; sz[j] += sz[i]; } 52 | else { id[j] = i; sz[i] += sz[j]; } 53 | count--; 54 | } 55 | 56 | 57 | public static void main(String[] args) { 58 | int N = StdIn.readInt(); 59 | WeightedQuickUnionUF uf = new WeightedQuickUnionUF(N); 60 | 61 | // read in a sequence of pairs of integers (each in the range 0 to N-1), 62 | // calling find() for each pair: If the members of the pair are not already 63 | // call union() and print the pair. 64 | while (!StdIn.isEmpty()) { 65 | int p = StdIn.readInt(); 66 | int q = StdIn.readInt(); 67 | if (uf.connected(p, q)) continue; 68 | uf.union(p, q); 69 | StdOut.println(p + " " + q); 70 | } 71 | StdOut.println("# components: " + uf.count()); 72 | } 73 | 74 | } 75 | 76 | -------------------------------------------------------------------------------- /1-Fundamentals/1-5-UnionFind/tinyUF.txt: -------------------------------------------------------------------------------- 1 | 10 2 | 4 3 3 | 3 8 4 | 6 5 5 | 9 4 6 | 2 1 7 | 8 9 8 | 5 0 9 | 7 2 10 | 6 1 11 | 1 0 12 | 6 7 13 | -------------------------------------------------------------------------------- /2-Sorting/2-1-ElementarySorts/tiny.txt: -------------------------------------------------------------------------------- 1 | S O R T E X A M P L E 2 | -------------------------------------------------------------------------------- /2-Sorting/2-1-ElementarySorts/words3.txt: -------------------------------------------------------------------------------- 1 | bed bug dad yes zoo 2 | now for tip ilk dim 3 | tag jot sob nob sky 4 | hut men egg few jay 5 | owl joy rap gig wee 6 | was wad fee tap tar 7 | dug jam all bad yet 8 | -------------------------------------------------------------------------------- /2-Sorting/2-2-Mergesort/tiny.txt: -------------------------------------------------------------------------------- 1 | S O R T E X A M P L E 2 | -------------------------------------------------------------------------------- /2-Sorting/2-2-Mergesort/words3.txt: -------------------------------------------------------------------------------- 1 | bed bug dad yes zoo 2 | now for tip ilk dim 3 | tag jot sob nob sky 4 | hut men egg few jay 5 | owl joy rap gig wee 6 | was wad fee tap tar 7 | dug jam all bad yet 8 | -------------------------------------------------------------------------------- /2-Sorting/2-3-Quicksort/tiny.txt: -------------------------------------------------------------------------------- 1 | S O R T E X A M P L E 2 | -------------------------------------------------------------------------------- /2-Sorting/2-3-Quicksort/words3.txt: -------------------------------------------------------------------------------- 1 | bed bug dad yes zoo 2 | now for tip ilk dim 3 | tag jot sob nob sky 4 | hut men egg few jay 5 | owl joy rap gig wee 6 | was wad fee tap tar 7 | dug jam all bad yet 8 | -------------------------------------------------------------------------------- /2-Sorting/2-4-PriorityQueues/Heap.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac Heap.java 3 | * Execution: java Heap < input.txt 4 | * Dependencies: StdOut.java StdIn.java 5 | * Data files: http://algs4.cs.princeton.edu/24pq/tiny.txt 6 | * http://algs4.cs.princeton.edu/24pq/words3.txt 7 | * 8 | * Sorts a sequence of strings from standard input using heapsort. 9 | * 10 | * % more tiny.txt 11 | * S O R T E X A M P L E 12 | * 13 | * % java Heap < tiny.txt 14 | * S O R T E X A M P L E A [ one string per line ] 15 | * 16 | * % more words3.txt 17 | * bed bug dad yes zoo ... all bad yet 18 | * 19 | * % java Heap < words3.txt 20 | * all bad bed bug dad ... yes yet zoo [ one string per line ] 21 | * 22 | *************************************************************************/ 23 | 24 | public class Heap { 25 | 26 | public static void sort(Comparable[] pq) { 27 | int N = pq.length; 28 | for (int k = N/2; k >= 1; k--) 29 | sink(pq, k, N); 30 | while (N > 1) { 31 | exch(pq, 1, N--); 32 | sink(pq, 1, N); 33 | } 34 | } 35 | 36 | /*********************************************************************** 37 | * Helper functions to restore the heap invariant. 38 | **********************************************************************/ 39 | 40 | private static void sink(Comparable[] pq, int k, int N) { 41 | while (2*k <= N) { 42 | int j = 2*k; 43 | if (j < N && less(pq, j, j+1)) j++; 44 | if (!less(pq, k, j)) break; 45 | exch(pq, k, j); 46 | k = j; 47 | } 48 | } 49 | 50 | /*********************************************************************** 51 | * Helper functions for comparisons and swaps. 52 | * Indices are "off-by-one" to support 1-based indexing. 53 | **********************************************************************/ 54 | private static boolean less(Comparable[] pq, int i, int j) { 55 | return pq[i-1].compareTo(pq[j-1]) < 0; 56 | } 57 | 58 | private static void exch(Object[] pq, int i, int j) { 59 | Object swap = pq[i-1]; 60 | pq[i-1] = pq[j-1]; 61 | pq[j-1] = swap; 62 | } 63 | 64 | // is v < w ? 65 | private static boolean less(Comparable v, Comparable w) { 66 | return (v.compareTo(w) < 0); 67 | } 68 | 69 | 70 | /*********************************************************************** 71 | * Check if array is sorted - useful for debugging 72 | ***********************************************************************/ 73 | private static boolean isSorted(Comparable[] a) { 74 | for (int i = 1; i < a.length; i++) 75 | if (less(a[i], a[i-1])) return false; 76 | return true; 77 | } 78 | 79 | 80 | // print array to standard output 81 | private static void show(Comparable[] a) { 82 | for (int i = 0; i < a.length; i++) { 83 | StdOut.println(a[i]); 84 | } 85 | } 86 | 87 | // Read strings from standard input, sort them, and print. 88 | public static void main(String[] args) { 89 | String[] a = StdIn.readStrings(); 90 | Heap.sort(a); 91 | show(a); 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /2-Sorting/2-4-PriorityQueues/Multiway.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac Multiway.java 3 | * Execution: java Multiway input1.txt input2.txt input3.txt ... 4 | * Dependencies: IndexMinPQ.java In.java StdOut.java 5 | * 6 | * Merges together the sorted input stream given as command-line arguments 7 | * into a single sorted output stream on standard output. 8 | * 9 | * % more m1.txt 10 | * A B C F G I I Z 11 | * 12 | * % more m2.txt 13 | * B D H P Q Q 14 | * 15 | * % more m3.txt 16 | * A B E F J N 17 | * 18 | * % java Multiway m1.txt m2.txt m3.txt 19 | * A A B B B C D E F F G H I I J N P Q Q Z 20 | * 21 | *************************************************************************/ 22 | 23 | public class Multiway { 24 | 25 | public static void merge(In[] streams) { 26 | int N = streams.length; 27 | IndexMinPQ pq = new IndexMinPQ(N); 28 | for (int i = 0; i < N; i++) 29 | if (!streams[i].isEmpty()) 30 | pq.insert(i, streams[i].readString()); 31 | 32 | // Extract and print min and read next from its stream. 33 | while (!pq.isEmpty()) { 34 | StdOut.print(pq.minKey() + " "); 35 | int i = pq.delMin(); 36 | if (!streams[i].isEmpty()) 37 | pq.insert(i, streams[i].readString()); 38 | } 39 | StdOut.println(); 40 | } 41 | 42 | 43 | public static void main(String[] args) { 44 | int N = args.length; 45 | In[] streams = new In[N]; 46 | for (int i = 0; i < N; i++) 47 | streams[i] = new In(args[i]); 48 | merge(streams); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /2-Sorting/2-4-PriorityQueues/TopM.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac TopM.java 3 | * Execution: java TopM M < input.txt 4 | * Dependencies: MinPQ.java Transaction.java StdIn.java StdOut.java 5 | * Data files: http://algs4.cs.princeton.edu/24pq/tinyBatch.txt 6 | * 7 | * Given an integer M from the command line and an input stream where 8 | * each line contains a String and a long value, this MinPQ client 9 | * prints the M lines whose numbers are the highest. 10 | * 11 | * % java TopM 5 < tinyBatch.txt 12 | * Thompson 2/27/2000 4747.08 13 | * vonNeumann 2/12/1994 4732.35 14 | * vonNeumann 1/11/1999 4409.74 15 | * Hoare 8/18/1992 4381.21 16 | * vonNeumann 3/26/2002 4121.85 17 | * 18 | *************************************************************************/ 19 | 20 | public class TopM { 21 | 22 | // Print the top M lines in the input stream. 23 | public static void main(String[] args) { 24 | int M = Integer.parseInt(args[0]); 25 | MinPQ pq = new MinPQ(M+1); 26 | 27 | while (StdIn.hasNextLine()) { 28 | // Create an entry from the next line and put on the PQ. 29 | String line = StdIn.readLine(); 30 | Transaction transaction = new Transaction(line); 31 | pq.insert(transaction); 32 | 33 | // remove minimum if M+1 entries on the PQ 34 | if (pq.size() > M) 35 | pq.delMin(); 36 | } // top M entries are on the PQ 37 | 38 | // print entries on PQ in reverse order 39 | Stack stack = new Stack(); 40 | for (Transaction transaction : pq) 41 | stack.push(transaction); 42 | for (Transaction transaction : stack) 43 | StdOut.println(transaction); 44 | } 45 | } 46 | 47 | -------------------------------------------------------------------------------- /2-Sorting/2-4-PriorityQueues/m1.txt: -------------------------------------------------------------------------------- 1 | A B C F G I I Z 2 | -------------------------------------------------------------------------------- /2-Sorting/2-4-PriorityQueues/m2.txt: -------------------------------------------------------------------------------- 1 | B D H P Q Q 2 | -------------------------------------------------------------------------------- /2-Sorting/2-4-PriorityQueues/m3.txt: -------------------------------------------------------------------------------- 1 | A B E F J N 2 | -------------------------------------------------------------------------------- /2-Sorting/2-4-PriorityQueues/tiny.txt: -------------------------------------------------------------------------------- 1 | S O R T E X A M P L E 2 | -------------------------------------------------------------------------------- /2-Sorting/2-4-PriorityQueues/tinyBatch.txt: -------------------------------------------------------------------------------- 1 | Turing 6/17/1990 644.08 2 | vonNeumann 3/26/2002 4121.85 3 | Dijkstra 8/22/2007 2678.40 4 | vonNeumann 1/11/1999 4409.74 5 | Dijkstra 11/18/1995 837.42 6 | Hoare 5/10/1993 3229.27 7 | vonNeumann 2/12/1994 4732.35 8 | Hoare 8/18/1992 4381.21 9 | Turing 1/11/2002 66.10 10 | Thompson 2/27/2000 4747.08 11 | Turing 2/11/1991 2156.86 12 | Hoare 8/12/2003 1025.70 13 | vonNeumann 10/13/1993 2520.97 14 | Dijkstra 9/10/2000 708.95 15 | Turing 10/12/1993 3532.36 16 | Hoare 2/10/2005 4050.20 17 | -------------------------------------------------------------------------------- /2-Sorting/2-4-PriorityQueues/tinyPQ.txt: -------------------------------------------------------------------------------- 1 | P Q E - X A M - P L E - 2 | -------------------------------------------------------------------------------- /2-Sorting/2-4-PriorityQueues/words3.txt: -------------------------------------------------------------------------------- 1 | bed bug dad yes zoo 2 | now for tip ilk dim 3 | tag jot sob nob sky 4 | hut men egg few jay 5 | owl joy rap gig wee 6 | was wad fee tap tar 7 | dug jam all bad yet 8 | -------------------------------------------------------------------------------- /3-Searching/3-1-SymbolTables/FrequencyCounter.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac FrequencyCounter.java 3 | * Execution: java FrequencyCounter L < input.txt 4 | * Dependencies: ST.java StdIn.java StdOut.java 5 | * Data files: http://algs4.cs.princeton.edu/41elementary/tnyTale.txt 6 | * http://algs4.cs.princeton.edu/41elementary/tale.txt 7 | * http://algs4.cs.princeton.edu/41elementary/tale.txt 8 | * http://algs4.cs.princeton.edu/41elementary/leipzig100K.txt 9 | * http://algs4.cs.princeton.edu/41elementary/leipzig300K.txt 10 | * http://algs4.cs.princeton.edu/41elementary/leipzig1M.txt 11 | * 12 | * Read in a list of words from standard input and print out 13 | * the most frequently occurring word. 14 | * 15 | * % java FrequencyCounter 1 < tinyTale.txt 16 | * it 10 17 | * 18 | * % java FrequencyCounter 8 < tale.txt 19 | * business 122 20 | * 21 | * % java FrequencyCounter 10 < leipzig1M.txt 22 | * government 24763 23 | * 24 | * 25 | *************************************************************************/ 26 | 27 | public class FrequencyCounter { 28 | 29 | public static void main(String[] args) { 30 | int distinct = 0, words = 0; 31 | int minlen = Integer.parseInt(args[0]); 32 | ST st = new ST(); 33 | 34 | // compute frequency counts 35 | while (!StdIn.isEmpty()) { 36 | String key = StdIn.readString(); 37 | if (key.length() < minlen) continue; 38 | words++; 39 | if (st.contains(key)) { st.put(key, st.get(key) + 1); } 40 | else { st.put(key, 1); distinct++; } 41 | } 42 | 43 | // find a key with the highest frequency count 44 | String max = ""; 45 | st.put(max, 0); 46 | for (String word : st.keys()) { 47 | if (st.get(word) > st.get(max)) 48 | max = word; 49 | } 50 | 51 | StdOut.println(max + " " + st.get(max)); 52 | StdOut.println("distinct = " + distinct); 53 | StdOut.println("words = " + words); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /3-Searching/3-1-SymbolTables/tinyST.txt: -------------------------------------------------------------------------------- 1 | S E A R C H E X A M P L E 2 | -------------------------------------------------------------------------------- /3-Searching/3-1-SymbolTables/tinyTale.txt: -------------------------------------------------------------------------------- 1 | it was the best of times it was the worst of times 2 | it was the age of wisdom it was the age of foolishness 3 | it was the epoch of belief it was the epoch of incredulity 4 | it was the season of light it was the season of darkness 5 | it was the spring of hope it was the winter of despair 6 | -------------------------------------------------------------------------------- /3-Searching/3-2-BinarySearchTrees/tinyST.txt: -------------------------------------------------------------------------------- 1 | S E A R C H E X A M P L E 2 | -------------------------------------------------------------------------------- /3-Searching/3-3-BalancedSearchTrees/tinyST.txt: -------------------------------------------------------------------------------- 1 | S E A R C H E X A M P L E 2 | -------------------------------------------------------------------------------- /3-Searching/3-4-HashTables/tinyST.txt: -------------------------------------------------------------------------------- 1 | S E A R C H E X A M P L E 2 | -------------------------------------------------------------------------------- /3-Searching/3-5-Applications/BlackFilter.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac BlackFilter.java 3 | * Execution: java BlackFilter blacklist.txt < input.txt 4 | * Dependencies: SET In.java StdIn.java StdOut.java 5 | * Data files: http://algs4.cs.princeton.edu/35applications/tinyTale.txt 6 | * http://algs4.cs.princeton.edu/35applications/list.txt 7 | * 8 | * Read in a blacklist of words from a file. Then read in a list of 9 | * words from standard input and print out all those words that 10 | * are not in the first file. 11 | * 12 | * % more tinyTale.txt 13 | * it was the best of times it was the worst of times 14 | * it was the age of wisdom it was the age of foolishness 15 | * it was the epoch of belief it was the epoch of incredulity 16 | * it was the season of light it was the season of darkness 17 | * it was the spring of hope it was the winter of despair 18 | * 19 | * % more list.txt 20 | * was it the of 21 | * 22 | * % java BlackFilter list.txt < tinyTale.txt 23 | * best times worst times 24 | * age wisdom age foolishness 25 | * epoch belief epoch incredulity 26 | * season light season darkness 27 | * spring hope winter despair 28 | * 29 | *************************************************************************/ 30 | 31 | public class BlackFilter { 32 | public static void main(String[] args) { 33 | SET set = new SET(); 34 | 35 | // read in strings and add to set 36 | In in = new In(args[0]); 37 | while (!in.isEmpty()) { 38 | String word = in.readString(); 39 | set.add(word); 40 | } 41 | 42 | // read in string from standard input, printing out all exceptions 43 | while (!StdIn.isEmpty()) { 44 | String word = StdIn.readString(); 45 | if (!set.contains(word)) 46 | StdOut.println(word); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /3-Searching/3-5-Applications/DeDup.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac DeDup.java 3 | * Execution: java DeDup < input.txt 4 | * Dependencies: SET StdIn.java StdOut.java 5 | * Data files: http://algs4.cs.princeton.edu/35applications/tinyTale.txt 6 | * 7 | * Read in a list of words from standard input and print out 8 | * each word, removing any duplicates. 9 | * 10 | * % more tinyTale.txt 11 | * it was the best of times it was the worst of times 12 | * it was the age of wisdom it was the age of foolishness 13 | * it was the epoch of belief it was the epoch of incredulity 14 | * it was the season of light it was the season of darkness 15 | * it was the spring of hope it was the winter of despair 16 | * 17 | * % java DeDup < tinyTale.txt 18 | * it 19 | * was 20 | * the 21 | * best 22 | * of 23 | * times 24 | * worst 25 | * age 26 | * wisdom 27 | * ... 28 | * winter 29 | * despair 30 | * 31 | *************************************************************************/ 32 | 33 | public class DeDup { 34 | public static void main(String[] args) { 35 | SET set = new SET(); 36 | 37 | // read in strings and add to set 38 | while (!StdIn.isEmpty()) { 39 | String key = StdIn.readString(); 40 | if (!set.contains(key)) { 41 | set.add(key); 42 | StdOut.println(key); 43 | } 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /3-Searching/3-5-Applications/FileIndex.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac FileIndex.java 3 | * Execution: java FileIndex file1.txt file2.txt file3.txt ... 4 | * Dependencies: ST.java SET.java In.java StdIn.java StdOut.java 5 | * Data files: http://algs4.cs.princeton.edu/ex1.txt 6 | * http://algs4.cs.princeton.edu/ex2.txt 7 | * http://algs4.cs.princeton.edu/ex3.txt 8 | * http://algs4.cs.princeton.edu/ex4.txt 9 | * 10 | * % java FileIndex ex*.txt 11 | * age 12 | * ex3.txt 13 | * ex4.txt 14 | * best 15 | * ex1.txt 16 | * was 17 | * ex1.txt 18 | * ex2.txt 19 | * ex3.txt 20 | * ex4.txt 21 | * 22 | * % java FileIndex *.txt 23 | * 24 | * % java FileIndex *.java 25 | * 26 | *************************************************************************/ 27 | 28 | import java.io.File; 29 | 30 | public class FileIndex { 31 | 32 | public static void main(String[] args) { 33 | 34 | // key = word, value = set of files containing that word 35 | ST> st = new ST>(); 36 | 37 | // create inverted index of all files 38 | StdOut.println("Indexing files"); 39 | for (String filename : args) { 40 | StdOut.println(" " + filename); 41 | File file = new File(filename); 42 | In in = new In(file); 43 | while (!in.isEmpty()) { 44 | String word = in.readString(); 45 | if (!st.contains(word)) st.put(word, new SET()); 46 | SET set = st.get(word); 47 | set.add(file); 48 | } 49 | } 50 | 51 | 52 | // read queries from standard input, one per line 53 | while (!StdIn.isEmpty()) { 54 | String query = StdIn.readString(); 55 | if (st.contains(query)) { 56 | SET set = st.get(query); 57 | for (File file : set) { 58 | StdOut.println(" " + file.getName()); 59 | } 60 | } 61 | } 62 | 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /3-Searching/3-5-Applications/LookupCSV.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac LookupCSV.java 3 | * Execution: java LookupCSV file.csv keyField valField 4 | * Dependencies: ST.java In.java StdIn.java StdOut.java 5 | * Data files: http://algs4.cs.princeton.edu/35applications/DJIA.csv 6 | * http://algs4.cs.princeton.edu/35applications/UPC.csv 7 | * http://algs4.cs.princeton.edu/35applications/amino.csv 8 | * http://algs4.cs.princeton.edu/35applications/elements.csv 9 | * http://algs4.cs.princeton.edu/35applications/ip.csv 10 | * http://algs4.cs.princeton.edu/35applications/morse.csv 11 | * 12 | * Reads in a set of key-value pairs from a two-column CSV file 13 | * specified on the command line; then, reads in keys from standard 14 | * input and prints out corresponding values. 15 | * 16 | * % java LookupCSV amino.csv 0 3 % java LookupCSV ip.csv 0 1 17 | * TTA www.google.com 18 | * Leucine 216.239.41.99 19 | * ABC 20 | * Not found % java LookupCSV ip.csv 1 0 21 | * TCT 216.239.41.99 22 | * Serine www.google.com 23 | * 24 | * % java LookupCSV amino.csv 3 0 % java LookupCSV DJIA.csv 0 1 25 | * Glycine 29-Oct-29 26 | * GGG 252.38 27 | * 20-Oct-87 28 | * 1738.74 29 | * 30 | * 31 | *************************************************************************/ 32 | 33 | public class LookupCSV { 34 | public static void main(String[] args) { 35 | int keyField = Integer.parseInt(args[1]); 36 | int valField = Integer.parseInt(args[2]); 37 | 38 | // symbol table 39 | ST st = new ST(); 40 | 41 | // read in the data from csv file 42 | In in = new In(args[0]); 43 | while (in.hasNextLine()) { 44 | String line = in.readLine(); 45 | String[] tokens = line.split(","); 46 | String key = tokens[keyField]; 47 | String val = tokens[valField]; 48 | st.put(key, val); 49 | } 50 | 51 | while (!StdIn.isEmpty()) { 52 | String s = StdIn.readString(); 53 | if (st.contains(s)) StdOut.println(st.get(s)); 54 | else StdOut.println("Not found"); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /3-Searching/3-5-Applications/LookupIndex.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac LookupIndex.java 3 | * Execution: java LookupIndex movies.txt "/" 4 | * Dependencies: ST.java Queue.java In.java StdIn.java StdOut.java 5 | * Data files: http://algs4.cs.princeton.edu/35applications/aminoI.txt 6 | * http://algs4.cs.princeton.edu/35applications/movies.txt 7 | * 8 | * % java LookupIndex aminoI.txt "," 9 | * Serine 10 | * TCT 11 | * TCA 12 | * TCG 13 | * AGT 14 | * AGC 15 | * TCG 16 | * Serine 17 | * 18 | * % java LookupIndex movies.txt "/" 19 | * Bacon, Kevin 20 | * Animal House (1978) 21 | * Apollo 13 (1995) 22 | * Beauty Shop (2005) 23 | * Diner (1982) 24 | * Few Good Men, A (1992) 25 | * Flatliners (1990) 26 | * Footloose (1984) 27 | * Friday the 13th (1980) 28 | * ... 29 | * Tin Men (1987) 30 | * DeBoy, David 31 | * Blumenfeld, Alan 32 | * ... 33 | * 34 | *************************************************************************/ 35 | 36 | public class LookupIndex { 37 | 38 | public static void main(String[] args) { 39 | String filename = args[0]; 40 | String separator = args[1]; 41 | In in = new In(filename); 42 | 43 | ST> st = new ST>(); 44 | ST> ts = new ST>(); 45 | 46 | while (in.hasNextLine()) { 47 | String line = in.readLine(); 48 | String[] fields = line.split(separator); 49 | String key = fields[0]; 50 | for (int i = 1; i < fields.length; i++) { 51 | String val = fields[i]; 52 | if (!st.contains(key)) st.put(key, new Queue()); 53 | if (!ts.contains(val)) ts.put(val, new Queue()); 54 | st.get(key).enqueue(val); 55 | ts.get(val).enqueue(key); 56 | } 57 | } 58 | 59 | StdOut.println("Done indexing"); 60 | 61 | // read queries from standard input, one per line 62 | while (!StdIn.isEmpty()) { 63 | String query = StdIn.readLine(); 64 | if (st.contains(query)) 65 | for (String vals : st.get(query)) 66 | StdOut.println(" " + vals); 67 | if (ts.contains(query)) 68 | for (String keys : ts.get(query)) 69 | StdOut.println(" " + keys); 70 | } 71 | 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /3-Searching/3-5-Applications/WhiteFilter.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac WhiteFilter.java 3 | * Execution: java WhiteFilter whitelist.txt < input.txt 4 | * Dependencies: SET In.java StdIn.java StdOut.java 5 | * Data files: http://algs4.cs.princeton.edu/35applications/tinyTale.txt 6 | * http://algs4.cs.princeton.edu/35applications/list.txt 7 | * 8 | * Read in a whitelist of words from a file. Then read in a list of 9 | * words from standard input and print out all those words that 10 | * are in the first file. 11 | * 12 | * % more tinyTale.txt 13 | * it was the best of times it was the worst of times 14 | * it was the age of wisdom it was the age of foolishness 15 | * it was the epoch of belief it was the epoch of incredulity 16 | * it was the season of light it was the season of darkness 17 | * it was the spring of hope it was the winter of despair 18 | * 19 | * % more list.txt 20 | * was it the of 21 | * 22 | * % java WhiteFilter list.txt < tinyTale.txt 23 | * it was the of it was the of 24 | * it was the of it was the of 25 | * it was the of it was the of 26 | * it was the of it was the of 27 | * it was the of it was the of 28 | * 29 | *************************************************************************/ 30 | 31 | public class WhiteFilter { 32 | public static void main(String[] args) { 33 | SET set = new SET(); 34 | 35 | // read in strings and add to set 36 | In in = new In(args[0]); 37 | while (!in.isEmpty()) { 38 | String word = in.readString(); 39 | set.add(word); 40 | } 41 | 42 | // read in string from standard input, printing out all exceptions 43 | while (!StdIn.isEmpty()) { 44 | String word = StdIn.readString(); 45 | if (set.contains(word)) 46 | StdOut.println(word); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /3-Searching/3-5-Applications/amino.csv: -------------------------------------------------------------------------------- 1 | TTT,Phe,F,Phenylalanine 2 | TTC,Phe,F,Phenylalanine 3 | TTA,Leu,L,Leucine 4 | TTG,Leu,L,Leucine 5 | TCT,Ser,S,Serine 6 | TCC,Ser,S,Serine 7 | TCA,Ser,S,Serine 8 | TCG,Ser,S,Serine 9 | TAT,Tyr,Y,Tyrosine 10 | TAC,Tyr,Y,Tyrosine 11 | TAA,Stop,Stop,Stop 12 | TAG,Stop,Stop,Stop 13 | TGT,Cys,C,Cysteine 14 | TGC,Cys,C,Cysteine 15 | TGA,Stop,Stop,Stop 16 | TGG,Trp,W,Tryptophan 17 | CTT,Leu,L,Leucine 18 | CTC,Leu,L,Leucine 19 | CTA,Leu,L,Leucine 20 | CTG,Leu,L,Leucine 21 | CCT,Pro,P,Proline 22 | CCC,Pro,P,Proline 23 | CCA,Pro,P,Proline 24 | CCG,Pro,P,Proline 25 | CAT,His,H,Histidine 26 | CAC,His,H,Histidine 27 | CAA,Gln,Q,Glutamine 28 | CAG,Gln,Q,Glutamine 29 | CGT,Arg,R,Arginine 30 | CGC,Arg,R,Arginine 31 | CGA,Arg,R,Arginine 32 | CGG,Arg,R,Arginine 33 | ATT,Ile,I,Isoleucine 34 | ATC,Ile,I,Isoleucine 35 | ATA,Ile,I,Isoleucine 36 | ATG,Met,M,Methionine 37 | ACT,Thr,T,Threonine 38 | ACC,Thr,T,Threonine 39 | ACA,Thr,T,Threonine 40 | ACG,Thr,T,Threonine 41 | AAT,Ala,A,Alanine 42 | AAC,Ala,A,Alanine 43 | AAA,Lys,K,Lysine 44 | AAG,Lys,K,Lysine 45 | AGT,Ser,S,Serine 46 | AGC,Ser,S,Serine 47 | AGA,Arg,R,Arginine 48 | AGG,Arg,R,Arginine 49 | GTT,Val,V,Valine 50 | GTC,Val,V,Valine 51 | GTA,Val,V,Valine 52 | GTG,Val,V,Valine 53 | GCT,Ala,A,Alanine 54 | GCC,Ala,A,Alanine 55 | GCA,Ala,A,Alanine 56 | GCG,Ala,A,Alanine 57 | GAT,Asp,D,Aspartic Acid 58 | GAC,Asp,D,Aspartic Acid 59 | GAA,Gly,G,Glutamic Acid 60 | GAG,Gly,G,Glutamic Acid 61 | GGT,Gly,G,Glycine 62 | GGC,Gly,G,Glycine 63 | GGA,Gly,G,Glycine 64 | GGG,Gly,G,Glycine 65 | -------------------------------------------------------------------------------- /3-Searching/3-5-Applications/aminoI.txt: -------------------------------------------------------------------------------- 1 | Alanine,AAT,AAC,GCT,GCC,GCA,GCG 2 | Arginine,CGT,CGC,CGA,CGG,AGA,AGG 3 | Aspartic Acid,GAT,GAC 4 | Cysteine,TGT,TGC 5 | Glutamic Acid,GAA,GAG 6 | Glutamine,CAA,CAG 7 | Glycine,GGT,GGC,GGA,GGG 8 | Histidine,CAT,CAC 9 | Isoleucine,ATT,ATC,ATA 10 | Leucine,TTA,TTG,CTT,CTC,CTA,CTG 11 | Lysine,AAA,AAG 12 | Methionine,ATG 13 | Phenylalanine,TTT,TTC 14 | Proline,CCT,CCC,CCA,CCG 15 | Serine,TCT,TCA,TCG,AGT,AGC 16 | Stop,TAA,TAG,TGA 17 | Threonine,ACT,ACC,ACA,ACG 18 | Tyrosine,TAT,TAC 19 | Tryptophan,TGG 20 | Valine,GTT,GTC,GTA,GTG 21 | -------------------------------------------------------------------------------- /3-Searching/3-5-Applications/ex1.txt: -------------------------------------------------------------------------------- 1 | it was the best of times 2 | -------------------------------------------------------------------------------- /3-Searching/3-5-Applications/ex2.txt: -------------------------------------------------------------------------------- 1 | it was the worst of times 2 | -------------------------------------------------------------------------------- /3-Searching/3-5-Applications/ex3.txt: -------------------------------------------------------------------------------- 1 | it was the age of wisdom 2 | -------------------------------------------------------------------------------- /3-Searching/3-5-Applications/ex4.txt: -------------------------------------------------------------------------------- 1 | it was the age of foolishness 2 | -------------------------------------------------------------------------------- /3-Searching/3-5-Applications/list.txt: -------------------------------------------------------------------------------- 1 | was it the of 2 | -------------------------------------------------------------------------------- /3-Searching/3-5-Applications/tinyTale.txt: -------------------------------------------------------------------------------- 1 | it was the best of times it was the worst of times 2 | it was the age of wisdom it was the age of foolishness 3 | it was the epoch of belief it was the epoch of incredulity 4 | it was the season of light it was the season of darkness 5 | it was the spring of hope it was the winter of despair 6 | -------------------------------------------------------------------------------- /4-Graphs/4-1-UndirectedGraphs/CC.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac CC.java 3 | * Execution: java CC filename.txt 4 | * Dependencies: Graph.java StdOut.java Queue.java 5 | * Data files: http://algs4.cs.princeton.edu/41undirected/tinyG.txt 6 | * 7 | * Compute connected components using depth first search. 8 | * Runs in O(E + V) time. 9 | * 10 | * % java CC tinyG.txt 11 | * 3 components 12 | * 0 1 2 3 4 5 6 13 | * 7 8 14 | * 9 10 11 12 15 | * 16 | *************************************************************************/ 17 | 18 | public class CC { 19 | private boolean[] marked; // marked[v] = has vertex v been marked? 20 | private int[] id; // id[v] = id of connected component containing v 21 | private int[] size; // size[v] = number of vertices in component containing v 22 | private int count; // number of connected components 23 | 24 | public CC(Graph G) { 25 | marked = new boolean[G.V()]; 26 | id = new int[G.V()]; 27 | size = new int[G.V()]; 28 | for (int v = 0; v < G.V(); v++) { 29 | if (!marked[v]) { 30 | dfs(G, v); 31 | count++; 32 | } 33 | } 34 | } 35 | 36 | // depth first search 37 | private void dfs(Graph G, int v) { 38 | marked[v] = true; 39 | id[v] = count; 40 | size[v]++; 41 | for (int w : G.adj(v)) { 42 | if (!marked[w]) { 43 | dfs(G, w); 44 | } 45 | } 46 | } 47 | 48 | // id of connected component containing v 49 | public int id(int v) { 50 | return id[v]; 51 | } 52 | 53 | // size of connected component containing v 54 | public int size(int v) { 55 | return size[id[v]]; 56 | } 57 | 58 | // number of connected components 59 | public int count() { 60 | return count; 61 | } 62 | 63 | // are v and w in the same connected component? 64 | public boolean areConnected(int v, int w) { 65 | return id(v) == id(w); 66 | } 67 | 68 | 69 | // test client 70 | public static void main(String[] args) { 71 | In in = new In(args[0]); 72 | Graph G = new Graph(in); 73 | CC cc = new CC(G); 74 | 75 | // number of connected components 76 | int M = cc.count(); 77 | StdOut.println(M + " components"); 78 | 79 | // compute list of vertices in each connected component 80 | Queue[] components = (Queue[]) new Queue[M]; 81 | for (int i = 0; i < M; i++) { 82 | components[i] = new Queue(); 83 | } 84 | for (int v = 0; v < G.V(); v++) { 85 | components[cc.id(v)].enqueue(v); 86 | } 87 | 88 | // print results 89 | for (int i = 0; i < M; i++) { 90 | for (int v : components[i]) { 91 | StdOut.print(v + " "); 92 | } 93 | StdOut.println(); 94 | } 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /4-Graphs/4-1-UndirectedGraphs/DegreesOfSeparation.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac DegreesOfSeparation.java 3 | * Execution: java DegreesOfSeparation filename delimiter source 4 | * Dependencies: SymbolGraph.java Graph.java BreadthFirstPaths.java StdOut.java 5 | * Data files: http://algs4.cs.princeton.edu/41undirected/routes.txt 6 | * http://algs4.cs.princeton.edu/41undirected/movies.txt 7 | * 8 | * 9 | * % java DegreesOfSeparation routes.txt " " "JFK" 10 | * LAS 11 | * JFK 12 | * ORD 13 | * DEN 14 | * LAS 15 | * DFW 16 | * JFK 17 | * ORD 18 | * DFW 19 | * EWR 20 | * Not in database. 21 | * 22 | * % java DegreesOfSeparation movies.txt "/" "Bacon, Kevin" 23 | * Kidman, Nicole 24 | * Bacon, Kevin 25 | * Woodsman, The (2004) 26 | * Grier, David Alan 27 | * Bewitched (2005) 28 | * Kidman, Nicole 29 | * Grant, Cary 30 | * Bacon, Kevin 31 | * Planes, Trains & Automobiles (1987) 32 | * Martin, Steve (I) 33 | * Dead Men Don't Wear Plaid (1982) 34 | * Grant, Cary 35 | * 36 | * % java DegreesOfSeparation movies.txt "/" "Animal House (1978)" 37 | * Titanic (1997) 38 | * Animal House (1978) 39 | * Allen, Karen (I) 40 | * Raiders of the Lost Ark (1981) 41 | * Taylor, Rocky (I) 42 | * Titanic (1997) 43 | * To Catch a Thief (1955) 44 | * Animal House (1978) 45 | * Vernon, John (I) 46 | * Topaz (1969) 47 | * Hitchcock, Alfred (I) 48 | * To Catch a Thief (1955) 49 | * 50 | *************************************************************************/ 51 | 52 | public class DegreesOfSeparation { 53 | public static void main(String[] args) { 54 | String filename = args[0]; 55 | String delimiter = args[1]; 56 | String source = args[2]; 57 | 58 | // StdOut.println("Source: " + source); 59 | 60 | SymbolGraph sg = new SymbolGraph(filename, delimiter); 61 | Graph G = sg.G(); 62 | if (!sg.contains(source)) { 63 | StdOut.println(source + " not in database."); 64 | return; 65 | } 66 | 67 | int s = sg.index(source); 68 | BreadthFirstPaths bfs = new BreadthFirstPaths(G, s); 69 | 70 | while (!StdIn.isEmpty()) { 71 | String sink = StdIn.readLine(); 72 | if (sg.contains(sink)) { 73 | int t = sg.index(sink); 74 | if (bfs.hasPathTo(t)) { 75 | for (int v : bfs.pathTo(t)) { 76 | StdOut.println(" " + sg.name(v)); 77 | } 78 | } 79 | else { 80 | StdOut.println("Not connected"); 81 | } 82 | } 83 | else { 84 | StdOut.println(" Not in database."); 85 | } 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /4-Graphs/4-1-UndirectedGraphs/DepthFirstPaths.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac DepthFirstPaths.java 3 | * Execution: java DepthFirstPaths G s 4 | * Dependencies: Graph.java Stack.java StdOut.java 5 | * Data files: http://algs4.cs.princeton.edu/41undirected/tinyCG.txt 6 | * 7 | * Run depth first search on an undirected graph. 8 | * Runs in O(E + V) time. 9 | * 10 | * % java Graph tinyCG.txt 11 | * 6 8 12 | * 0: 2 1 5 13 | * 1: 0 2 14 | * 2: 0 1 3 4 15 | * 3: 5 4 2 16 | * 4: 3 2 17 | * 5: 3 0 18 | * 19 | * % java DepthFirstPaths tinyCG.txt 0 20 | * 0 to 0: 0 21 | * 0 to 1: 0-2-1 22 | * 0 to 2: 0-2 23 | * 0 to 3: 0-2-3 24 | * 0 to 4: 0-2-3-4 25 | * 0 to 5: 0-2-3-5 26 | * 27 | *************************************************************************/ 28 | 29 | public class DepthFirstPaths { 30 | private boolean[] marked; // marked[v] = is there an s-v path? 31 | private int[] edgeTo; // edgeTo[v] = last edge on s-v path 32 | private final int s; // source vertex 33 | 34 | public DepthFirstPaths(Graph G, int s) { 35 | this.s = s; 36 | edgeTo = new int[G.V()]; 37 | marked = new boolean[G.V()]; 38 | dfs(G, s); 39 | } 40 | 41 | // depth first search from v 42 | private void dfs(Graph G, int v) { 43 | marked[v] = true; 44 | for (int w : G.adj(v)) { 45 | if (!marked[w]) { 46 | edgeTo[w] = v; 47 | dfs(G, w); 48 | } 49 | } 50 | } 51 | 52 | // is there a path between s and v? 53 | public boolean hasPathTo(int v) { 54 | return marked[v]; 55 | } 56 | 57 | // return a path between s to v; null if no such path 58 | public Iterable pathTo(int v) { 59 | if (!hasPathTo(v)) return null; 60 | Stack path = new Stack(); 61 | for (int x = v; x != s; x = edgeTo[x]) 62 | path.push(x); 63 | path.push(s); 64 | return path; 65 | } 66 | 67 | public static void main(String[] args) { 68 | In in = new In(args[0]); 69 | Graph G = new Graph(in); 70 | int s = Integer.parseInt(args[1]); 71 | DepthFirstPaths dfs = new DepthFirstPaths(G, s); 72 | 73 | for (int v = 0; v < G.V(); v++) { 74 | if (dfs.hasPathTo(v)) { 75 | StdOut.printf("%d to %d: ", s, v); 76 | for (int x : dfs.pathTo(v)) { 77 | if (x == s) StdOut.print(x); 78 | else StdOut.print("-" + x); 79 | } 80 | StdOut.println(); 81 | } 82 | 83 | else { 84 | StdOut.printf("%d to %d: not connected\n", s, v); 85 | } 86 | 87 | } 88 | } 89 | 90 | } 91 | -------------------------------------------------------------------------------- /4-Graphs/4-1-UndirectedGraphs/DepthFirstSearch.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac DepthFirstSearch.java 3 | * Execution: java DepthFirstSearch filename.txt s 4 | * Dependencies: Graph.java StdOut.java 5 | * Data files: http://algs4.cs.princeton.edu/41undirected/tinyG.txt 6 | * 7 | * Run depth first search on an undirected graph. 8 | * Runs in O(E + V) time. 9 | * 10 | * % java DepthFirstSearch tinyG.txt 0 11 | * 0 1 2 3 4 5 6 12 | * NOT connected 13 | * 14 | * % java DepthFirstSearch tinyG.txt 9 15 | * 9 10 11 12 16 | * NOT connected 17 | * 18 | *************************************************************************/ 19 | 20 | public class DepthFirstSearch { 21 | private boolean[] marked; // marked[v] = is there an s-v path? 22 | private int count; // number of vertices connected to s 23 | 24 | // single source 25 | public DepthFirstSearch(Graph G, int s) { 26 | marked = new boolean[G.V()]; 27 | dfs(G, s); 28 | } 29 | 30 | // depth first search from v 31 | private void dfs(Graph G, int v) { 32 | marked[v] = true; 33 | for (int w : G.adj(v)) { 34 | if (!marked[w]) { 35 | dfs(G, w); 36 | } 37 | } 38 | } 39 | 40 | // is there an s-v path? 41 | public boolean marked(int v) { 42 | return marked[v]; 43 | } 44 | 45 | // number of vertices connected to s 46 | public int count() { 47 | return count; 48 | } 49 | 50 | // test client 51 | public static void main(String[] args) { 52 | In in = new In(args[0]); 53 | Graph G = new Graph(in); 54 | int s = Integer.parseInt(args[1]); 55 | DepthFirstSearch search = new DepthFirstSearch(G, s); 56 | for (int v = 0; v < G.V(); v++) { 57 | if (search.marked(v)) 58 | StdOut.print(v + " "); 59 | } 60 | 61 | StdOut.println(); 62 | if (search.count() != G.V()) StdOut.println("NOT connected"); 63 | else StdOut.println("connected"); 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /4-Graphs/4-1-UndirectedGraphs/SymbolGraph.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac SymbolGraph.java 3 | * Execution: java SymbolGraph filename.txt delimiter 4 | * Dependencies: ST.java Graph.java In.java StdIn.java StdOut.java 5 | * Data files: http://algs4.cs.princeton.edu/41undirected/routes.txt 6 | * http://algs4.cs.princeton.edu/41undirected/movies.txt 7 | * 8 | * % java SymbolGraph routes.txt " " 9 | * JFK 10 | * MCO 11 | * ATL 12 | * ORD 13 | * LAX 14 | * PHX 15 | * LAS 16 | * 17 | * % java SymbolGraph movies.txt "/" 18 | * Tin Men (1987) 19 | * Hershey, Barbara 20 | * Geppi, Cindy 21 | * Jones, Kathy (II) 22 | * Herr, Marcia 23 | * ... 24 | * Blumenfeld, Alan 25 | * DeBoy, David 26 | * Bacon, Kevin 27 | * Woodsman, The (2004) 28 | * Wild Things (1998) 29 | * Where the Truth Lies (2005) 30 | * Tremors (1990) 31 | * ... 32 | * Apollo 13 (1995) 33 | * Animal House (1978) 34 | * 35 | *************************************************************************/ 36 | 37 | public class SymbolGraph { 38 | private ST st; // string -> index 39 | private String[] keys; // index -> string 40 | private Graph G; 41 | 42 | public SymbolGraph(String filename, String delimiter) { 43 | st = new ST(); 44 | 45 | // First pass builds the index by reading strings to associate 46 | // distinct strings with an index 47 | In in = new In(filename); 48 | while (in.hasNextLine()) { 49 | String[] a = in.readLine().split(delimiter); 50 | for (int i = 0; i < a.length; i++) { 51 | if (!st.contains(a[i])) 52 | st.put(a[i], st.size()); 53 | } 54 | } 55 | 56 | // inverted index to get string keys in an aray 57 | keys = new String[st.size()]; 58 | for (String name : st.keys()) { 59 | keys[st.get(name)] = name; 60 | } 61 | 62 | // second pass builds the graph by connecting first vertex on each 63 | // line to all others 64 | G = new Graph(st.size()); 65 | in = new In(filename); 66 | while (in.hasNextLine()) { 67 | String[] a = in.readLine().split(delimiter); 68 | int v = st.get(a[0]); 69 | for (int i = 1; i < a.length; i++) { 70 | int w = st.get(a[i]); 71 | G.addEdge(v, w); 72 | } 73 | } 74 | } 75 | 76 | public boolean contains(String s) { 77 | return st.contains(s); 78 | } 79 | 80 | public int index(String s) { 81 | return st.get(s); 82 | } 83 | 84 | public String name(int v) { 85 | return keys[v]; 86 | } 87 | 88 | public Graph G() { 89 | return G; 90 | } 91 | 92 | 93 | public static void main(String[] args) { 94 | String filename = args[0]; 95 | String delimiter = args[1]; 96 | SymbolGraph sg = new SymbolGraph(filename, delimiter); 97 | Graph G = sg.G(); 98 | while (StdIn.hasNextLine()) { 99 | String source = StdIn.readLine(); 100 | int s = sg.index(source); 101 | for (int v : G.adj(s)) { 102 | StdOut.println(" " + sg.name(v)); 103 | } 104 | } 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /4-Graphs/4-1-UndirectedGraphs/routes.txt: -------------------------------------------------------------------------------- 1 | JFK MCO 2 | ORD DEN 3 | ORD HOU 4 | DFW PHX 5 | JFK ATL 6 | ORD DFW 7 | ORD PHX 8 | ATL HOU 9 | DEN PHX 10 | PHX LAX 11 | JFK ORD 12 | DEN LAS 13 | DFW HOU 14 | ORD ATL 15 | LAS LAX 16 | ATL MCO 17 | HOU MCO 18 | LAS PHX 19 | -------------------------------------------------------------------------------- /4-Graphs/4-1-UndirectedGraphs/tinyCG.txt: -------------------------------------------------------------------------------- 1 | 6 2 | 8 3 | 0 5 4 | 2 4 5 | 2 3 6 | 1 2 7 | 0 1 8 | 3 4 9 | 3 5 10 | 0 2 11 | -------------------------------------------------------------------------------- /4-Graphs/4-1-UndirectedGraphs/tinyG.txt: -------------------------------------------------------------------------------- 1 | 13 2 | 13 3 | 0 5 4 | 4 3 5 | 0 1 6 | 9 12 7 | 6 4 8 | 5 4 9 | 0 2 10 | 11 12 11 | 9 10 12 | 0 6 13 | 7 8 14 | 9 11 15 | 5 3 16 | -------------------------------------------------------------------------------- /4-Graphs/4-2-DirectedGraphs/DepthFirstDirectedPaths.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac DepthFirstDirectedPaths.java 3 | * Execution: java DepthFirstDirectedPaths G s 4 | * Dependencies: Digraph.java Stack.java 5 | * 6 | * Determine reachability in a digraph from a given vertex using 7 | * depth first search. 8 | * Runs in O(E + V) time. 9 | * 10 | * % tinyDG.txt 3 11 | * 3 to 0: 3-5-4-2-0 12 | * 3 to 1: 3-5-4-2-0-1 13 | * 3 to 2: 3-5-4-2 14 | * 3 to 3: 3 15 | * 3 to 4: 3-5-4 16 | * 3 to 5: 3-5 17 | * 3 to 6: not connected 18 | * 3 to 7: not connected 19 | * 3 to 8: not connected 20 | * 3 to 9: not connected 21 | * 3 to 10: not connected 22 | * 3 to 11: not connected 23 | * 3 to 12: not connected 24 | * 25 | *************************************************************************/ 26 | 27 | public class DepthFirstDirectedPaths { 28 | private boolean[] marked; // marked[v] = true if v is reachable from s 29 | private int[] edgeTo; // edgeTo[v] = last edge on path from s to v 30 | private final int s; // source vertex 31 | 32 | // single source 33 | public DepthFirstDirectedPaths(Digraph G, int s) { 34 | marked = new boolean[G.V()]; 35 | edgeTo = new int[G.V()]; 36 | this.s = s; 37 | dfs(G, s); 38 | } 39 | 40 | 41 | private void dfs(Digraph G, int v) { 42 | marked[v] = true; 43 | for (int w : G.adj(v)) { 44 | if (!marked[w]) { 45 | edgeTo[w] = v; 46 | dfs(G, w); 47 | } 48 | } 49 | } 50 | 51 | // is there a directed path from s to v? 52 | public boolean hasPathTo(int v) { 53 | return marked[v]; 54 | } 55 | 56 | // return path from s to v; null if no such path 57 | public Iterable pathTo(int v) { 58 | if (!hasPathTo(v)) return null; 59 | Stack path = new Stack(); 60 | for (int x = v; x != s; x = edgeTo[x]) 61 | path.push(x); 62 | path.push(s); 63 | return path; 64 | } 65 | 66 | public static void main(String[] args) { 67 | In in = new In(args[0]); 68 | Digraph G = new Digraph(in); 69 | // StdOut.println(G); 70 | 71 | int s = Integer.parseInt(args[1]); 72 | DepthFirstDirectedPaths dfs = new DepthFirstDirectedPaths(G, s); 73 | 74 | for (int v = 0; v < G.V(); v++) { 75 | if (dfs.hasPathTo(v)) { 76 | StdOut.printf("%d to %d: ", s, v); 77 | for (int x : dfs.pathTo(v)) { 78 | if (x == s) StdOut.print(x); 79 | else StdOut.print("-" + x); 80 | } 81 | StdOut.println(); 82 | } 83 | 84 | else { 85 | StdOut.printf("%d to %d: not connected\n", s, v); 86 | } 87 | 88 | } 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /4-Graphs/4-2-DirectedGraphs/DirectedDFS.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac DirectedDFS.java 3 | * Execution: java DirectedDFS V E 4 | * Dependencies: Digraph.java Bag.java In.java StdOut.java 5 | * Data files: http://www.cs.princeton.edu/algs4/42directed/tinyDG.txt 6 | * 7 | * Determine single-source or multiple-source reachability in a digraph 8 | * using depth first search. 9 | * Runs in O(E + V) time. 10 | * 11 | * % java DirectedDFS tinyDG.txt 1 12 | * 1 13 | * 14 | * % java DirectedDFS tinyDG.txt 2 15 | * 0 1 2 3 4 5 16 | * 17 | * % java DirectedDFS tinyDG.txt 1 2 6 18 | * 0 1 2 3 4 5 6 9 10 11 12 19 | * 20 | *************************************************************************/ 21 | 22 | public class DirectedDFS { 23 | private boolean[] marked; // marked[v] = true if v is reachable 24 | // from source (or sources) 25 | 26 | // single-source reachability 27 | public DirectedDFS(Digraph G, int s) { 28 | marked = new boolean[G.V()]; 29 | dfs(G, s); 30 | } 31 | 32 | // multiple-source reachability 33 | public DirectedDFS(Digraph G, Iterable sources) { 34 | marked = new boolean[G.V()]; 35 | for (int v : sources) 36 | dfs(G, v); 37 | } 38 | 39 | private void dfs(Digraph G, int v) { 40 | marked[v] = true; 41 | for (int w : G.adj(v)) { 42 | if (!marked[w]) dfs(G, w); 43 | } 44 | } 45 | 46 | // is there a directed path from the source (or sources) to v? 47 | public boolean marked(int v) { 48 | return marked[v]; 49 | } 50 | 51 | // test client 52 | public static void main(String[] args) { 53 | 54 | // read in digraph from command-line argument 55 | In in = new In(args[0]); 56 | Digraph G = new Digraph(in); 57 | 58 | // read in sources from command-line arguments 59 | Bag sources = new Bag(); 60 | for (int i = 1; i < args.length; i++) { 61 | int s = Integer.parseInt(args[i]); 62 | sources.add(s); 63 | } 64 | 65 | // multiple-source reachability 66 | DirectedDFS dfs = new DirectedDFS(G, sources); 67 | 68 | // print out vertices reachable from sources 69 | for (int v = 0; v < G.V(); v++) { 70 | if (dfs.marked(v)) StdOut.print(v + " "); 71 | } 72 | StdOut.println(); 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /4-Graphs/4-2-DirectedGraphs/SymbolDigraph.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac SymbolDigraph.java 3 | * Execution: java SymbolDigraph 4 | * Dependencies: ST.java Digraph.java In.java 5 | * 6 | * % java SymbolDigraph routes.txt " " 7 | * JFK 8 | * MCO 9 | * ATL 10 | * ORD 11 | * ATL 12 | * HOU 13 | * MCO 14 | * LAX 15 | * 16 | *************************************************************************/ 17 | 18 | public class SymbolDigraph { 19 | private ST st; // string -> index 20 | private String[] keys; // index -> string 21 | private Digraph G; 22 | 23 | public SymbolDigraph(String filename, String delimiter) { 24 | st = new ST(); 25 | 26 | // First pass builds the index by reading strings to associate 27 | // distinct strings with an index 28 | In in = new In(filename); 29 | while (in.hasNextLine()) { 30 | String[] a = in.readLine().split(delimiter); 31 | for (int i = 0; i < a.length; i++) { 32 | if (!st.contains(a[i])) 33 | st.put(a[i], st.size()); 34 | } 35 | } 36 | 37 | // inverted index to get string keys in an aray 38 | keys = new String[st.size()]; 39 | for (String name : st.keys()) { 40 | keys[st.get(name)] = name; 41 | } 42 | 43 | // second pass builds the digraph by connecting first vertex on each 44 | // line to all others 45 | G = new Digraph(st.size()); 46 | in = new In(filename); 47 | while (in.hasNextLine()) { 48 | String[] a = in.readLine().split(delimiter); 49 | int v = st.get(a[0]); 50 | for (int i = 1; i < a.length; i++) { 51 | int w = st.get(a[i]); 52 | G.addEdge(v, w); 53 | } 54 | } 55 | } 56 | 57 | public boolean contains(String s) { 58 | return st.contains(s); 59 | } 60 | 61 | public int index(String s) { 62 | return st.get(s); 63 | } 64 | 65 | public String name(int v) { 66 | return keys[v]; 67 | } 68 | 69 | public Digraph G() { 70 | return G; 71 | } 72 | 73 | 74 | public static void main(String[] args) { 75 | String filename = args[0]; 76 | String delimiter = args[1]; 77 | SymbolDigraph sg = new SymbolDigraph(filename, delimiter); 78 | Digraph G = sg.G(); 79 | while (!StdIn.isEmpty()) { 80 | String t = StdIn.readLine(); 81 | for (int v : G.adj(sg.index(t))) { 82 | StdOut.println(" " + sg.name(v)); 83 | } 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /4-Graphs/4-2-DirectedGraphs/Topological.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac Topoological.java 3 | * Dependencies: Digraph.java DepthFirstOrder.java DirectedCycle.java 4 | * EdgeWeightedDigraph.java EdgeWeightedDirectedCycle.java 5 | * Data files: http://algs4.cs.princeton.edu/42directed/jobs.txt 6 | * 7 | * Compute topological ordering of a DAG or edge-weighted DAG. 8 | * Runs in O(E + V) time. 9 | * 10 | * % java Topological jobs.txt "/" 11 | * Calculus 12 | * Linear Algebra 13 | * Introduction to CS 14 | * Programming Systems 15 | * Algorithms 16 | * Theoretical CS 17 | * Artificial Intelligence 18 | * Machine Learning 19 | * Neural Networks 20 | * Robotics 21 | * Scientific Computing 22 | * Computational Biology 23 | * Databases 24 | * 25 | * 26 | *************************************************************************/ 27 | 28 | public class Topological { 29 | private Iterable order; // topological order 30 | 31 | // topological sort in a digraph 32 | public Topological(Digraph G) { 33 | DirectedCycle finder = new DirectedCycle(G); 34 | if (!finder.hasCycle()) { 35 | DepthFirstOrder dfs = new DepthFirstOrder(G); 36 | order = dfs.reversePost(); 37 | } 38 | } 39 | 40 | // topological sort in an edge-weighted digraph 41 | public Topological(EdgeWeightedDigraph G) { 42 | EdgeWeightedDirectedCycle finder = new EdgeWeightedDirectedCycle(G); 43 | if (!finder.hasCycle()) { 44 | DepthFirstOrder dfs = new DepthFirstOrder(G); 45 | order = dfs.reversePost(); 46 | } 47 | } 48 | 49 | // return topological order if a DAG; null otherwise 50 | public Iterable order() { 51 | return order; 52 | } 53 | 54 | // does digraph have a topological order? 55 | public boolean hasOrder() { 56 | return order != null; 57 | } 58 | 59 | 60 | public static void main(String[] args) { 61 | String filename = args[0]; 62 | String delimiter = args[1]; 63 | SymbolDigraph sg = new SymbolDigraph(filename, delimiter); 64 | Topological topological = new Topological(sg.G()); 65 | for (int v : topological.order()) { 66 | StdOut.println(sg.name(v)); 67 | } 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /4-Graphs/4-2-DirectedGraphs/TransitiveClosure.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac TransitiveClosure.java 3 | * Execution: java TransitiveClosure filename.txt 4 | * Dependencies: Digraph.java DepthFirstDirectedPaths.java In.java StdOut.java 5 | * Data files: http://algs4.cs.princeton.edu/42directed/tinyDG.txt 6 | * 7 | * Compute transitive closure of a digraph and support 8 | * reachability queries. 9 | * 10 | * Preprocessing time: O(V(E + V)) time. 11 | * Query time: O(1). 12 | * Space: O(V^2). 13 | * 14 | * % java TransitiveClosure tinyDG.txt 15 | * 0 1 2 3 4 5 6 7 8 9 10 11 12 16 | * -------------------------------------------- 17 | * 0: T T T T T T 18 | * 1: T 19 | * 2: T T T T T T 20 | * 3: T T T T T T 21 | * 4: T T T T T T 22 | * 5: T T T T T T 23 | * 6: T T T T T T T T T T T 24 | * 7: T T T T T T T T T T T T T 25 | * 8: T T T T T T T T T T T T T 26 | * 9: T T T T T T T T T T 27 | * 10: T T T T T T T T T T 28 | * 11: T T T T T T T T T T 29 | * 12: T T T T T T T T T T 30 | * 31 | *************************************************************************/ 32 | 33 | public class TransitiveClosure { 34 | private DirectedDFS[] tc; // tc[v] = reachable from v 35 | 36 | public TransitiveClosure(Digraph G) { 37 | tc = new DirectedDFS[G.V()]; 38 | for (int v = 0; v < G.V(); v++) 39 | tc[v] = new DirectedDFS(G, v); 40 | } 41 | 42 | public boolean reachable(int v, int w) { 43 | return tc[v].marked(w); 44 | } 45 | 46 | // test client 47 | public static void main(String[] args) { 48 | In in = new In(args[0]); 49 | Digraph G = new Digraph(in); 50 | 51 | TransitiveClosure tc = new TransitiveClosure(G); 52 | 53 | // print header 54 | StdOut.print(" "); 55 | for (int v = 0; v < G.V(); v++) 56 | StdOut.printf("%3d", v); 57 | StdOut.println(); 58 | StdOut.println("--------------------------------------------"); 59 | 60 | // print transitive closure 61 | for (int v = 0; v < G.V(); v++) { 62 | StdOut.printf("%3d: ", v); 63 | for (int w = 0; w < G.V(); w++) { 64 | if (tc.reachable(v, w)) StdOut.printf(" T"); 65 | else StdOut.printf(" "); 66 | } 67 | StdOut.println(); 68 | } 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /4-Graphs/4-2-DirectedGraphs/jobs.txt: -------------------------------------------------------------------------------- 1 | Algorithms/Theoretical CS/Databases/Scientific Computing 2 | Introduction to CS/Advanced Programming/Algorithms 3 | Advanced Programming/Scientific Computing 4 | Scientific Computing/Computational Biology 5 | Theoretical CS/Computational Biology/Artificial Intelligence 6 | Linear Algebra/Theoretical CS 7 | Calculus/Linear Algebra 8 | Artificial Intelligence/Neural Networks/Robotics/Machine Learning 9 | Machine Learning/Neural Networks 10 | -------------------------------------------------------------------------------- /4-Graphs/4-2-DirectedGraphs/tinyDAG.txt: -------------------------------------------------------------------------------- 1 | 13 2 | 15 3 | 2 3 4 | 0 6 5 | 0 1 6 | 2 0 7 | 11 12 8 | 9 12 9 | 9 10 10 | 9 11 11 | 3 5 12 | 8 7 13 | 5 4 14 | 0 5 15 | 6 4 16 | 6 9 17 | 7 6 18 | 19 | -------------------------------------------------------------------------------- /4-Graphs/4-2-DirectedGraphs/tinyDG.txt: -------------------------------------------------------------------------------- 1 | 13 2 | 22 3 | 4 2 4 | 2 3 5 | 3 2 6 | 6 0 7 | 0 1 8 | 2 0 9 | 11 12 10 | 12 9 11 | 9 10 12 | 9 11 13 | 8 9 14 | 10 12 15 | 11 4 16 | 4 3 17 | 3 5 18 | 7 8 19 | 8 7 20 | 5 4 21 | 0 5 22 | 6 4 23 | 6 9 24 | 7 6 25 | -------------------------------------------------------------------------------- /4-Graphs/4-3-MinSpanningTrees/Edge.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac Edge.java 3 | * Execution: java Edge 4 | * 5 | * Immutable weighted edge. 6 | * 7 | *************************************************************************/ 8 | 9 | /** 10 | * The Edge class represents a weighted edge in an undirected graph. 11 | *

12 | * For additional documentation, see Section 4.3 of 13 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 14 | */ 15 | public class Edge implements Comparable { 16 | 17 | private final int v; 18 | private final int w; 19 | private final double weight; 20 | 21 | /** 22 | * Create an edge between v and w with given weight. 23 | */ 24 | public Edge(int v, int w, double weight) { 25 | this.v = v; 26 | this.w = w; 27 | this.weight = weight; 28 | } 29 | 30 | /** 31 | * Return the weight of this edge. 32 | */ 33 | public double weight() { 34 | return weight; 35 | } 36 | 37 | /** 38 | * Return either endpoint of this edge. 39 | */ 40 | public int either() { 41 | return v; 42 | } 43 | 44 | /** 45 | * Return the endpoint of this edge that is different from the given vertex 46 | * (unless a self-loop). 47 | */ 48 | public int other(int vertex) { 49 | if (vertex == v) return w; 50 | else if (vertex == w) return v; 51 | else throw new RuntimeException("Illegal endpoint"); 52 | } 53 | 54 | /** 55 | * Compare edges by weight. 56 | */ 57 | public int compareTo(Edge that) { 58 | if (this.weight() < that.weight()) return -1; 59 | else if (this.weight() > that.weight()) return +1; 60 | else return 0; 61 | } 62 | 63 | 64 | /** 65 | * Return a string representation of this edge. 66 | */ 67 | public String toString() { 68 | return String.format("%d-%d %.5f", v, w, weight); 69 | } 70 | 71 | 72 | /** 73 | * Test client. 74 | */ 75 | public static void main(String[] args) { 76 | Edge e = new Edge(12, 23, 3.14); 77 | StdOut.println(e); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /4-Graphs/4-3-MinSpanningTrees/tinyEWG.txt: -------------------------------------------------------------------------------- 1 | 8 2 | 16 3 | 4 5 0.35 4 | 4 7 0.37 5 | 5 7 0.28 6 | 0 7 0.16 7 | 1 5 0.32 8 | 0 4 0.38 9 | 2 3 0.17 10 | 1 7 0.19 11 | 0 2 0.26 12 | 1 2 0.36 13 | 1 3 0.29 14 | 2 7 0.34 15 | 6 2 0.40 16 | 3 6 0.52 17 | 6 0 0.58 18 | 6 4 0.93 19 | -------------------------------------------------------------------------------- /4-Graphs/4-4-ShortestPaths/AcyclicSP.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac AcyclicSP.java 3 | * Execution: java AcyclicSP V E 4 | * Dependencies: EdgeWeightedDigraph.java DirectedEdge.java Topological.java 5 | * Data files: http://algs4.cs.princeton.edu/44sp/tinyEWDAG.txt 6 | * 7 | * Computes shortest paths in an edge-weighted acyclic digraph. 8 | * 9 | * Remark: should probably check that graph is a DAG before running 10 | * 11 | * % java AcyclicSP tinyEWDAG.txt 5 12 | * 5 to 0 (0.73) 5->4 0.35 4->0 0.38 13 | * 5 to 1 (0.32) 5->1 0.32 14 | * 5 to 2 (0.62) 5->7 0.28 7->2 0.34 15 | * 5 to 3 (0.61) 5->1 0.32 1->3 0.29 16 | * 5 to 4 (0.35) 5->4 0.35 17 | * 5 to 5 (0.00) 18 | * 5 to 6 (1.13) 5->1 0.32 1->3 0.29 3->6 0.52 19 | * 5 to 7 (0.28) 5->7 0.28 20 | * 21 | *************************************************************************/ 22 | 23 | public class AcyclicSP { 24 | private double[] distTo; // distTo[v] = distance of shortest s->v path 25 | private DirectedEdge[] edgeTo; // edgeTo[v] = last edge on shortest s->v path 26 | 27 | public AcyclicSP(EdgeWeightedDigraph G, int s) { 28 | distTo = new double[G.V()]; 29 | edgeTo = new DirectedEdge[G.V()]; 30 | for (int v = 0; v < G.V(); v++) 31 | distTo[v] = Double.POSITIVE_INFINITY; 32 | distTo[s] = 0.0; 33 | 34 | // visit vertices in toplogical order 35 | Topological topological = new Topological(G); 36 | for (int v : topological.order()) { 37 | for (DirectedEdge e : G.adj(v)) 38 | relax(e); 39 | } 40 | } 41 | 42 | // relax edge e 43 | private void relax(DirectedEdge e) { 44 | int v = e.from(), w = e.to(); 45 | if (distTo[w] > distTo[v] + e.weight()) { 46 | distTo[w] = distTo[v] + e.weight(); 47 | edgeTo[w] = e; 48 | } 49 | } 50 | 51 | // return length of the shortest path from s to v, infinity if no such path 52 | public double distTo(int v) { 53 | return distTo[v]; 54 | } 55 | 56 | // is there a path from s to v? 57 | public boolean hasPathTo(int v) { 58 | return distTo[v] < Double.POSITIVE_INFINITY; 59 | } 60 | 61 | // return view of the shortest path from s to v, null if no such path 62 | public Iterable pathTo(int v) { 63 | if (!hasPathTo(v)) return null; 64 | Stack path = new Stack(); 65 | for (DirectedEdge e = edgeTo[v]; e != null; e = edgeTo[e.from()]) { 66 | path.push(e); 67 | } 68 | return path; 69 | } 70 | 71 | 72 | 73 | public static void main(String[] args) { 74 | In in = new In(args[0]); 75 | int s = Integer.parseInt(args[1]); 76 | EdgeWeightedDigraph G = new EdgeWeightedDigraph(in); 77 | 78 | // find shortest path from s to each other vertex in DAG 79 | AcyclicSP sp = new AcyclicSP(G, s); 80 | for (int v = 0; v < G.V(); v++) { 81 | if (sp.hasPathTo(v)) { 82 | StdOut.printf("%d to %d (%.2f) ", s, v, sp.distTo(v)); 83 | for (DirectedEdge e : sp.pathTo(v)) { 84 | StdOut.print(e + " "); 85 | } 86 | StdOut.println(); 87 | } 88 | else { 89 | StdOut.printf("%d to %d no path\n", s, v); 90 | } 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /4-Graphs/4-4-ShortestPaths/Arbitrage.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac Arbitrage.java 3 | * Execution: java Arbitrage < input.txt 4 | * Dependencies: EdgeWeightedDigraph.java DirectedEdge.java 5 | * BellmanFordSP.java 6 | * Data file: http://algs4.cs.princeton.edu/44sp/rates.txt 7 | * 8 | * Arbitrage detection. 9 | * 10 | * % more rates.txt 11 | * 5 12 | * USD 1 0.741 0.657 1.061 1.005 13 | * EUR 1.349 1 0.888 1.433 1.366 14 | * GBP 1.521 1.126 1 1.614 1.538 15 | * CHF 0.942 0.698 0.619 1 0.953 16 | * CAD 0.995 0.732 0.650 1.049 1 17 | * 18 | * % java Arbitrage < rates.txt 19 | * 1000.00000 USD = 741.00000 EUR 20 | * 741.00000 EUR = 1012.20600 CAD 21 | * 1012.20600 CAD = 1007.14497 USD 22 | * 23 | *************************************************************************/ 24 | 25 | public class Arbitrage { 26 | 27 | public static void main(String[] args) { 28 | 29 | // V currencies 30 | int V = StdIn.readInt(); 31 | String[] name = new String[V]; 32 | 33 | // create complete network 34 | EdgeWeightedDigraph G = new EdgeWeightedDigraph(V); 35 | for (int v = 0; v < V; v++) { 36 | name[v] = StdIn.readString(); 37 | for (int w = 0; w < V; w++) { 38 | double rate = StdIn.readDouble(); 39 | DirectedEdge e = new DirectedEdge(v, w, -Math.log(rate)); 40 | G.addEdge(e); 41 | } 42 | } 43 | 44 | // find negative cycle 45 | BellmanFordSP spt = new BellmanFordSP(G, 0); 46 | if (spt.hasNegativeCycle()) { 47 | double stake = 1000.0; 48 | for (DirectedEdge e : spt.negativeCycle()) { 49 | StdOut.printf("%10.5f %s ", stake, name[e.from()]); 50 | stake *= Math.exp(-e.weight()); 51 | StdOut.printf("= %10.5f %s\n", stake, name[e.to()]); 52 | } 53 | } 54 | else { 55 | StdOut.println("No arbitrage opportunity"); 56 | } 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /4-Graphs/4-4-ShortestPaths/CPM.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac CPM.java 3 | * Execution: java CPM < input.txt 4 | * Dependencies: EdgeWeightedDigraph.java AcyclicDigraphLP.java StdOut.java 5 | * Data files: http://algs4.cs.princeton.edu/44sp/jobsPC.txt 6 | * 7 | * Critical path method. 8 | * 9 | * % java CPM < jobsPC.txt 10 | * job start finish 11 | * -------------------- 12 | * 0 0.0 41.0 13 | * 1 41.0 92.0 14 | * 2 123.0 173.0 15 | * 3 91.0 127.0 16 | * 4 70.0 108.0 17 | * 5 0.0 45.0 18 | * 6 70.0 91.0 19 | * 7 41.0 73.0 20 | * 8 91.0 123.0 21 | * 9 41.0 70.0 22 | * Finish time: 173.0 23 | * 24 | *************************************************************************/ 25 | 26 | public class CPM { 27 | 28 | public static void main(String[] args) { 29 | 30 | // number of jobs 31 | int N = StdIn.readInt(); 32 | 33 | // source and sink 34 | int source = 2*N; 35 | int sink = 2*N + 1; 36 | 37 | // build network 38 | EdgeWeightedDigraph G = new EdgeWeightedDigraph(2*N + 2); 39 | for (int i = 0; i < N; i++) { 40 | double duration = StdIn.readDouble(); 41 | G.addEdge(new DirectedEdge(source, i, 0.0)); 42 | G.addEdge(new DirectedEdge(i+N, sink, 0.0)); 43 | G.addEdge(new DirectedEdge(i, i+N, duration)); 44 | 45 | // precedence constraints 46 | int M = StdIn.readInt(); 47 | for (int j = 0; j < M; j++) { 48 | int precedent = StdIn.readInt(); 49 | G.addEdge(new DirectedEdge(N+i, precedent, 0.0)); 50 | } 51 | } 52 | 53 | // compute longest path 54 | AcyclicLP lp = new AcyclicLP(G, source); 55 | 56 | // print results 57 | StdOut.println(" job start finish"); 58 | StdOut.println("--------------------"); 59 | for (int i = 0; i < N; i++) { 60 | StdOut.printf("%4d %7.1f %7.1f\n", i, lp.distTo(i), lp.distTo(i+N)); 61 | } 62 | StdOut.printf("Finish time: %7.1f\n", lp.distTo(sink)); 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /4-Graphs/4-4-ShortestPaths/DijkstraAllPairsSP.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac DijkstraAllPairsSP.java 3 | * Dependencies: EdgeWeightedDigraph.java Dijkstra.java 4 | * 5 | * Dijkstra's algorithm run from each vertex. 6 | * Takes time proportional to E V log V and space proportional to EV. 7 | * 8 | *************************************************************************/ 9 | 10 | public class DijkstraAllPairsSP { 11 | private DijkstraSP[] all; 12 | 13 | public DijkstraAllPairsSP(EdgeWeightedDigraph G) { 14 | all = new DijkstraSP[G.V()]; 15 | for (int v = 0; v < G.V(); v++) 16 | all[v] = new DijkstraSP(G, v); 17 | } 18 | 19 | Iterable path(int s, int t) { 20 | return all[s].pathTo(t); 21 | } 22 | 23 | double dist(int s, int t) { 24 | return all[s].distTo(t); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /4-Graphs/4-4-ShortestPaths/DirectedEdge.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac DirectedEdge.java 3 | * Execution: java DirectedEdge 4 | * 5 | * Immutable weighted directed edge. 6 | * 7 | *************************************************************************/ 8 | 9 | /** 10 | * The DirectedEdge class represents a weighted edge in an directed graph. 11 | *

12 | * For additional documentation, see Section 4.4 of 13 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 14 | */ 15 | 16 | public class DirectedEdge { 17 | private final int v; 18 | private final int w; 19 | private final double weight; 20 | 21 | /** 22 | * Create a directed edge from v to w with given weight. 23 | */ 24 | public DirectedEdge(int v, int w, double weight) { 25 | this.v = v; 26 | this.w = w; 27 | this.weight = weight; 28 | } 29 | 30 | /** 31 | * Return the vertex where this edge begins. 32 | */ 33 | public int from() { 34 | return v; 35 | } 36 | 37 | /** 38 | * Return the vertex where this edge ends. 39 | */ 40 | public int to() { 41 | return w; 42 | } 43 | 44 | /** 45 | * Return the weight of this edge. 46 | */ 47 | public double weight() { return weight; } 48 | 49 | /** 50 | * Return a string representation of this edge. 51 | */ 52 | public String toString() { 53 | return v + "->" + w + " " + String.format("%5.2f", weight); 54 | } 55 | 56 | /** 57 | * Test client. 58 | */ 59 | public static void main(String[] args) { 60 | DirectedEdge e = new DirectedEdge(12, 23, 3.14); 61 | StdOut.println(e); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /4-Graphs/4-4-ShortestPaths/jobsPC.txt: -------------------------------------------------------------------------------- 1 | 10 2 | 41.0 3 1 7 9 3 | 51.0 1 2 4 | 50.0 0 5 | 36.0 0 6 | 38.0 0 7 | 45.0 0 8 | 21.0 2 3 8 9 | 32.0 2 3 8 10 | 32.0 1 2 11 | 29.0 2 4 6 12 | -------------------------------------------------------------------------------- /4-Graphs/4-4-ShortestPaths/rates.txt: -------------------------------------------------------------------------------- 1 | 5 2 | USD 1 0.741 0.657 1.061 1.005 3 | EUR 1.349 1 0.888 1.433 1.366 4 | GBP 1.521 1.126 1 1.614 1.538 5 | CHF 0.942 0.698 0.619 1 0.953 6 | CAD 0.995 0.732 0.650 1.049 1 7 | 8 | -------------------------------------------------------------------------------- /4-Graphs/4-4-ShortestPaths/tinyEWD.txt: -------------------------------------------------------------------------------- 1 | 8 2 | 15 3 | 4 5 0.35 4 | 5 4 0.35 5 | 4 7 0.37 6 | 5 7 0.28 7 | 7 5 0.28 8 | 5 1 0.32 9 | 0 4 0.38 10 | 0 2 0.26 11 | 7 3 0.39 12 | 1 3 0.29 13 | 2 7 0.34 14 | 6 2 0.40 15 | 3 6 0.52 16 | 6 0 0.58 17 | 6 4 0.93 18 | -------------------------------------------------------------------------------- /4-Graphs/4-4-ShortestPaths/tinyEWDAG.txt: -------------------------------------------------------------------------------- 1 | 8 2 | 13 3 | 5 4 0.35 4 | 4 7 0.37 5 | 5 7 0.28 6 | 5 1 0.32 7 | 4 0 0.38 8 | 0 2 0.26 9 | 3 7 0.39 10 | 1 3 0.29 11 | 7 2 0.34 12 | 6 2 0.40 13 | 3 6 0.52 14 | 6 0 0.58 15 | 6 4 0.93 16 | -------------------------------------------------------------------------------- /4-Graphs/4-4-ShortestPaths/tinyEWDn.txt: -------------------------------------------------------------------------------- 1 | 8 2 | 15 3 | 4 5 0.35 4 | 5 4 0.35 5 | 4 7 0.37 6 | 5 7 0.28 7 | 7 5 0.28 8 | 5 1 0.32 9 | 0 4 0.38 10 | 0 2 0.26 11 | 7 3 0.39 12 | 1 3 0.29 13 | 2 7 0.34 14 | 6 2 -1.20 15 | 3 6 0.52 16 | 6 0 -1.40 17 | 6 4 -1.25 18 | -------------------------------------------------------------------------------- /4-Graphs/4-4-ShortestPaths/tinyEWDnc.txt: -------------------------------------------------------------------------------- 1 | 8 2 | 15 3 | 4 5 0.35 4 | 5 4 -0.66 5 | 4 7 0.37 6 | 5 7 0.28 7 | 7 5 0.28 8 | 5 1 0.32 9 | 0 4 0.38 10 | 0 2 0.26 11 | 7 3 0.39 12 | 1 3 0.29 13 | 2 7 0.34 14 | 6 2 0.40 15 | 3 6 0.52 16 | 6 0 0.58 17 | 6 4 0.93 18 | -------------------------------------------------------------------------------- /5-Strings/5-1-StringSorts/LSD.java: -------------------------------------------------------------------------------- 1 | /*********************************************************************************** 2 | * Compilation: javac LSD.java 3 | * Execution: java LSD < input.txt 4 | * 5 | * LSD radix sort an array of extended ASCII strings, each of length W. 6 | * 7 | * % java LSD < words3.txt 8 | * all 9 | * bad 10 | * bed 11 | * bug 12 | * dad 13 | * ... 14 | * yes 15 | * yet 16 | * zoo 17 | * 18 | ***********************************************************************************/ 19 | 20 | public class LSD { 21 | 22 | // LSD radix sort 23 | public static void sort(String[] a, int W) { 24 | int N = a.length; 25 | int R = 256; // extend ASCII alphabet size 26 | String[] aux = new String[N]; 27 | 28 | for (int d = W-1; d >= 0; d--) { 29 | // sort by key-indexed counting on dth character 30 | 31 | // compute frequency counts 32 | int[] count = new int[R+1]; 33 | for (int i = 0; i < N; i++) 34 | count[a[i].charAt(d) + 1]++; 35 | 36 | // compute cumulates 37 | for (int r = 0; r < R; r++) 38 | count[r+1] += count[r]; 39 | 40 | // move data 41 | for (int i = 0; i < N; i++) 42 | aux[count[a[i].charAt(d)]++] = a[i]; 43 | 44 | // copy back 45 | for (int i = 0; i < N; i++) 46 | a[i] = aux[i]; 47 | } 48 | } 49 | 50 | 51 | public static void main(String[] args) { 52 | String[] a = StdIn.readStrings(); 53 | int N = a.length; 54 | 55 | // check that strings have fixed length 56 | int W = a[0].length(); 57 | for (int i = 0; i < N; i++) 58 | assert a[i].length() == W : "Strings must have fixed length"; 59 | 60 | // sort the strings 61 | sort(a, W); 62 | 63 | // print results 64 | for (int i = 0; i < N; i++) 65 | StdOut.println(a[i]); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /5-Strings/5-1-StringSorts/MSD.java: -------------------------------------------------------------------------------- 1 | /*********************************************************************************** 2 | * Compilation: javac MSD.java 3 | * Execution: java MSD < input.txt 4 | * 5 | * Reads extended ASCII string from standard input and MSD radix sorts them. 6 | * 7 | * % java MSD < shells.txt 8 | * are 9 | * by 10 | * sea 11 | * seashells 12 | * seashells 13 | * sells 14 | * sells 15 | * she 16 | * she 17 | * shells 18 | * shore 19 | * surely 20 | * the 21 | * the 22 | * 23 | ***********************************************************************************/ 24 | 25 | public class MSD { 26 | private static final int R = 256; // extended ASCII alphabet size 27 | private static final int CUTOFF = 15; // cutoff to insertion sort 28 | 29 | // sort array of strings 30 | public static void sort(String[] a) { 31 | int N = a.length; 32 | String[] aux = new String[N]; 33 | sort(a, 0, N-1, 0, aux); 34 | } 35 | 36 | // return dth character of s, -1 if d = length of string 37 | private static int charAt(String s, int d) { 38 | assert d >= 0 && d <= s.length(); 39 | if (d == s.length()) return -1; 40 | return s.charAt(d); 41 | } 42 | 43 | // sort from a[lo] to a[hi], starting at the dth character 44 | private static void sort(String[] a, int lo, int hi, int d, String[] aux) { 45 | 46 | // cutoff to insertion sort for small subarrays 47 | if (hi <= lo + CUTOFF) { 48 | insertion(a, lo, hi, d); 49 | return; 50 | } 51 | 52 | // compute frequency counts 53 | int[] count = new int[R+2]; 54 | for (int i = lo; i <= hi; i++) { 55 | int c = charAt(a[i], d); 56 | count[c+2]++; 57 | } 58 | 59 | // transform counts to indicies 60 | for (int r = 0; r < R+1; r++) 61 | count[r+1] += count[r]; 62 | 63 | // distribute 64 | for (int i = lo; i <= hi; i++) { 65 | int c = charAt(a[i], d); 66 | aux[count[c+1]++] = a[i]; 67 | } 68 | 69 | // copy back 70 | for (int i = lo; i <= hi; i++) 71 | a[i] = aux[i - lo]; 72 | 73 | 74 | // recursively sort for each character 75 | for (int r = 0; r < R; r++) 76 | sort(a, lo + count[r], lo + count[r+1] - 1, d+1, aux); 77 | } 78 | 79 | 80 | // return dth character of s, -1 if d = length of string 81 | private static void insertion(String[] a, int lo, int hi, int d) { 82 | for (int i = lo; i <= hi; i++) 83 | for (int j = i; j > lo && less(a[j], a[j-1], d); j--) 84 | exch(a, j, j-1); 85 | } 86 | 87 | // exchange a[i] and a[j] 88 | private static void exch(String[] a, int i, int j) { 89 | String temp = a[i]; 90 | a[i] = a[j]; 91 | a[j] = temp; 92 | } 93 | 94 | // is v less than w, starting at character d 95 | private static boolean less(String v, String w, int d) { 96 | assert v.substring(0, d).equals(w.substring(0, d)); 97 | return v.substring(d).compareTo(w.substring(d)) < 0; 98 | } 99 | 100 | 101 | public static void main(String[] args) { 102 | String[] a = StdIn.readStrings(); 103 | int N = a.length; 104 | sort(a); 105 | for (int i = 0; i < N; i++) 106 | StdOut.println(a[i]); 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /5-Strings/5-1-StringSorts/shells.txt: -------------------------------------------------------------------------------- 1 | she sells seashells by the sea shore 2 | the shells she sells are surely seashells 3 | -------------------------------------------------------------------------------- /5-Strings/5-1-StringSorts/words3.txt: -------------------------------------------------------------------------------- 1 | bed bug dad yes zoo 2 | now for tip ilk dim 3 | tag jot sob nob sky 4 | hut men egg few jay 5 | owl joy rap gig wee 6 | was wad fee tap tar 7 | dug jam all bad yet 8 | -------------------------------------------------------------------------------- /5-Strings/5-2-Tries/shellsST.txt: -------------------------------------------------------------------------------- 1 | she sells sea shells by the sea shore 2 | -------------------------------------------------------------------------------- /5-Strings/5-4-RegularExpressions/GREP.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac GREP.java 3 | * Execution: java GREP regexp < input.txt 4 | * Dependencies: NFA.java 5 | * Data files: http://algs4.cs.princeton.edu/54regexp/tinyL.txt 6 | * 7 | * This program takes an RE as a command-line argument and prints 8 | * the lines from standard input having some substring that 9 | * is in the language described by the RE. 10 | * 11 | * % more tinyL.txt 12 | * AC 13 | * AD 14 | * AAA 15 | * ABD 16 | * ADD 17 | * BCD 18 | * ABCCBD 19 | * BABAAA 20 | * BABBAAA 21 | * 22 | * % java GREP "(A*B|AC)D" < tinyL.txt 23 | * ABD 24 | * ABCCBD 25 | * 26 | *************************************************************************/ 27 | 28 | public class GREP { 29 | public static void main(String[] args) { 30 | String regexp = "(.*" + args[0] + ".*)"; 31 | NFA nfa = new NFA(regexp); 32 | while (StdIn.hasNextLine()) { 33 | String txt = StdIn.readLine(); 34 | if (nfa.recognizes(txt)) { 35 | StdOut.println(txt); 36 | } 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /5-Strings/5-4-RegularExpressions/NFA.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac NFA.java 3 | * Execution: java NFA regexp text 4 | * Dependencies: Stack.java Bag.java Digraph.java DirectedDFS.java 5 | * 6 | * % java NFA "(A*B|AC)D" AAAABD 7 | * true 8 | * 9 | * % java NFA "(A*B|AC)D" AAAAC 10 | * false 11 | * 12 | * % java NFA "(a|(bc)*d)*" abcbcd 13 | * true 14 | * 15 | * % java NFA "(a|(bc)*d)*" abcbcbcdaaaabcbcdaaaddd 16 | * true 17 | * 18 | *************************************************************************/ 19 | 20 | public class NFA { 21 | 22 | private Digraph G; // digraph of epsilon transitions 23 | private String regexp; // regular expression 24 | private int M; // number of characters in regular expression 25 | 26 | // Create the NFA for the given RE 27 | public NFA(String regexp) { 28 | this.regexp = regexp; 29 | M = regexp.length(); 30 | Stack ops = new Stack(); 31 | G = new Digraph(M+1); 32 | for (int i = 0; i < M; i++) { 33 | int lp = i; 34 | if (regexp.charAt(i) == '(' || regexp.charAt(i) == '|') 35 | ops.push(i); 36 | else if (regexp.charAt(i) == ')') { 37 | int or = ops.pop(); 38 | if (regexp.charAt(or) == '|') { 39 | lp = ops.pop(); 40 | G.addEdge(lp, or+1); 41 | G.addEdge(or, i); 42 | } 43 | else if (regexp.charAt(or) == '(') 44 | lp = or; 45 | else assert false; 46 | } 47 | 48 | // Lookahead; 49 | if (i < M-1 && regexp.charAt(i+1) == '*') { 50 | G.addEdge(lp, i+1); 51 | G.addEdge(i+1, lp); 52 | } 53 | if (regexp.charAt(i) == '(' || regexp.charAt(i) == '*' || regexp.charAt(i) == ')') 54 | G.addEdge(i, i+1); 55 | } 56 | } 57 | 58 | // Does the NFA recognize txt? 59 | public boolean recognizes(String txt) { 60 | DirectedDFS dfs = new DirectedDFS(G, 0); 61 | Bag pc = new Bag(); 62 | for (int v = 0; v < G.V(); v++) 63 | if (dfs.marked(v)) pc.add(v); 64 | 65 | // Compute possible NFA states for txt[i+1]. 66 | for (int i = 0; i < txt.length(); i++) { 67 | Bag match = new Bag(); 68 | for (int v : pc) { 69 | if (v == M) continue; 70 | if ((regexp.charAt(v) == txt.charAt(i)) || regexp.charAt(v) == '.') 71 | match.add(v+1); 72 | } 73 | dfs = new DirectedDFS(G, match); 74 | pc = new Bag(); 75 | for (int v = 0; v < G.V(); v++) 76 | if (dfs.marked(v)) pc.add(v); 77 | } 78 | for (int v : pc) 79 | if (v == M) return true; 80 | return false; 81 | } 82 | 83 | 84 | public static void main(String[] args) { 85 | String regexp = "(" + args[0] + ")"; 86 | String txt = args[1]; 87 | NFA nfa = new NFA(regexp); 88 | StdOut.println(nfa.recognizes(txt)); 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /5-Strings/5-4-RegularExpressions/tinyL.txt: -------------------------------------------------------------------------------- 1 | AC 2 | AD 3 | AAA 4 | ABD 5 | ADD 6 | BCD 7 | ABCCBD 8 | BABAAA 9 | BABBAAA 10 | -------------------------------------------------------------------------------- /5-Strings/5-5-DataCompression/4runs.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aistrate/AlgorithmsSedgewick/06703c1371ffdf669d3996baa9e9684d13cdcc82/5-Strings/5-5-DataCompression/4runs.bin -------------------------------------------------------------------------------- /5-Strings/5-5-DataCompression/BinaryDump.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac BinaryDump.java 3 | * Execution: java BinaryDump N < file 4 | * Dependencies: BinaryStdIn.java 5 | * Data file: http://introcs.cs.princeton.edu/stdlib/abra.txt 6 | * 7 | * Reads in a binary file and writes out the bits, N per line. 8 | * 9 | * % more abra.txt 10 | * ABRACADABRA! 11 | * 12 | * % java BinaryDump 16 < abra.txt 13 | * 0100000101000010 14 | * 0101001001000001 15 | * 0100001101000001 16 | * 0100010001000001 17 | * 0100001001010010 18 | * 0100000100100001 19 | * 96 bits 20 | * 21 | *************************************************************************/ 22 | 23 | public class BinaryDump { 24 | 25 | public static void main(String[] args) { 26 | int BITS_PER_LINE = 16; 27 | if (args.length == 1) { 28 | BITS_PER_LINE = Integer.parseInt(args[0]); 29 | } 30 | 31 | int count; 32 | for (count = 0; !BinaryStdIn.isEmpty(); count++) { 33 | if (BITS_PER_LINE == 0) { BinaryStdIn.readBoolean(); continue; } 34 | else if (count != 0 && count % BITS_PER_LINE == 0) StdOut.println(); 35 | if (BinaryStdIn.readBoolean()) StdOut.print(1); 36 | else StdOut.print(0); 37 | } 38 | if (BITS_PER_LINE != 0) StdOut.println(); 39 | StdOut.println(count + " bits"); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /5-Strings/5-5-DataCompression/Count.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac Count.java 3 | * Execution: java Count alpha < input.txt 4 | * 5 | * Create an alphabet specified on the command line, read in a 6 | * sequence of characters over that alphabet (ignoring characters 7 | * not in the alphabet), computes the frequency of occurrence of 8 | * each character, and print out the results. 9 | * 10 | * % java Count ABCDR < abra.txt 11 | * A 5 12 | * B 2 13 | * C 1 14 | * D 1 15 | * R 2 16 | * 17 | * % java Count 0123456789 < pi.txt 18 | * 0 99959 19 | * 1 99757 20 | * 2 100026 21 | * 3 100230 22 | * 4 100230 23 | * 5 100359 24 | * 6 99548 25 | * 7 99800 26 | * 8 99985 27 | * 9 100106 28 | * 29 | *************************************************************************/ 30 | 31 | 32 | 33 | public class Count { 34 | public static void main(String[] args) { 35 | Alphabet alpha = new Alphabet(args[0]); 36 | int R = alpha.R(); 37 | int[] count = new int[R]; 38 | String a = StdIn.readAll(); 39 | int N = a.length(); 40 | for (int i = 0; i < N; i++) 41 | if (alpha.contains(a.charAt(i))) 42 | count[alpha.toIndex(a.charAt(i))]++; 43 | for (int c = 0; c < R; c++) 44 | StdOut.println(alpha.toChar(c) + " " + count[c]); 45 | } 46 | } 47 | 48 | -------------------------------------------------------------------------------- /5-Strings/5-5-DataCompression/Genome.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac Genome.java 3 | * Execution: java Genome - < input.txt (compress) 4 | * Execution: java Genome + < input.txt (expand) 5 | * Dependencies: BinaryIn.java BinaryOut.java 6 | * 7 | * Compress or expand a genomic sequence using a 2-bit code. 8 | * 9 | * % more genomeTiny.txt 10 | * ATAGATGCATAGCGCATAGCTAGATGTGCTAGC 11 | * 12 | * % java Genome - < genomeTiny.txt | java Genome + 13 | * ATAGATGCATAGCGCATAGCTAGATGTGCTAGC 14 | * 15 | *************************************************************************/ 16 | 17 | public class Genome { 18 | 19 | public static void compress() { 20 | Alphabet DNA = new Alphabet("ACTG"); 21 | String s = BinaryStdIn.readString(); 22 | int N = s.length(); 23 | BinaryStdOut.write(N); 24 | 25 | // Write two-bit code for char. 26 | for (int i = 0; i < N; i++) { 27 | int d = DNA.toIndex(s.charAt(i)); 28 | BinaryStdOut.write(d, 2); 29 | } 30 | BinaryStdOut.close(); 31 | } 32 | 33 | public static void expand() { 34 | Alphabet DNA = new Alphabet("ACTG"); 35 | int N = BinaryStdIn.readInt(); 36 | // Read two bits; write char. 37 | for (int i = 0; i < N; i++) { 38 | char c = BinaryStdIn.readChar(2); 39 | BinaryStdOut.write(DNA.toChar(c)); 40 | } 41 | BinaryStdOut.close(); 42 | } 43 | 44 | 45 | public static void main(String[] args) { 46 | if (args[0].equals("-")) compress(); 47 | else if (args[0].equals("+")) expand(); 48 | else throw new RuntimeException("Illegal command line argument"); 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /5-Strings/5-5-DataCompression/HexDump.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac HexDump.java 3 | * Execution: java HexDump < file 4 | * Dependencies: BinaryStdIn.java 5 | * Data file: http://introcs.cs.princeton.edu/stdlib/abra.txt 6 | * 7 | * Reads in a binary file and writes out the bytes in hex, 16 per line. 8 | * 9 | * % more abra.txt 10 | * ABRACADABRA! 11 | * 12 | * % java HexDump 16 < abra.txt 13 | * 41 42 52 41 43 41 44 41 42 52 41 21 14 | * 96 bits 15 | * 16 | * % hexdump < abra.txt 17 | * 18 | * % od -t x1 < abra.txt 19 | * 0000000 41 42 52 41 43 41 44 41 42 52 41 21 20 | * 0000014 21 | * 22 | *************************************************************************/ 23 | 24 | public class HexDump { 25 | 26 | public static void main(String[] args) { 27 | int BYTES_PER_LINE = 16; 28 | if (args.length == 1) { 29 | BYTES_PER_LINE = Integer.parseInt(args[0]); 30 | } 31 | 32 | int i; 33 | for (i = 0; !BinaryStdIn.isEmpty(); i++) { 34 | if (BYTES_PER_LINE == 0) { BinaryStdIn.readChar(); continue; } 35 | if (i == 0) StdOut.printf(""); 36 | else if (i % BYTES_PER_LINE == 0) StdOut.printf("\n", i); 37 | else StdOut.print(" "); 38 | char c = BinaryStdIn.readChar(); 39 | StdOut.printf("%02x", c & 0xff); 40 | } 41 | if (BYTES_PER_LINE != 0) StdOut.println(); 42 | StdOut.println((i*8) + " bits"); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /5-Strings/5-5-DataCompression/LZW.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac LZW.java 3 | * Execution: java LZW - < input.txt (compress) 4 | * Execution: java LZW + < input.txt (expand) 5 | * Dependencies: BinaryIn.java BinaryOut.java 6 | * 7 | * Compress or expand binary input from standard input using LZW. 8 | * 9 | * 10 | *************************************************************************/ 11 | 12 | public class LZW { 13 | private static final int R = 256; // number of input chars 14 | private static final int L = 4096; // number of codewords = 2^W 15 | private static final int W = 12; // codeword width 16 | 17 | public static void compress() { 18 | String input = BinaryStdIn.readString(); 19 | TST st = new TST(); 20 | for (int i = 0; i < R; i++) 21 | st.put("" + (char) i, i); 22 | int code = R+1; // R is codeword for EOF 23 | 24 | while (input.length() > 0) { 25 | String s = st.longestPrefixOf(input); // Find max prefix match s. 26 | BinaryStdOut.write(st.get(s), W); // Print s's encoding. 27 | int t = s.length(); 28 | if (t < input.length() && code < L) // Add s to symbol table. 29 | st.put(input.substring(0, t + 1), code++); 30 | input = input.substring(t); // Scan past s in input. 31 | } 32 | BinaryStdOut.write(R, W); 33 | BinaryStdOut.close(); 34 | } 35 | 36 | 37 | public static void expand() { 38 | String[] st = new String[L]; 39 | int i; // next available codeword value 40 | 41 | // initialize symbol table with all 1-character strings 42 | for (i = 0; i < R; i++) 43 | st[i] = "" + (char) i; 44 | st[i++] = ""; // (unused) lookahead for EOF 45 | 46 | int codeword = BinaryStdIn.readInt(W); 47 | String val = st[codeword]; 48 | 49 | while (true) { 50 | BinaryStdOut.write(val); 51 | codeword = BinaryStdIn.readInt(W); 52 | if (codeword == R) break; 53 | String s = st[codeword]; 54 | if (i == codeword) s = val + val.charAt(0); // special case hack 55 | if (i < L) st[i++] = val + s.charAt(0); 56 | val = s; 57 | } 58 | BinaryStdOut.close(); 59 | } 60 | 61 | 62 | 63 | public static void main(String[] args) { 64 | if (args[0].equals("-")) compress(); 65 | else if (args[0].equals("+")) expand(); 66 | else throw new RuntimeException("Illegal command line argument"); 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /5-Strings/5-5-DataCompression/PictureDump.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac PictureDump.java 3 | * Execution: java PictureDump width height < file 4 | * Dependencies: BinaryStdIn.java Picture.java 5 | * Data file: http://introcs.cs.princeton.edu/stdlib/abra.txt 6 | * 7 | * Reads in a binary file and writes out the bits as w-by-h picture, 8 | * with the 1 bits in black and the 0 bits in white. 9 | * 10 | * % more abra.txt 11 | * ABRACADABRA! 12 | * 13 | * % java PictureDump 16 6 < abra.txt 14 | * 15 | *************************************************************************/ 16 | import java.awt.Color; 17 | 18 | public class PictureDump { 19 | 20 | public static void main(String[] args) { 21 | int width = Integer.parseInt(args[0]); 22 | int height = Integer.parseInt(args[1]); 23 | Picture pic = new Picture(width, height); 24 | int count = 0; 25 | for (int i = 0; i < height; i++) { 26 | for (int j = 0; j < width; j++) { 27 | pic.set(j, i, Color.RED); 28 | if (!BinaryStdIn.isEmpty()) { 29 | count++; 30 | boolean bit = BinaryStdIn.readBoolean(); 31 | if (bit) pic.set(j, i, Color.BLACK); 32 | else pic.set(j, i, Color.WHITE); 33 | } 34 | } 35 | } 36 | pic.show(); 37 | StdOut.println(count + " bits"); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /5-Strings/5-5-DataCompression/RunLength.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac RunLength.java 3 | * Execution: java RunLength - < input.txt (compress) 4 | * Execution: java RunLength + < input.txt (expand) 5 | * Dependencies: BinaryIn.java BinaryOut.java 6 | * 7 | * Compress or expand binary input from standard input using 8 | * run-length encoding. 9 | * 10 | * % java BinaryDump 40 < 4runs.bin 11 | * 0000000000000001111111000000011111111111 12 | * 40 bits 13 | * 14 | * This has runs of 15 0s, 7 1s, 7 0s, and 11 1s. 15 | * 16 | * % java RunLength - < 4runs.bin | java HexDump 17 | * 0f 07 07 0b 18 | * 4 bytes 19 | * 20 | *************************************************************************/ 21 | 22 | public class RunLength { 23 | private static final int R = 256; 24 | private static final int lgR = 8; 25 | 26 | public static void expand() { 27 | boolean b = false; 28 | while (!BinaryStdIn.isEmpty()) { 29 | int run = BinaryStdIn.readInt(lgR); 30 | for (int i = 0; i < run; i++) 31 | BinaryStdOut.write(b); 32 | b = !b; 33 | } 34 | BinaryStdOut.close(); 35 | } 36 | 37 | public static void compress() { 38 | char run = 0; 39 | boolean old = false; 40 | while (!BinaryStdIn.isEmpty()) { 41 | boolean b = BinaryStdIn.readBoolean(); 42 | if (b != old) { 43 | BinaryStdOut.write(run, lgR); 44 | run = 1; 45 | old = !old; 46 | } 47 | else { 48 | if (run == R-1) { 49 | BinaryStdOut.write(run, lgR); 50 | run = 0; 51 | BinaryStdOut.write(run, lgR); 52 | } 53 | run++; 54 | } 55 | } 56 | BinaryStdOut.write(run, lgR); 57 | BinaryStdOut.close(); 58 | } 59 | 60 | 61 | public static void main(String[] args) { 62 | if (args[0].equals("-")) compress(); 63 | else if (args[0].equals("+")) expand(); 64 | else throw new RuntimeException("Illegal command line argument"); 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /5-Strings/5-5-DataCompression/ababLZW.txt: -------------------------------------------------------------------------------- 1 | ABABABA -------------------------------------------------------------------------------- /5-Strings/5-5-DataCompression/abra.txt: -------------------------------------------------------------------------------- 1 | ABRACADABRA! -------------------------------------------------------------------------------- /5-Strings/5-5-DataCompression/abraLZW.txt: -------------------------------------------------------------------------------- 1 | ABRACADABRABRABRA -------------------------------------------------------------------------------- /5-Strings/5-5-DataCompression/genomeTiny.txt: -------------------------------------------------------------------------------- 1 | ATAGATGCATAGCGCATAGCTAGATGTGCTAGC -------------------------------------------------------------------------------- /5-Strings/5-5-DataCompression/q32x48.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aistrate/AlgorithmsSedgewick/06703c1371ffdf669d3996baa9e9684d13cdcc82/5-Strings/5-5-DataCompression/q32x48.bin -------------------------------------------------------------------------------- /5-Strings/5-5-DataCompression/q64x96.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aistrate/AlgorithmsSedgewick/06703c1371ffdf669d3996baa9e9684d13cdcc82/5-Strings/5-5-DataCompression/q64x96.bin -------------------------------------------------------------------------------- /5-Strings/5-5-DataCompression/tinytinyTale.txt: -------------------------------------------------------------------------------- 1 | it was the best of times it was the worst of times 2 | -------------------------------------------------------------------------------- /6-Context/6-3-SuffixArrays/KWIK.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac KWIK.java 3 | * Execution: java KWIK file.txt 4 | * Dependencies: StdIn.java In.java 5 | * Data files: http://algs4.cs.princeton.edu/63suffix/tale.txt 6 | * 7 | * % java KWIK tale.txt 15 8 | * majesty 9 | * most gracious majesty king george th 10 | * rnkeys and the majesty of the law fir 11 | * on against the majesty of the people 12 | * se them to his majestys chief secreta 13 | * h lists of his majestys forces and of 14 | * 15 | * the worst 16 | * w the best and the worst are known to y 17 | * f them give me the worst first there th 18 | * for in case of the worst is a friend in 19 | * e roomdoor and the worst is over then a 20 | * pect mr darnay the worst its the wisest 21 | * is his brother the worst of a bad race 22 | * ss in them for the worst of health for 23 | * you have seen the worst of her agitati 24 | * cumwented into the worst of luck buuust 25 | * n your brother the worst of the bad rac 26 | * full share in the worst of the day pla 27 | * mes to himself the worst of the strife 28 | * f times it was the worst of times it wa 29 | * ould hope that the worst was over well 30 | * urage business the worst will be over i 31 | * clesiastics of the worst world worldly 32 | * 33 | *************************************************************************/ 34 | 35 | public class KWIK { 36 | 37 | public static void main(String[] args) { 38 | In in = new In(args[0]); 39 | int context = Integer.parseInt(args[1]); 40 | 41 | // read in text 42 | String text = in.readAll().replaceAll("\\s+", " "); 43 | int N = text.length(); 44 | 45 | // build suffix array 46 | SuffixArray sa = new SuffixArray(text); 47 | 48 | // find all occurrences of queries and give context 49 | while (StdIn.hasNextLine()) { 50 | String query = StdIn.readLine(); 51 | for (int i = sa.rank(query); i < N && sa.select(i).startsWith(query); i++) { 52 | int from = Math.max(0, sa.index(i) - context); 53 | int to = Math.min(N-1, from + query.length() + 2*context); 54 | StdOut.println(text.substring(from, to)); 55 | } 56 | StdOut.println(); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /6-Context/6-3-SuffixArrays/LRS.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac LRS.java 3 | * Execution: java LRS < file.txt 4 | * Dependencies: StdIn.java SuffixArray.java 5 | * Data files: http://algs4.cs.princeton.edu/63suffix/tinyTale.txt 6 | * http://algs4.cs.princeton.edu/63suffix/mobydick.txt 7 | * 8 | * Reads a text string from stdin, replaces all consecutive blocks of 9 | * whitespace with a single space, and then computes the longest 10 | * repeated substring in that text using a suffix array. 11 | * 12 | * % java LRS < tinyTale.txt 13 | * 'st of times it was the ' 14 | * 15 | * % java LRS < mobydick.txt 16 | * ',- Such a funny, sporty, gamy, jesty, joky, hoky-poky lad, is the Ocean, oh! Th' 17 | * 18 | * % java LRS 19 | * aaaaaaaaa 20 | * 'aaaaaaaa' 21 | * 22 | * % java LRS 23 | * abcdefg 24 | * '' 25 | * 26 | *************************************************************************/ 27 | 28 | 29 | public class LRS { 30 | 31 | public static void main(String[] args) { 32 | String text = StdIn.readAll().replaceAll("\\s+", " "); 33 | SuffixArray sa = new SuffixArray(text); 34 | 35 | int N = sa.length(); 36 | 37 | String lrs = ""; 38 | for (int i = 1; i < N; i++) { 39 | int length = sa.lcp(i); 40 | if (length > lrs.length()) 41 | lrs = sa.select(i).substring(0, length); 42 | } 43 | 44 | StdOut.println("'" + lrs + "'"); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /6-Context/6-3-SuffixArrays/SuffixArray.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac SuffixArray.java 3 | * Execution: java SuffixArray < input.txt 4 | * 5 | * A data type that computes the suffix array of a string. 6 | * 7 | * % java SuffixArray < abra.txt 8 | * i ind lcp rnk select 9 | * --------------------------- 10 | * 0 11 - 0 ! 11 | * 1 10 0 1 A! 12 | * 2 7 1 2 ABRA! 13 | * 3 0 4 3 ABRACADABRA! 14 | * 4 3 1 4 ACADABRA! 15 | * 5 5 1 5 ADABRA! 16 | * 6 8 0 6 BRA! 17 | * 7 1 3 7 BRACADABRA! 18 | * 8 4 0 8 CADABRA! 19 | * 9 6 0 9 DABRA! 20 | * 10 9 0 10 RA! 21 | * 11 2 2 11 RACADABRA! 22 | * 23 | *************************************************************************/ 24 | 25 | import java.util.Arrays; 26 | 27 | public class SuffixArray { 28 | private final String[] suffixes; 29 | private final int N; 30 | 31 | public SuffixArray(String s) { 32 | N = s.length(); 33 | suffixes = new String[N]; 34 | for (int i = 0; i < N; i++) 35 | suffixes[i] = s.substring(i); 36 | Arrays.sort(suffixes); 37 | } 38 | 39 | // size of string 40 | public int length() { return N; } 41 | 42 | // index of ith sorted suffix 43 | public int index(int i) { return N - suffixes[i].length(); } 44 | 45 | // ith sorted suffix 46 | public String select(int i) { return suffixes[i]; } 47 | 48 | // number of suffixes strictly less than query 49 | public int rank(String query) { 50 | int lo = 0, hi = N - 1; 51 | while (lo <= hi) { 52 | int mid = lo + (hi - lo) / 2; 53 | int cmp = query.compareTo(suffixes[mid]); 54 | if (cmp < 0) hi = mid - 1; 55 | else if (cmp > 0) lo = mid + 1; 56 | else return mid; 57 | } 58 | return lo; 59 | } 60 | 61 | // length of longest common prefix of s and t 62 | private static int lcp(String s, String t) { 63 | int N = Math.min(s.length(), t.length()); 64 | for (int i = 0; i < N; i++) 65 | if (s.charAt(i) != t.charAt(i)) return i; 66 | return N; 67 | } 68 | 69 | // longest common prefix of suffixes(i) and suffixes(i-1) 70 | public int lcp(int i) { 71 | return lcp(suffixes[i], suffixes[i-1]); 72 | } 73 | 74 | // longest common prefix of suffixes(i) and suffixes(j) 75 | public int lcp(int i, int j) { 76 | return lcp(suffixes[i], suffixes[j]); 77 | } 78 | 79 | 80 | 81 | 82 | public static void main(String[] args) { 83 | String s = StdIn.readAll().trim(); 84 | SuffixArray suffix = new SuffixArray(s); 85 | 86 | StdOut.println(" i ind lcp rnk select"); 87 | StdOut.println("---------------------------"); 88 | StdOut.printf("%3d %3d %3s %3d %s\n", 89 | 0, suffix.index(0), "-", suffix.rank(suffix.select(0)), suffix.select(0)); 90 | for (int i = 1; i < s.length(); i++) { 91 | int index = suffix.index(i); 92 | String ith = suffix.select(i); 93 | int lcp = suffix.lcp(i, i-1); 94 | int rank = suffix.rank(ith); 95 | StdOut.printf("%3d %3d %3d %3d %s\n", i, index, lcp, rank, ith); 96 | } 97 | } 98 | 99 | } 100 | -------------------------------------------------------------------------------- /6-Context/6-3-SuffixArrays/abra.txt: -------------------------------------------------------------------------------- 1 | ABRACADABRA! -------------------------------------------------------------------------------- /6-Context/6-3-SuffixArrays/tinyTale.txt: -------------------------------------------------------------------------------- 1 | it was the best of times it was the worst of times 2 | it was the age of wisdom it was the age of foolishness 3 | it was the epoch of belief it was the epoch of incredulity 4 | it was the season of light it was the season of darkness 5 | it was the spring of hope it was the winter of despair 6 | -------------------------------------------------------------------------------- /6-Context/6-4-Maxflow/FlowEdge.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac FlowEdge.java 3 | * Execution: java FlowEdge 4 | * 5 | * Capacitated edge with a flow in a flow network. 6 | * 7 | *************************************************************************/ 8 | 9 | /** 10 | * The FlowEdge class represents a capacitated edge with a flow 11 | * in a digraph. 12 | *

13 | * For additional documentation, see Section 7.4 of 14 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 15 | */ 16 | 17 | 18 | public class FlowEdge { 19 | private final int v; // from 20 | private final int w; // to 21 | private final double capacity; // capacity 22 | private double flow; // flow 23 | 24 | public FlowEdge(int v, int w, double capacity) { 25 | if (capacity < 0) throw new RuntimeException("Negative edge capacity"); 26 | this.v = v; 27 | this.w = w; 28 | this.capacity = capacity; 29 | this.flow = 0; 30 | } 31 | 32 | public FlowEdge(int v, int w, double capacity, double flow) { 33 | if (capacity < 0) throw new RuntimeException("Negative edge capacity"); 34 | this.v = v; 35 | this.w = w; 36 | this.capacity = capacity; 37 | this.flow = flow; 38 | } 39 | 40 | // accessor methods 41 | public int from() { return v; } 42 | public int to() { return w; } 43 | public double capacity() { return capacity; } 44 | public double flow() { return flow; } 45 | 46 | 47 | public int other(int vertex) { 48 | if (vertex == v) return w; 49 | else if (vertex == w) return v; 50 | else throw new RuntimeException("Illegal endpoint"); 51 | } 52 | 53 | public double residualCapacityTo(int vertex) { 54 | if (vertex == v) return flow; 55 | else if (vertex == w) return capacity - flow; 56 | else throw new RuntimeException("Illegal endpoint"); 57 | } 58 | 59 | public void addResidualFlowTo(int vertex, double delta) { 60 | if (vertex == v) flow -= delta; 61 | else if (vertex == w) flow += delta; 62 | else throw new RuntimeException("Illegal endpoint"); 63 | } 64 | 65 | 66 | public String toString() { 67 | return v + "->" + w + " " + flow + "/" + capacity; 68 | } 69 | 70 | 71 | /** 72 | * Test client. 73 | */ 74 | public static void main(String[] args) { 75 | FlowEdge e = new FlowEdge(12, 23, 3.14); 76 | StdOut.println(e); 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /6-Context/6-4-Maxflow/FlowNetwork.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac FlowNetwork.java 3 | * Execution: java FlowNetwork V E 4 | * Dependencies: Bag.java FlowEdge.java 5 | * 6 | * A capacitated flow network, implemented using adjacency lists. 7 | * 8 | *************************************************************************/ 9 | 10 | public class FlowNetwork { 11 | private final int V; 12 | private int E; 13 | private Bag[] adj; 14 | 15 | // empty graph with V vertices 16 | public FlowNetwork(int V) { 17 | this.V = V; 18 | this.E = 0; 19 | adj = (Bag[]) new Bag[V]; 20 | for (int v = 0; v < V; v++) 21 | adj[v] = new Bag(); 22 | } 23 | 24 | // random graph with V vertices and E edges 25 | public FlowNetwork(int V, int E) { 26 | this(V); 27 | for (int i = 0; i < E; i++) { 28 | int v = StdRandom.uniform(V); 29 | int w = StdRandom.uniform(V); 30 | double capacity = StdRandom.uniform(100); 31 | addEdge(new FlowEdge(v, w, capacity)); 32 | } 33 | } 34 | 35 | // graph, read from input stream 36 | public FlowNetwork(In in) { 37 | this(in.readInt()); 38 | int E = in.readInt(); 39 | for (int i = 0; i < E; i++) { 40 | int v = in.readInt(); 41 | int w = in.readInt(); 42 | double capacity = in.readDouble(); 43 | addEdge(new FlowEdge(v, w, capacity)); 44 | } 45 | } 46 | 47 | 48 | // number of vertices and edges 49 | public int V() { return V; } 50 | public int E() { return E; } 51 | 52 | // add edge e in both v's and w's adjacency lists 53 | public void addEdge(FlowEdge e) { 54 | E++; 55 | int v = e.from(); 56 | int w = e.to(); 57 | adj[v].add(e); 58 | adj[w].add(e); 59 | } 60 | 61 | // return list of edges incident to v 62 | public Iterable adj(int v) { 63 | return adj[v]; 64 | } 65 | 66 | // return list of all edges - excludes self loops 67 | public Iterable edges() { 68 | Bag list = new Bag(); 69 | for (int v = 0; v < V; v++) 70 | for (FlowEdge e : adj(v)) { 71 | if (e.to() != v) 72 | list.add(e); 73 | } 74 | return list; 75 | } 76 | 77 | 78 | // string representation of Graph (excludes self loops) - takes quadratic time 79 | public String toString() { 80 | String NEWLINE = System.getProperty("line.separator"); 81 | StringBuilder s = new StringBuilder(); 82 | s.append(V + " " + E + NEWLINE); 83 | for (int v = 0; v < V; v++) { 84 | s.append(v + ": "); 85 | for (FlowEdge e : adj[v]) { 86 | if (e.to() != v) s.append(e + " "); 87 | } 88 | s.append(NEWLINE); 89 | } 90 | return s.toString(); 91 | } 92 | 93 | // test client 94 | public static void main(String[] args) { 95 | In in = new In(args[0]); 96 | FlowNetwork G = new FlowNetwork(in); 97 | StdOut.println(G); 98 | } 99 | 100 | } 101 | -------------------------------------------------------------------------------- /6-Context/6-4-Maxflow/tinyFN.txt: -------------------------------------------------------------------------------- 1 | 6 2 | 8 3 | 0 1 2.0 4 | 0 2 3.0 5 | 1 3 3.0 6 | 1 4 1.0 7 | 2 3 1.0 8 | 2 4 1.0 9 | 3 5 2.0 10 | 4 5 3.0 11 | -------------------------------------------------------------------------------- /6-Context/6-5-Reductions/BipartiteMatching.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac BipartiteMatching.java 3 | * Execution: java BipartiteMatching N E 4 | * Dependencies: FordFulkerson.java FlowNetwork.java FlowEdge.java 5 | * 6 | * Find a maximum matching in a bipartite graph. Solve by reducing 7 | * to maximum flow. 8 | * 9 | * The order of growth of the running time in the worst case is E V 10 | * because each augmentation increases the cardinality of the matching 11 | * by one. 12 | * 13 | * The Hopcroft-Karp algorithm improves this to E V^1/2 by finding 14 | * a maximal set of shortest augmenting paths in each phase. 15 | * 16 | *********************************************************************/ 17 | 18 | public class BipartiteMatching { 19 | 20 | public static void main(String[] args) { 21 | 22 | // read in bipartite network with 2N vertices and E edges 23 | // we assume the vertices on one side of the bipartition 24 | // are named 0 to N-1 and on the other side are N to 2N-1. 25 | int N = Integer.parseInt(args[0]); 26 | int E = Integer.parseInt(args[1]); 27 | int s = 2*N, t = 2*N + 1; 28 | FlowNetwork G = new FlowNetwork(2*N + 2); 29 | for (int i = 0; i < E; i++) { 30 | int v = StdRandom.uniform(N); 31 | int w = StdRandom.uniform(N) + N; 32 | G.addEdge(new FlowEdge(v, w, Double.POSITIVE_INFINITY)); 33 | StdOut.println(v + "-" + w); 34 | } 35 | for (int i = 0; i < N; i++) { 36 | G.addEdge(new FlowEdge(s, i, 1.0)); 37 | G.addEdge(new FlowEdge(i + N, t, 1.0)); 38 | } 39 | 40 | 41 | // compute maximum flow and minimum cut 42 | FordFulkerson maxflow = new FordFulkerson(G, s, t); 43 | StdOut.println(); 44 | StdOut.println("Size of maximum matching = " + (int) maxflow.value()); 45 | for (int v = 0; v < N; v++) { 46 | for (FlowEdge e : G.adj(v)) { 47 | if (e.from() == v && e.flow() > 0) 48 | StdOut.println(e.from() + "-" + e.to()); 49 | } 50 | } 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /Beyond/GaussianElimination.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac GaussianElimination.java 3 | * Execution: java GaussianElimination 4 | * 5 | * Gaussian elimination with partial pivoting. 6 | * 7 | * % java GaussianElimination 8 | * -1.0 9 | * 2.0 10 | * 2.0 11 | * 12 | *************************************************************************/ 13 | 14 | public class GaussianElimination { 15 | private static final double EPSILON = 1e-10; 16 | 17 | // Gaussian elimination with partial pivoting 18 | public static double[] lsolve(double[][] A, double[] b) { 19 | int N = b.length; 20 | 21 | for (int p = 0; p < N; p++) { 22 | 23 | // find pivot row and swap 24 | int max = p; 25 | for (int i = p + 1; i < N; i++) { 26 | if (Math.abs(A[i][p]) > Math.abs(A[max][p])) { 27 | max = i; 28 | } 29 | } 30 | double[] temp = A[p]; A[p] = A[max]; A[max] = temp; 31 | double t = b[p]; b[p] = b[max]; b[max] = t; 32 | 33 | // singular or nearly singular 34 | if (Math.abs(A[p][p]) <= EPSILON) { 35 | throw new RuntimeException("Matrix is singular or nearly singular"); 36 | } 37 | 38 | // pivot within A and b 39 | for (int i = p + 1; i < N; i++) { 40 | double alpha = A[i][p] / A[p][p]; 41 | b[i] -= alpha * b[p]; 42 | for (int j = p; j < N; j++) { 43 | A[i][j] -= alpha * A[p][j]; 44 | } 45 | } 46 | } 47 | 48 | // back substitution 49 | double[] x = new double[N]; 50 | for (int i = N - 1; i >= 0; i--) { 51 | double sum = 0.0; 52 | for (int j = i + 1; j < N; j++) { 53 | sum += A[i][j] * x[j]; 54 | } 55 | x[i] = (b[i] - sum) / A[i][i]; 56 | } 57 | return x; 58 | } 59 | 60 | 61 | // sample client 62 | public static void main(String[] args) { 63 | int N = 3; 64 | double[][] A = { 65 | { 0, 1, 1 }, 66 | { 2, 4, -2 }, 67 | { 0, 3, 15 } 68 | }; 69 | double[] b = { 4, 2, 36 }; 70 | double[] x = lsolve(A, b); 71 | 72 | 73 | // print results 74 | for (int i = 0; i < N; i++) { 75 | StdOut.println(x[i]); 76 | } 77 | 78 | } 79 | 80 | } 81 | -------------------------------------------------------------------------------- /Readme.txt: -------------------------------------------------------------------------------- 1 | The following data files are missing from this repository, due to their large size: 2 | 3 | File Size Used by 4 | ------------- -------- --------------------- 5 | leipzig1M.txt 129.6 MB 3-Searching 6 | UPC.csv 48.1 MB 3-Searching 7 | largeUF.txt 25.8 MB 1-Fundamentals 8 | largeT.txt 7.0 MB 1-Fundamentals 9 | largeW.txt 7.0 MB 1-Fundamentals 10 | movies.txt 3.4 MB 3-Searching, 4-Graphs 11 | mobydick.txt 1.2 MB 6-Context 12 | DJIA.csv 1.1 MB 3-Searching 13 | 14 | An archive that contains these data files (as well as all the other ones used in the book) can be found at: 15 | http://algs4.cs.princeton.edu/code/algs4-data.zip 16 | -------------------------------------------------------------------------------- /StdLib/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /StdLib/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | StdLib 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /StdLib/BinaryDump.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac BinaryDump.java 3 | * Execution: java BinaryDump N < file 4 | * Dependencies: BinaryStdIn.java 5 | * Data file: http://introcs.cs.princeton.edu/stdlib/abra.txt 6 | * 7 | * Reads in a binary file and writes out the bits, N per line. 8 | * 9 | * % more abra.txt 10 | * ABRACADABRA! 11 | * 12 | * % java BinaryDump 16 < abra.txt 13 | * 0100000101000010 14 | * 0101001001000001 15 | * 0100001101000001 16 | * 0100010001000001 17 | * 0100001001010010 18 | * 0100000100100001 19 | * 96 bits 20 | * 21 | *************************************************************************/ 22 | 23 | public class BinaryDump { 24 | 25 | public static void main(String[] args) { 26 | int BITS_PER_LINE = 16; 27 | if (args.length == 1) { 28 | BITS_PER_LINE = Integer.parseInt(args[0]); 29 | } 30 | 31 | int count; 32 | for (count = 0; !BinaryStdIn.isEmpty(); count++) { 33 | if (BITS_PER_LINE == 0) { BinaryStdIn.readBoolean(); continue; } 34 | else if (count != 0 && count % BITS_PER_LINE == 0) StdOut.println(); 35 | if (BinaryStdIn.readBoolean()) StdOut.print(1); 36 | else StdOut.print(0); 37 | } 38 | if (BITS_PER_LINE != 0) StdOut.println(); 39 | StdOut.println(count + " bits"); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /StdLib/BinaryStdInTester.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac BinaryStdInTester.java 3 | * Execution: java BinaryStdInTester 4 | * 5 | * % java BinaryStdInTester 6 | * true 7 | * K 8 | * 17 9 | * 12345678901 10 | * 3.141592653589793 11 | * 1.125 12 | * 13 | *************************************************************************/ 14 | 15 | public class BinaryStdInTester { 16 | 17 | 18 | public static void main(String[] args) { 19 | boolean x1 = BinaryStdIn.readBoolean(); 20 | char x2 = BinaryStdIn.readChar(); 21 | int x3 = BinaryStdIn.readInt(); 22 | long x4 = BinaryStdIn.readLong(); 23 | double x5 = BinaryStdIn.readDouble(); 24 | float x6 = BinaryStdIn.readFloat(); 25 | System.out.println(x1); 26 | System.out.println(x2); 27 | System.out.println(x3); 28 | System.out.println(x4); 29 | System.out.println(x5); 30 | System.out.println(x6); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /StdLib/BinaryStdOutTester.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac BinaryStdOutTester.java 3 | * Execution: java BinaryStdOutTester 4 | * 5 | *************************************************************************/ 6 | 7 | public class BinaryStdOutTester { 8 | 9 | 10 | public static void main(String[] args) { 11 | boolean x1 = true; 12 | char x2 = 'K'; 13 | int x3 = 17; 14 | long x4 = 12345678901L; 15 | double x5 = Math.PI; 16 | float x6 = 1.125F; 17 | BinaryStdOut.write(x1); 18 | BinaryStdOut.write(x2); 19 | BinaryStdOut.write(x3); 20 | BinaryStdOut.write(x4); 21 | BinaryStdOut.write(x5); 22 | BinaryStdOut.write(x6); 23 | BinaryStdOut.flush(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /StdLib/Copy.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac Copy.java 3 | * Execution: java Copy < file 4 | * Dependencies: BinaryStdIn.java BinaryStdOut.java 5 | * 6 | * Reads in a binary file from standard input and writes it to standard output. 7 | * 8 | * % java Copy < mandrill.jpg > copy.jpg 9 | * 10 | * % diff mandrill.jpg copy.jpg 11 | * 12 | *************************************************************************/ 13 | 14 | public class Copy { 15 | 16 | public static void main(String[] args) { 17 | while (!BinaryStdIn.isEmpty()) { 18 | char c = BinaryStdIn.readChar(); 19 | BinaryStdOut.write(c); 20 | } 21 | BinaryStdOut.flush(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /StdLib/DrawListener.java: -------------------------------------------------------------------------------- 1 | public interface DrawListener { 2 | public void mousePressed (double x, double y); 3 | public void mouseDragged (double x, double y); 4 | public void mouseReleased(double x, double y); 5 | public void keyTyped(char c); 6 | } 7 | -------------------------------------------------------------------------------- /StdLib/HexDump.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac HexDump.java 3 | * Execution: java HexDump < file 4 | * Dependencies: BinaryStdIn.java 5 | * Data file: http://introcs.cs.princeton.edu/stdlib/abra.txt 6 | * 7 | * Reads in a binary file and writes out the bytes in hex, 16 per line. 8 | * 9 | * % more abra.txt 10 | * ABRACADABRA! 11 | * 12 | * % java HexDump 16 < abra.txt 13 | * 41 42 52 41 43 41 44 41 42 52 41 21 14 | * 96 bits 15 | * 16 | * % hexdump < abra.txt 17 | * 18 | * % od -t x1 < abra.txt 19 | * 0000000 41 42 52 41 43 41 44 41 42 52 41 21 20 | * 0000014 21 | * 22 | *************************************************************************/ 23 | 24 | public class HexDump { 25 | 26 | public static void main(String[] args) { 27 | int BYTES_PER_LINE = 16; 28 | if (args.length == 1) { 29 | BYTES_PER_LINE = Integer.parseInt(args[0]); 30 | } 31 | 32 | int i; 33 | for (i = 0; !BinaryStdIn.isEmpty(); i++) { 34 | if (BYTES_PER_LINE == 0) { BinaryStdIn.readChar(); continue; } 35 | if (i == 0) StdOut.printf(""); 36 | else if (i % BYTES_PER_LINE == 0) StdOut.printf("\n", i); 37 | else StdOut.print(" "); 38 | char c = BinaryStdIn.readChar(); 39 | StdOut.printf("%02x", c & 0xff); 40 | } 41 | if (BYTES_PER_LINE != 0) StdOut.println(); 42 | StdOut.println((i*8) + " bits"); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /StdLib/InTest.txt: -------------------------------------------------------------------------------- 1 | This is a test file. 2 | Here is line 2. 3 | -------------------------------------------------------------------------------- /StdLib/PictureDump.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac PictureDump.java 3 | * Execution: java PictureDump width height < file 4 | * Dependencies: BinaryStdIn.java Picture.java 5 | * Data file: http://introcs.cs.princeton.edu/stdlib/abra.txt 6 | * 7 | * Reads in a binary file and writes out the bits as w-by-h picture, 8 | * with the 1 bits in black and the 0 bits in white. 9 | * 10 | * % more abra.txt 11 | * ABRACADABRA! 12 | * 13 | * % java PictureDump 16 6 < abra.txt 14 | * 15 | *************************************************************************/ 16 | import java.awt.Color; 17 | 18 | public class PictureDump { 19 | 20 | public static void main(String[] args) { 21 | int width = Integer.parseInt(args[0]); 22 | int height = Integer.parseInt(args[1]); 23 | Picture pic = new Picture(width, height); 24 | int count = 0; 25 | for (int i = 0; i < height; i++) { 26 | for (int j = 0; j < width; j++) { 27 | pic.set(j, i, Color.RED); 28 | if (!BinaryStdIn.isEmpty()) { 29 | count++; 30 | boolean bit = BinaryStdIn.readBoolean(); 31 | if (bit) pic.set(j, i, Color.BLACK); 32 | else pic.set(j, i, Color.WHITE); 33 | } 34 | } 35 | } 36 | pic.show(); 37 | StdOut.println(count + " bits"); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /StdLib/Stopwatch.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac Stopwatch.java 3 | * 4 | * 5 | *************************************************************************/ 6 | 7 | /** 8 | * Stopwatch. This class is a data type for measuring 9 | * the running time (wall clock) of a program. 10 | *

11 | * For additional documentation, see 12 | * Section 3.2 of 13 | * Introduction to Programming in Java: An Interdisciplinary Approach 14 | * by Robert Sedgewick and Kevin Wayne. 15 | */ 16 | 17 | 18 | 19 | public class Stopwatch { 20 | 21 | private final long start; 22 | 23 | /** 24 | * Create a stopwatch object. 25 | */ 26 | public Stopwatch() { 27 | start = System.currentTimeMillis(); 28 | } 29 | 30 | 31 | /** 32 | * Return elapsed time (in seconds) since this object was created. 33 | */ 34 | public double elapsedTime() { 35 | long now = System.currentTimeMillis(); 36 | return (now - start) / 1000.0; 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /StdLib/mandrill.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aistrate/AlgorithmsSedgewick/06703c1371ffdf669d3996baa9e9684d13cdcc82/StdLib/mandrill.jpg -------------------------------------------------------------------------------- /algs4.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aistrate/AlgorithmsSedgewick/06703c1371ffdf669d3996baa9e9684d13cdcc82/algs4.jar -------------------------------------------------------------------------------- /stdlib.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aistrate/AlgorithmsSedgewick/06703c1371ffdf669d3996baa9e9684d13cdcc82/stdlib.jar --------------------------------------------------------------------------------