├── .gitignore ├── LICENSE.txt ├── README.md ├── RELEASE.md ├── pom.xml └── src └── main └── java └── edu └── princeton └── cs └── algorithms ├── AcyclicLP.java ├── AcyclicSP.java ├── AdjMatrixEdgeWeightedDigraph.java ├── Alphabet.java ├── Arbitrage.java ├── AssignmentProblem.java ├── Average.java ├── BST.java ├── BTree.java ├── Bag.java ├── BellmanFordSP.java ├── BinaryDump.java ├── BinarySearch.java ├── BinarySearchST.java ├── Bipartite.java ├── BipartiteMatching.java ├── BlackFilter.java ├── BoruvkaMST.java ├── BoyerMoore.java ├── BreadthFirstDirectedPaths.java ├── BreadthFirstPaths.java ├── CC.java ├── CPM.java ├── Cat.java ├── ClosestPair.java ├── CollisionSystem.java ├── Complex.java ├── Count.java ├── Counter.java ├── Cycle.java ├── Date.java ├── DeDup.java ├── DegreesOfSeparation.java ├── DepthFirstDirectedPaths.java ├── DepthFirstOrder.java ├── DepthFirstPaths.java ├── DepthFirstSearch.java ├── Digraph.java ├── DigraphGenerator.java ├── DijkstraAllPairsSP.java ├── DijkstraSP.java ├── DirectedCycle.java ├── DirectedDFS.java ├── DirectedEdge.java ├── DoublingRatio.java ├── DoublingTest.java ├── Edge.java ├── EdgeWeightedDigraph.java ├── EdgeWeightedDirectedCycle.java ├── EdgeWeightedGraph.java ├── FFT.java ├── FarthestPair.java ├── FileIndex.java ├── FlowEdge.java ├── FlowNetwork.java ├── FloydWarshall.java ├── FordFulkerson.java ├── FrequencyCounter.java ├── GREP.java ├── GabowSCC.java ├── GaussianElimination.java ├── Genome.java ├── GrahamScan.java ├── Graph.java ├── GraphGenerator.java ├── Heap.java ├── HexDump.java ├── Huffman.java ├── IndexMaxPQ.java ├── IndexMinPQ.java ├── Insertion.java ├── InsertionX.java ├── Interval1D.java ├── Interval2D.java ├── KMP.java ├── KWIK.java ├── Knuth.java ├── KosarajuSharirSCC.java ├── KruskalMST.java ├── LRS.java ├── LSD.java ├── LZW.java ├── LazyPrimMST.java ├── LinearProbingHashST.java ├── LinearRegression.java ├── LinkedBag.java ├── LinkedQueue.java ├── LinkedStack.java ├── LongestCommonSubstring.java ├── LookupCSV.java ├── LookupIndex.java ├── MSD.java ├── MaxPQ.java ├── Merge.java ├── MergeBU.java ├── MergeX.java ├── MinPQ.java ├── Multiway.java ├── NFA.java ├── Particle.java ├── PictureDump.java ├── Point2D.java ├── PolynomialRegression.java ├── PrimMST.java ├── Queue.java ├── Quick.java ├── Quick3string.java ├── Quick3way.java ├── QuickFindUF.java ├── QuickUnionUF.java ├── QuickX.java ├── RabinKarp.java ├── RandomSeq.java ├── RedBlackBST.java ├── ResizingArrayBag.java ├── ResizingArrayQueue.java ├── ResizingArrayStack.java ├── RunLength.java ├── SET.java ├── ST.java ├── Selection.java ├── SeparateChainingHashST.java ├── SequentialSearchST.java ├── Shell.java ├── Simplex.java ├── SparseVector.java ├── Stack.java ├── StaticSETofInts.java ├── Stopwatch.java ├── StopwatchCPU.java ├── SuffixArray.java ├── SuffixArrayX.java ├── SymbolDigraph.java ├── SymbolGraph.java ├── TST.java ├── TarjanSCC.java ├── ThreeSum.java ├── ThreeSumFast.java ├── TopM.java ├── Topological.java ├── Transaction.java ├── TransitiveClosure.java ├── TrieSET.java ├── TrieST.java ├── UF.java ├── Vector.java ├── WeightedQuickUnionUF.java ├── WhiteFilter.java └── Whitelist.java /.gitignore: -------------------------------------------------------------------------------- 1 | *.DS_Store 2 | */target/* 3 | */bin/* 4 | *~ 5 | /target 6 | .classpath 7 | .project 8 | .settings 9 | .idea/ 10 | *.iml 11 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # princeton-java-algorithms 2 | 3 | Contains the [mavenized](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.googlecode.princeton-java-algorithms%22) examples for the textbook Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 4 | The examples cover the most important algorithms and data structures in use today. 5 | 6 | http://algs4.cs.princeton.edu/ 7 | 8 | ## Maven 9 | 10 | You can use the following dependency in your `pom.xml`: 11 | 12 | ```xml 13 | 14 | com.github.fracpete 15 | princeton-java-algorithms 16 | 4.0.2 17 | 18 | ``` 19 | 20 | -------------------------------------------------------------------------------- /RELEASE.md: -------------------------------------------------------------------------------- 1 | # RELEASE 2 | 3 | Switch to Java 8. 4 | 5 | Use the following command to make a new release: 6 | 7 | ``` 8 | mvn --batch-mode release:clean release:prepare release:perform 9 | ``` 10 | 11 | Push all changes 12 | 13 | Go to the following URL and publish the artifact: 14 | 15 | ``` 16 | https://central.sonatype.com/publishing/deployments 17 | ``` 18 | 19 | Update the Maven artifact version in [README.md](README.md#maven). 20 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/Arbitrage.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdIn; 4 | import edu.princeton.cs.introcs.StdOut; 5 | 6 | /************************************************************************* 7 | * Compilation: javac Arbitrage.java 8 | * Execution: java Arbitrage < input.txt 9 | * Dependencies: EdgeWeightedDigraph.java DirectedEdge.java 10 | * BellmanFordSP.java 11 | * Data file: http://algs4.cs.princeton.edu/44sp/rates.txt 12 | * 13 | * Arbitrage detection. 14 | * 15 | * % more rates.txt 16 | * 5 17 | * USD 1 0.741 0.657 1.061 1.005 18 | * EUR 1.349 1 0.888 1.433 1.366 19 | * GBP 1.521 1.126 1 1.614 1.538 20 | * CHF 0.942 0.698 0.619 1 0.953 21 | * CAD 0.995 0.732 0.650 1.049 1 22 | * 23 | * % java Arbitrage < rates.txt 24 | * 1000.00000 USD = 741.00000 EUR 25 | * 741.00000 EUR = 1012.20600 CAD 26 | * 1012.20600 CAD = 1007.14497 USD 27 | * 28 | *************************************************************************/ 29 | 30 | /** 31 | * The Arbitrage class provides a client that finds an arbitrage 32 | * opportunity in a currency exchange table by constructing a 33 | * complete-digraph representation of the exchange table and then finding 34 | * a negative cycle in the digraph. 35 | *

36 | * This implementation uses the Bellman-Ford algorithm to find a 37 | * negative cycle in the complete digraph. 38 | * The running time is proportional to V3 in the 39 | * worst case, where V is the number of currencies. 40 | *

41 | * For additional documentation, 42 | * see Section 4.4 of 43 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 44 | * 45 | * @author Robert Sedgewick 46 | * @author Kevin Wayne 47 | */ 48 | public class Arbitrage { 49 | 50 | // this class cannot be instantiated 51 | private Arbitrage() { } 52 | 53 | /** 54 | * Reads the currency exchange table from standard input and 55 | * prints an arbitrage opportunity to standard output (if one exists). 56 | */ 57 | public static void main(String[] args) { 58 | 59 | // V currencies 60 | int V = StdIn.readInt(); 61 | String[] name = new String[V]; 62 | 63 | // create complete network 64 | EdgeWeightedDigraph G = new EdgeWeightedDigraph(V); 65 | for (int v = 0; v < V; v++) { 66 | name[v] = StdIn.readString(); 67 | for (int w = 0; w < V; w++) { 68 | double rate = StdIn.readDouble(); 69 | DirectedEdge e = new DirectedEdge(v, w, -Math.log(rate)); 70 | G.addEdge(e); 71 | } 72 | } 73 | 74 | // find negative cycle 75 | BellmanFordSP spt = new BellmanFordSP(G, 0); 76 | if (spt.hasNegativeCycle()) { 77 | double stake = 1000.0; 78 | for (DirectedEdge e : spt.negativeCycle()) { 79 | StdOut.printf("%10.5f %s ", stake, name[e.from()]); 80 | stake *= Math.exp(-e.weight()); 81 | StdOut.printf("= %10.5f %s\n", stake, name[e.to()]); 82 | } 83 | } 84 | else { 85 | StdOut.println("No arbitrage opportunity"); 86 | } 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/Average.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdIn; 4 | import edu.princeton.cs.introcs.StdOut; 5 | 6 | /************************************************************************* 7 | * Compilation: javac Average.java 8 | * Execution: java Average < data.txt 9 | * Dependencies: StdIn.java StdOut.java 10 | * 11 | * Reads in a sequence of real numbers, and computes their average. 12 | * 13 | * % java Average 14 | * 10.0 5.0 6.0 15 | * 3.0 7.0 32.0 16 | * 17 | * Average is 10.5 18 | 19 | * Note signifies the end of file on Unix. 20 | * On windows use . 21 | * 22 | *************************************************************************/ 23 | 24 | /** 25 | * The Average class provides a client for reading in a sequence 26 | * of real numbers and printing out their average. 27 | *

28 | * For additional documentation, see Section 1.1 of 29 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 30 | * 31 | * @author Robert Sedgewick 32 | * @author Kevin Wayne 33 | */ 34 | public class Average { 35 | 36 | // this class should not be instantiated 37 | private Average() { } 38 | 39 | /** 40 | * Reads in a sequence of real numbers from standard input and prints 41 | * out their average to standard output. 42 | */ 43 | public static void main(String[] args) { 44 | int count = 0; // number input values 45 | double sum = 0.0; // sum of input values 46 | 47 | // read data and compute statistics 48 | while (!StdIn.isEmpty()) { 49 | double value = StdIn.readDouble(); 50 | sum += value; 51 | count++; 52 | } 53 | 54 | // compute the average 55 | double average = sum / count; 56 | 57 | // print results 58 | StdOut.println("Average is " + average); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/Bag.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | /************************************************************************* 4 | * Compilation: javac Bag.java 5 | * Execution: java Bag < input.txt 6 | * 7 | * A generic bag or multiset, implemented using a singly-linked list. 8 | * 9 | * % more tobe.txt 10 | * to be or not to - be - - that - - - is 11 | * 12 | * % java Bag < tobe.txt 13 | * size of bag = 14 14 | * is 15 | * - 16 | * - 17 | * - 18 | * that 19 | * - 20 | * - 21 | * be 22 | * - 23 | * to 24 | * not 25 | * or 26 | * be 27 | * to 28 | * 29 | *************************************************************************/ 30 | 31 | import java.util.Iterator; 32 | import java.util.NoSuchElementException; 33 | 34 | import edu.princeton.cs.introcs.StdIn; 35 | import edu.princeton.cs.introcs.StdOut; 36 | 37 | /** 38 | * The Bag class represents a bag (or multiset) of 39 | * generic items. It supports insertion and iterating over the 40 | * items in arbitrary order. 41 | *

42 | * This implementation uses a singly-linked list with a static nested class Node. 43 | * See {@link LinkedBag} for the version from the 44 | * textbook that uses a non-static nested class. 45 | * The add, isEmpty, and size operations 46 | * take constant time. Iteration takes time proportional to the number of items. 47 | *

48 | * For additional documentation, see Section 1.3 of 49 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 50 | * 51 | * @author Robert Sedgewick 52 | * @author Kevin Wayne 53 | */ 54 | public class Bag implements Iterable { 55 | private int N; // number of elements in bag 56 | private Node first; // beginning of bag 57 | 58 | // helper linked list class 59 | private static class Node { 60 | private Item item; 61 | private Node next; 62 | } 63 | 64 | /** 65 | * Initializes an empty bag. 66 | */ 67 | public Bag() { 68 | first = null; 69 | N = 0; 70 | } 71 | 72 | /** 73 | * Is this bag empty? 74 | * @return true if this bag is empty; false otherwise 75 | */ 76 | public boolean isEmpty() { 77 | return first == null; 78 | } 79 | 80 | /** 81 | * Returns the number of items in this bag. 82 | * @return the number of items in this bag 83 | */ 84 | public int size() { 85 | return N; 86 | } 87 | 88 | /** 89 | * Adds the item to this bag. 90 | * @param item the item to add to this bag 91 | */ 92 | public void add(Item item) { 93 | Node oldfirst = first; 94 | first = new Node(); 95 | first.item = item; 96 | first.next = oldfirst; 97 | N++; 98 | } 99 | 100 | 101 | /** 102 | * Returns an iterator that iterates over the items in the bag in arbitrary order. 103 | * @return an iterator that iterates over the items in the bag in arbitrary order 104 | */ 105 | public Iterator iterator() { 106 | return new ListIterator(first); 107 | } 108 | 109 | // an iterator, doesn't implement remove() since it's optional 110 | private class ListIterator implements Iterator { 111 | private Node current; 112 | 113 | public ListIterator(Node first) { 114 | current = first; 115 | } 116 | 117 | public boolean hasNext() { return current != null; } 118 | public void remove() { throw new UnsupportedOperationException(); } 119 | 120 | public Item next() { 121 | if (!hasNext()) throw new NoSuchElementException(); 122 | Item item = current.item; 123 | current = current.next; 124 | return item; 125 | } 126 | } 127 | 128 | /** 129 | * Unit tests the Bag data type. 130 | */ 131 | public static void main(String[] args) { 132 | Bag bag = new Bag(); 133 | while (!StdIn.isEmpty()) { 134 | String item = StdIn.readString(); 135 | bag.add(item); 136 | } 137 | 138 | StdOut.println("size of bag = " + bag.size()); 139 | for (String s : bag) { 140 | StdOut.println(s); 141 | } 142 | } 143 | 144 | 145 | } 146 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/BinaryDump.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.BinaryStdIn; 4 | import edu.princeton.cs.introcs.StdOut; 5 | 6 | /************************************************************************* 7 | * Compilation: javac BinaryDump.java 8 | * Execution: java BinaryDump N < file 9 | * Dependencies: BinaryStdIn.java 10 | * Data file: http://introcs.cs.princeton.edu/stdlib/abra.txt 11 | * 12 | * Reads in a binary file and writes out the bits, N per line. 13 | * 14 | * % more abra.txt 15 | * ABRACADABRA! 16 | * 17 | * % java BinaryDump 16 < abra.txt 18 | * 0100000101000010 19 | * 0101001001000001 20 | * 0100001101000001 21 | * 0100010001000001 22 | * 0100001001010010 23 | * 0100000100100001 24 | * 96 bits 25 | * 26 | *************************************************************************/ 27 | 28 | public class BinaryDump { 29 | 30 | public static void main(String[] args) { 31 | int BITS_PER_LINE = 16; 32 | if (args.length == 1) { 33 | BITS_PER_LINE = Integer.parseInt(args[0]); 34 | } 35 | 36 | int count; 37 | for (count = 0; !BinaryStdIn.isEmpty(); count++) { 38 | if (BITS_PER_LINE == 0) { BinaryStdIn.readBoolean(); continue; } 39 | else if (count != 0 && count % BITS_PER_LINE == 0) StdOut.println(); 40 | if (BinaryStdIn.readBoolean()) StdOut.print(1); 41 | else StdOut.print(0); 42 | } 43 | if (BITS_PER_LINE != 0) StdOut.println(); 44 | StdOut.println(count + " bits"); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/BinarySearch.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | /************************************************************************* 4 | * Compilation: javac BinarySearch.java 5 | * Execution: java BinarySearch whitelist.txt < input.txt 6 | * Data files: http://algs4.cs.princeton.edu/11model/tinyW.txt 7 | * http://algs4.cs.princeton.edu/11model/tinyT.txt 8 | * http://algs4.cs.princeton.edu/11model/largeW.txt 9 | * http://algs4.cs.princeton.edu/11model/largeT.txt 10 | * 11 | * % java BinarySearch tinyW.txt < tinyT.txt 12 | * 50 13 | * 99 14 | * 13 15 | * 16 | * % java BinarySearch largeW.txt < largeT.txt | more 17 | * 499569 18 | * 984875 19 | * 295754 20 | * 207807 21 | * 140925 22 | * 161828 23 | * [3,675,966 total values] 24 | * 25 | *************************************************************************/ 26 | 27 | import java.util.Arrays; 28 | 29 | import edu.princeton.cs.introcs.In; 30 | import edu.princeton.cs.introcs.StdIn; 31 | import edu.princeton.cs.introcs.StdOut; 32 | 33 | /** 34 | * The BinarySearch class provides a static method for binary 35 | * searching for an integer in a sorted array of integers. 36 | *

37 | * The rank operations takes logarithmic time in the worst case. 38 | *

39 | * For additional documentation, see Section 1.1 of 40 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 41 | * 42 | * @author Robert Sedgewick 43 | * @author Kevin Wayne 44 | */ 45 | public class BinarySearch { 46 | 47 | /** 48 | * This class should not be instantiated. 49 | */ 50 | private BinarySearch() { } 51 | 52 | /** 53 | * Searches for the integer key in the sorted array a[]. 54 | * @param key the search key 55 | * @param a the array of integers, must be sorted in ascending order 56 | * @return index of key in array a[] if present; -1 if not present 57 | */ 58 | public static int rank(int key, int[] a) { 59 | int lo = 0; 60 | int hi = a.length - 1; 61 | while (lo <= hi) { 62 | // Key is in a[lo..hi] or not present. 63 | int mid = lo + (hi - lo) / 2; 64 | if (key < a[mid]) hi = mid - 1; 65 | else if (key > a[mid]) lo = mid + 1; 66 | else return mid; 67 | } 68 | return -1; 69 | } 70 | 71 | /** 72 | * Reads in a sequence of integers from the whitelist file, specified as 73 | * a command-line argument. Reads in integers from standard input and 74 | * prints to standard output those integers that do *not* appear in the file. 75 | */ 76 | public static void main(String[] args) { 77 | 78 | // read the integers from a file 79 | In in = new In(args[0]); 80 | int[] whitelist = in.readAllInts(); 81 | 82 | // sort the array 83 | Arrays.sort(whitelist); 84 | 85 | // read integer key from standard input; print if not in whitelist 86 | while (!StdIn.isEmpty()) { 87 | int key = StdIn.readInt(); 88 | if (rank(key, whitelist) == -1) 89 | StdOut.println(key); 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/BipartiteMatching.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdOut; 4 | import edu.princeton.cs.introcs.StdRandom; 5 | 6 | /************************************************************************* 7 | * Compilation: javac BipartiteMatching.java 8 | * Execution: java BipartiteMatching N E 9 | * Dependencies: FordFulkerson.java FlowNetwork.java FlowEdge.java 10 | * 11 | * Find a maximum matching in a bipartite graph. Solve by reducing 12 | * to maximum flow. 13 | * 14 | * The order of growth of the running time in the worst case is E V 15 | * because each augmentation increases the cardinality of the matching 16 | * by one. 17 | * 18 | * The Hopcroft-Karp algorithm improves this to E V^1/2 by finding 19 | * a maximal set of shortest augmenting paths in each phase. 20 | * 21 | *********************************************************************/ 22 | 23 | public class BipartiteMatching { 24 | 25 | public static void main(String[] args) { 26 | 27 | // read in bipartite network with 2N vertices and E edges 28 | // we assume the vertices on one side of the bipartition 29 | // are named 0 to N-1 and on the other side are N to 2N-1. 30 | int N = Integer.parseInt(args[0]); 31 | int E = Integer.parseInt(args[1]); 32 | int s = 2*N, t = 2*N + 1; 33 | FlowNetwork G = new FlowNetwork(2*N + 2); 34 | for (int i = 0; i < E; i++) { 35 | int v = StdRandom.uniform(N); 36 | int w = StdRandom.uniform(N) + N; 37 | G.addEdge(new FlowEdge(v, w, Double.POSITIVE_INFINITY)); 38 | StdOut.println(v + "-" + w); 39 | } 40 | for (int i = 0; i < N; i++) { 41 | G.addEdge(new FlowEdge(s, i, 1.0)); 42 | G.addEdge(new FlowEdge(i + N, t, 1.0)); 43 | } 44 | 45 | 46 | // compute maximum flow and minimum cut 47 | FordFulkerson maxflow = new FordFulkerson(G, s, t); 48 | StdOut.println(); 49 | StdOut.println("Size of maximum matching = " + (int) maxflow.value()); 50 | for (int v = 0; v < N; v++) { 51 | for (FlowEdge e : G.adj(v)) { 52 | if (e.from() == v && e.flow() > 0) 53 | StdOut.println(e.from() + "-" + e.to()); 54 | } 55 | } 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/BlackFilter.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.In; 4 | import edu.princeton.cs.introcs.StdIn; 5 | import edu.princeton.cs.introcs.StdOut; 6 | 7 | /************************************************************************* 8 | * Compilation: javac BlackFilter.java 9 | * Execution: java BlackFilter blacklist.txt < input.txt 10 | * Dependencies: SET In.java StdIn.java StdOut.java 11 | * Data files: http://algs4.cs.princeton.edu/35applications/tinyTale.txt 12 | * http://algs4.cs.princeton.edu/35applications/list.txt 13 | * 14 | * Read in a blacklist of words from a file. Then read in a list of 15 | * words from standard input and print out all those words that 16 | * are not in the first file. 17 | * 18 | * % more tinyTale.txt 19 | * it was the best of times it was the worst of times 20 | * it was the age of wisdom it was the age of foolishness 21 | * it was the epoch of belief it was the epoch of incredulity 22 | * it was the season of light it was the season of darkness 23 | * it was the spring of hope it was the winter of despair 24 | * 25 | * % more list.txt 26 | * was it the of 27 | * 28 | * % java BlackFilter list.txt < tinyTale.txt 29 | * best times worst times 30 | * age wisdom age foolishness 31 | * epoch belief epoch incredulity 32 | * season light season darkness 33 | * spring hope winter despair 34 | * 35 | *************************************************************************/ 36 | 37 | public class BlackFilter { 38 | public static void main(String[] args) { 39 | SET set = new SET(); 40 | 41 | // read in strings and add to set 42 | In in = new In(args[0]); 43 | while (!in.isEmpty()) { 44 | String word = in.readString(); 45 | set.add(word); 46 | } 47 | 48 | // read in string from standard input, printing out all exceptions 49 | while (!StdIn.isEmpty()) { 50 | String word = StdIn.readString(); 51 | if (!set.contains(word)) 52 | StdOut.println(word); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/CPM.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdIn; 4 | import edu.princeton.cs.introcs.StdOut; 5 | 6 | /************************************************************************* 7 | * Compilation: javac CPM.java 8 | * Execution: java CPM < input.txt 9 | * Dependencies: EdgeWeightedDigraph.java AcyclicDigraphLP.java StdOut.java 10 | * Data files: http://algs4.cs.princeton.edu/44sp/jobsPC.txt 11 | * 12 | * Critical path method. 13 | * 14 | * % java CPM < jobsPC.txt 15 | * job start finish 16 | * -------------------- 17 | * 0 0.0 41.0 18 | * 1 41.0 92.0 19 | * 2 123.0 173.0 20 | * 3 91.0 127.0 21 | * 4 70.0 108.0 22 | * 5 0.0 45.0 23 | * 6 70.0 91.0 24 | * 7 41.0 73.0 25 | * 8 91.0 123.0 26 | * 9 41.0 70.0 27 | * Finish time: 173.0 28 | * 29 | *************************************************************************/ 30 | 31 | /** 32 | * The CPM class provides a client that solves the 33 | * parallel precedence-constrained job scheduling problem 34 | * via the critical path method. It reduces the problem 35 | * to the longest-paths problem in edge-weighted DAGs. 36 | * It builds an edge-weighted digraph (which must be a DAG) 37 | * from the job-scheduling problem specification, 38 | * finds the longest-paths tree, and computes the longest-paths 39 | * lengths (which are precisely the start times for each job). 40 | *

41 | * This implementation uses {@link AcyclicLP} to find a longest 42 | * path in a DAG. 43 | * The running time is proportional to V + E, 44 | * where V is the number of jobs and E is the 45 | * number of precedence constraints. 46 | *

47 | * For additional documentation, 48 | * see Section 4.4 of 49 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 50 | * 51 | * @author Robert Sedgewick 52 | * @author Kevin Wayne 53 | */ 54 | public class CPM { 55 | 56 | // this class cannot be instantiated 57 | private CPM() { } 58 | 59 | /** 60 | * Reads the precedence constraints from standard input 61 | * and prints a feasible schedule to standard output. 62 | */ 63 | public static void main(String[] args) { 64 | 65 | // number of jobs 66 | int N = StdIn.readInt(); 67 | 68 | // source and sink 69 | int source = 2*N; 70 | int sink = 2*N + 1; 71 | 72 | // build network 73 | EdgeWeightedDigraph G = new EdgeWeightedDigraph(2*N + 2); 74 | for (int i = 0; i < N; i++) { 75 | double duration = StdIn.readDouble(); 76 | G.addEdge(new DirectedEdge(source, i, 0.0)); 77 | G.addEdge(new DirectedEdge(i+N, sink, 0.0)); 78 | G.addEdge(new DirectedEdge(i, i+N, duration)); 79 | 80 | // precedence constraints 81 | int M = StdIn.readInt(); 82 | for (int j = 0; j < M; j++) { 83 | int precedent = StdIn.readInt(); 84 | G.addEdge(new DirectedEdge(N+i, precedent, 0.0)); 85 | } 86 | } 87 | 88 | // compute longest path 89 | AcyclicLP lp = new AcyclicLP(G, source); 90 | 91 | // print results 92 | StdOut.println(" job start finish"); 93 | StdOut.println("--------------------"); 94 | for (int i = 0; i < N; i++) { 95 | StdOut.printf("%4d %7.1f %7.1f\n", i, lp.distTo(i), lp.distTo(i+N)); 96 | } 97 | StdOut.printf("Finish time: %7.1f\n", lp.distTo(sink)); 98 | } 99 | 100 | } 101 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/Cat.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.In; 4 | import edu.princeton.cs.introcs.Out; 5 | 6 | /************************************************************************* 7 | * Compilation: javac Cat.java 8 | * Execution: java Cat input0.txt input1.txt ... output.txt 9 | * Dependencies: In.java Out.java 10 | * 11 | * Reads in text files specified as the first command-line 12 | * arguments, concatenates them, and writes the result to 13 | * filename specified as the last command-line arguments. 14 | * 15 | * % more in1.txt 16 | * This is 17 | * 18 | * % more in2.txt 19 | * a tiny 20 | * test. 21 | * 22 | * % java Cat in1.txt in2.txt out.txt 23 | * 24 | * % more out.txt 25 | * This is 26 | * a tiny 27 | * test. 28 | * 29 | *************************************************************************/ 30 | 31 | /** 32 | * The Cat class provides a client for concatenating the results 33 | * of several text files. 34 | *

35 | * For additional documentation, see Section 1.1 of 36 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 37 | * 38 | * @author Robert Sedgewick 39 | * @author Kevin Wayne 40 | */ 41 | public class Cat { 42 | 43 | // this class should not be instantiated 44 | private Cat() { } 45 | 46 | /** 47 | * Reads in a sequence of text files specified as the first command-line 48 | * arguments, concatenates them, and writes the results to the file 49 | * specified as the last command-line argument. 50 | */ 51 | public static void main(String[] args) { 52 | Out out = new Out(args[args.length - 1]); 53 | for (int i = 0; i < args.length - 1; i++) { 54 | In in = new In(args[i]); 55 | String s = in.readAll(); 56 | out.println(s); 57 | in.close(); 58 | } 59 | out.close(); 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/Count.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdIn; 4 | import edu.princeton.cs.introcs.StdOut; 5 | 6 | /************************************************************************* 7 | * Compilation: javac Count.java 8 | * Execution: java Count alpha < input.txt 9 | * 10 | * Create an alphabet specified on the command line, read in a 11 | * sequence of characters over that alphabet (ignoring characters 12 | * not in the alphabet), computes the frequency of occurrence of 13 | * each character, and print out the results. 14 | * 15 | * % java Count ABCDR < abra.txt 16 | * A 5 17 | * B 2 18 | * C 1 19 | * D 1 20 | * R 2 21 | * 22 | * % java Count 0123456789 < pi.txt 23 | * 0 99959 24 | * 1 99757 25 | * 2 100026 26 | * 3 100230 27 | * 4 100230 28 | * 5 100359 29 | * 6 99548 30 | * 7 99800 31 | * 8 99985 32 | * 9 100106 33 | * 34 | *************************************************************************/ 35 | 36 | 37 | 38 | public class Count { 39 | public static void main(String[] args) { 40 | Alphabet alpha = new Alphabet(args[0]); 41 | int R = alpha.R(); 42 | int[] count = new int[R]; 43 | String a = StdIn.readAll(); 44 | int N = a.length(); 45 | for (int i = 0; i < N; i++) 46 | if (alpha.contains(a.charAt(i))) 47 | count[alpha.toIndex(a.charAt(i))]++; 48 | for (int c = 0; c < R; c++) 49 | StdOut.println(alpha.toChar(c) + " " + count[c]); 50 | } 51 | } 52 | 53 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/Counter.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdOut; 4 | import edu.princeton.cs.introcs.StdRandom; 5 | 6 | /************************************************************************* 7 | * Compilation: javac Counter.java 8 | * Execution: java Counter N T 9 | * Dependencies: StdRandom.java StdOut.java 10 | * 11 | * A mutable data type for an integer counter. 12 | * 13 | * The test clients create N counters and performs T increment 14 | * operations on random counters. 15 | * 16 | * % java Counter 6 600000 17 | * 0: 99870 18 | * 1: 99948 19 | * 2: 99738 20 | * 3: 100283 21 | * 4: 100185 22 | * 5: 99976 23 | * 24 | *************************************************************************/ 25 | 26 | /** 27 | * The Counter class is a mutable data type to encapsulate a counter. 28 | *

29 | * For additional documentation, see Section 1.2 of 30 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 31 | * 32 | * @author Robert Sedgewick 33 | * @author Kevin Wayne 34 | */ 35 | public class Counter implements Comparable { 36 | 37 | private final String name; // counter name 38 | private int count; // current value 39 | 40 | /** 41 | * Initializes a new counter starting at 0, with the given id. 42 | * @param id the name of the counter 43 | */ 44 | public Counter(String id) { 45 | name = id; 46 | } 47 | 48 | /** 49 | * Increments the counter by 1. 50 | */ 51 | public void increment() { 52 | count++; 53 | } 54 | 55 | /** 56 | * Returns the current count. 57 | */ 58 | public int tally() { 59 | return count; 60 | } 61 | 62 | /** 63 | * Returns a string representation of this counter 64 | */ 65 | @Override 66 | public String toString() { 67 | return count + " " + name; 68 | } 69 | 70 | /** 71 | * Compares this counter to that counter. 72 | */ 73 | public int compareTo(Counter that) { 74 | if (this.count < that.count) return -1; 75 | else if (this.count > that.count) return +1; 76 | else return 0; 77 | } 78 | 79 | 80 | /** 81 | * Reads two command-line integers N and T; creates N counters; 82 | * increments T counters at random; and prints results. 83 | */ 84 | public static void main(String[] args) { 85 | int N = Integer.parseInt(args[0]); 86 | int T = Integer.parseInt(args[1]); 87 | 88 | // create N counters 89 | Counter[] hits = new Counter[N]; 90 | for (int i = 0; i < N; i++) { 91 | hits[i] = new Counter("counter" + i); 92 | } 93 | 94 | // increment T counters at random 95 | for (int t = 0; t < T; t++) { 96 | hits[StdRandom.uniform(N)].increment(); 97 | } 98 | 99 | // print results 100 | for (int i = 0; i < N; i++) { 101 | StdOut.println(hits[i]); 102 | } 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/DeDup.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdIn; 4 | import edu.princeton.cs.introcs.StdOut; 5 | 6 | /************************************************************************* 7 | * Compilation: javac DeDup.java 8 | * Execution: java DeDup < input.txt 9 | * Dependencies: SET StdIn.java StdOut.java 10 | * Data files: http://algs4.cs.princeton.edu/35applications/tinyTale.txt 11 | * 12 | * Read in a list of words from standard input and print out 13 | * each word, removing any duplicates. 14 | * 15 | * % more tinyTale.txt 16 | * it was the best of times it was the worst of times 17 | * it was the age of wisdom it was the age of foolishness 18 | * it was the epoch of belief it was the epoch of incredulity 19 | * it was the season of light it was the season of darkness 20 | * it was the spring of hope it was the winter of despair 21 | * 22 | * % java DeDup < tinyTale.txt 23 | * it 24 | * was 25 | * the 26 | * best 27 | * of 28 | * times 29 | * worst 30 | * age 31 | * wisdom 32 | * ... 33 | * winter 34 | * despair 35 | * 36 | *************************************************************************/ 37 | 38 | public class DeDup { 39 | public static void main(String[] args) { 40 | SET set = new SET(); 41 | 42 | // read in strings and add to set 43 | while (!StdIn.isEmpty()) { 44 | String key = StdIn.readString(); 45 | if (!set.contains(key)) { 46 | set.add(key); 47 | StdOut.println(key); 48 | } 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/DepthFirstDirectedPaths.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.In; 4 | import edu.princeton.cs.introcs.StdOut; 5 | 6 | /************************************************************************* 7 | * Compilation: javac DepthFirstDirectedPaths.java 8 | * Execution: java DepthFirstDirectedPaths G s 9 | * Dependencies: Digraph.java Stack.java 10 | * 11 | * Determine reachability in a digraph from a given vertex using 12 | * depth first search. 13 | * Runs in O(E + V) time. 14 | * 15 | * % tinyDG.txt 3 16 | * 3 to 0: 3-5-4-2-0 17 | * 3 to 1: 3-5-4-2-0-1 18 | * 3 to 2: 3-5-4-2 19 | * 3 to 3: 3 20 | * 3 to 4: 3-5-4 21 | * 3 to 5: 3-5 22 | * 3 to 6: not connected 23 | * 3 to 7: not connected 24 | * 3 to 8: not connected 25 | * 3 to 9: not connected 26 | * 3 to 10: not connected 27 | * 3 to 11: not connected 28 | * 3 to 12: not connected 29 | * 30 | *************************************************************************/ 31 | 32 | /** 33 | * The DepthFirstDirectedPaths class represents a data type for finding 34 | * directed paths from a source vertex s to every 35 | * other vertex in the digraph. 36 | *

37 | * This implementation uses depth-first search. 38 | * The constructor takes time proportional to V + E, 39 | * where V is the number of vertices and E is the number of edges. 40 | * It uses extra space (not including the graph) proportional to V. 41 | *

42 | * For additional documentation, see Section 4.1 of 43 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 44 | * 45 | * @author Robert Sedgewick 46 | * @author Kevin Wayne 47 | */ 48 | public class DepthFirstDirectedPaths { 49 | private boolean[] marked; // marked[v] = true if v is reachable from s 50 | private int[] edgeTo; // edgeTo[v] = last edge on path from s to v 51 | private final int s; // source vertex 52 | 53 | /** 54 | * Computes a directed path from s to every other vertex in digraph G. 55 | * @param G the digraph 56 | * @param s the source vertex 57 | */ 58 | public DepthFirstDirectedPaths(Digraph G, int s) { 59 | marked = new boolean[G.V()]; 60 | edgeTo = new int[G.V()]; 61 | this.s = s; 62 | dfs(G, s); 63 | } 64 | 65 | private void dfs(Digraph G, int v) { 66 | marked[v] = true; 67 | for (int w : G.adj(v)) { 68 | if (!marked[w]) { 69 | edgeTo[w] = v; 70 | dfs(G, w); 71 | } 72 | } 73 | } 74 | 75 | /** 76 | * Is there a directed path from the source vertex s to vertex v? 77 | * @param v the vertex 78 | * @return true if there is a directed path from the source 79 | * vertex s to vertex v, false otherwise 80 | */ 81 | public boolean hasPathTo(int v) { 82 | return marked[v]; 83 | } 84 | 85 | 86 | /** 87 | * Returns a directed path from the source vertex s to vertex v, or 88 | * null if no such path. 89 | * @param v the vertex 90 | * @return the sequence of vertices on a directed path from the source vertex 91 | * s to vertex v, as an Iterable 92 | */ 93 | public Iterable pathTo(int v) { 94 | if (!hasPathTo(v)) return null; 95 | Stack path = new Stack(); 96 | for (int x = v; x != s; x = edgeTo[x]) 97 | path.push(x); 98 | path.push(s); 99 | return path; 100 | } 101 | 102 | /** 103 | * Unit tests the DepthFirstDirectedPaths data type. 104 | */ 105 | public static void main(String[] args) { 106 | In in = new In(args[0]); 107 | Digraph G = new Digraph(in); 108 | // StdOut.println(G); 109 | 110 | int s = Integer.parseInt(args[1]); 111 | DepthFirstDirectedPaths dfs = new DepthFirstDirectedPaths(G, s); 112 | 113 | for (int v = 0; v < G.V(); v++) { 114 | if (dfs.hasPathTo(v)) { 115 | StdOut.printf("%d to %d: ", s, v); 116 | for (int x : dfs.pathTo(v)) { 117 | if (x == s) StdOut.print(x); 118 | else StdOut.print("-" + x); 119 | } 120 | StdOut.println(); 121 | } 122 | 123 | else { 124 | StdOut.printf("%d to %d: not connected\n", s, v); 125 | } 126 | 127 | } 128 | } 129 | 130 | } 131 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/DepthFirstPaths.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.In; 4 | import edu.princeton.cs.introcs.StdOut; 5 | 6 | /************************************************************************* 7 | * Compilation: javac DepthFirstPaths.java 8 | * Execution: java DepthFirstPaths G s 9 | * Dependencies: Graph.java Stack.java StdOut.java 10 | * Data files: http://algs4.cs.princeton.edu/41undirected/tinyCG.txt 11 | * 12 | * Run depth first search on an undirected graph. 13 | * Runs in O(E + V) time. 14 | * 15 | * % java Graph tinyCG.txt 16 | * 6 8 17 | * 0: 2 1 5 18 | * 1: 0 2 19 | * 2: 0 1 3 4 20 | * 3: 5 4 2 21 | * 4: 3 2 22 | * 5: 3 0 23 | * 24 | * % java DepthFirstPaths tinyCG.txt 0 25 | * 0 to 0: 0 26 | * 0 to 1: 0-2-1 27 | * 0 to 2: 0-2 28 | * 0 to 3: 0-2-3 29 | * 0 to 4: 0-2-3-4 30 | * 0 to 5: 0-2-3-5 31 | * 32 | *************************************************************************/ 33 | 34 | /** 35 | * The DepthFirstPaths class represents a data type for finding 36 | * paths from a source vertex s to every other vertex 37 | * in an undirected graph. 38 | *

39 | * This implementation uses depth-first search. 40 | * The constructor takes time proportional to V + E, 41 | * where V is the number of vertices and E is the number of edges. 42 | * It uses extra space (not including the graph) proportional to V. 43 | *

44 | * For additional documentation, see Section 4.1 of 45 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 46 | * 47 | * @author Robert Sedgewick 48 | * @author Kevin Wayne 49 | */ 50 | public class DepthFirstPaths { 51 | private boolean[] marked; // marked[v] = is there an s-v path? 52 | private int[] edgeTo; // edgeTo[v] = last edge on s-v path 53 | private final int s; // source vertex 54 | 55 | /** 56 | * Computes a path between s and every other vertex in graph G. 57 | * @param G the graph 58 | * @param s the source vertex 59 | */ 60 | public DepthFirstPaths(Graph G, int s) { 61 | this.s = s; 62 | edgeTo = new int[G.V()]; 63 | marked = new boolean[G.V()]; 64 | dfs(G, s); 65 | } 66 | 67 | // depth first search from v 68 | private void dfs(Graph G, int v) { 69 | marked[v] = true; 70 | for (int w : G.adj(v)) { 71 | if (!marked[w]) { 72 | edgeTo[w] = v; 73 | dfs(G, w); 74 | } 75 | } 76 | } 77 | 78 | /** 79 | * Is there a path between the source vertex s and vertex v? 80 | * @param v the vertex 81 | * @return true if there is a path, false otherwise 82 | */ 83 | public boolean hasPathTo(int v) { 84 | return marked[v]; 85 | } 86 | 87 | /** 88 | * Returns a path between the source vertex s and vertex v, or 89 | * null if no such path. 90 | * @param v the vertex 91 | * @return the sequence of vertices on a path between the source vertex 92 | * s and vertex v, as an Iterable 93 | */ 94 | public Iterable pathTo(int v) { 95 | if (!hasPathTo(v)) return null; 96 | Stack path = new Stack(); 97 | for (int x = v; x != s; x = edgeTo[x]) 98 | path.push(x); 99 | path.push(s); 100 | return path; 101 | } 102 | 103 | /** 104 | * Unit tests the DepthFirstPaths data type. 105 | */ 106 | public static void main(String[] args) { 107 | In in = new In(args[0]); 108 | Graph G = new Graph(in); 109 | int s = Integer.parseInt(args[1]); 110 | DepthFirstPaths dfs = new DepthFirstPaths(G, s); 111 | 112 | for (int v = 0; v < G.V(); v++) { 113 | if (dfs.hasPathTo(v)) { 114 | StdOut.printf("%d to %d: ", s, v); 115 | for (int x : dfs.pathTo(v)) { 116 | if (x == s) StdOut.print(x); 117 | else StdOut.print("-" + x); 118 | } 119 | StdOut.println(); 120 | } 121 | 122 | else { 123 | StdOut.printf("%d to %d: not connected\n", s, v); 124 | } 125 | 126 | } 127 | } 128 | 129 | } 130 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/DepthFirstSearch.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.In; 4 | import edu.princeton.cs.introcs.StdOut; 5 | 6 | /************************************************************************* 7 | * Compilation: javac DepthFirstSearch.java 8 | * Execution: java DepthFirstSearch filename.txt s 9 | * Dependencies: Graph.java StdOut.java 10 | * Data files: http://algs4.cs.princeton.edu/41undirected/tinyG.txt 11 | * 12 | * Run depth first search on an undirected graph. 13 | * Runs in O(E + V) time. 14 | * 15 | * % java DepthFirstSearch tinyG.txt 0 16 | * 0 1 2 3 4 5 6 17 | * NOT connected 18 | * 19 | * % java DepthFirstSearch tinyG.txt 9 20 | * 9 10 11 12 21 | * NOT connected 22 | * 23 | *************************************************************************/ 24 | 25 | /** 26 | * The DepthFirstSearch class represents a data type for 27 | * determining the vertices connected to a given source vertex s 28 | * in an undirected graph. For versions that find the paths, see 29 | * {@link DepthFirstPaths} and {@link BreadthFirstPaths}. 30 | *

31 | * This implementation uses depth-first search. 32 | * The constructor takes time proportional to V + E 33 | * (in the worst case), 34 | * where V is the number of vertices and E is the number of edges. 35 | * It uses extra space (not including the graph) proportional to V. 36 | *

37 | * For additional documentation, see Section 4.1 of 38 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 39 | * 40 | * @author Robert Sedgewick 41 | * @author Kevin Wayne 42 | */ 43 | public class DepthFirstSearch { 44 | private boolean[] marked; // marked[v] = is there an s-v path? 45 | private int count; // number of vertices connected to s 46 | 47 | /** 48 | * Computes the vertices in graph G that are 49 | * connected to the source vertex s. 50 | * @param G the graph 51 | * @param s the source vertex 52 | */ 53 | public DepthFirstSearch(Graph G, int s) { 54 | marked = new boolean[G.V()]; 55 | dfs(G, s); 56 | } 57 | 58 | // depth first search from v 59 | private void dfs(Graph G, int v) { 60 | count++; 61 | marked[v] = true; 62 | for (int w : G.adj(v)) { 63 | if (!marked[w]) { 64 | dfs(G, w); 65 | } 66 | } 67 | } 68 | 69 | /** 70 | * Is there a path between the source vertex s and vertex v? 71 | * @param v the vertex 72 | * @return true if there is a path, false otherwise 73 | */ 74 | public boolean marked(int v) { 75 | return marked[v]; 76 | } 77 | 78 | /** 79 | * Returns the number of vertices connected to the source vertex s. 80 | * @return the number of vertices connected to the source vertex s 81 | */ 82 | public int count() { 83 | return count; 84 | } 85 | 86 | /** 87 | * Unit tests the DepthFirstSearch data type. 88 | */ 89 | public static void main(String[] args) { 90 | In in = new In(args[0]); 91 | Graph G = new Graph(in); 92 | int s = Integer.parseInt(args[1]); 93 | DepthFirstSearch search = new DepthFirstSearch(G, s); 94 | for (int v = 0; v < G.V(); v++) { 95 | if (search.marked(v)) 96 | StdOut.print(v + " "); 97 | } 98 | 99 | StdOut.println(); 100 | if (search.count() != G.V()) StdOut.println("NOT connected"); 101 | else StdOut.println("connected"); 102 | } 103 | 104 | } 105 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/DijkstraAllPairsSP.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | /************************************************************************* 4 | * Compilation: javac DijkstraAllPairsSP.java 5 | * Dependencies: EdgeWeightedDigraph.java Dijkstra.java 6 | * 7 | * Dijkstra's algorithm run from each vertex. 8 | * Takes time proportional to E V log V and space proportional to EV. 9 | * 10 | *************************************************************************/ 11 | 12 | /** 13 | * The DijkstraAllPairsSP class represents a data type for solving the 14 | * all-pairs shortest paths problem in edge-weighted digraphs 15 | * where the edge weights are nonnegative. 16 | *

17 | * This implementation runs Dijkstra's algorithm from each vertex. 18 | * The constructor takes time proportional to V (E log V) 19 | * and uses space proprtional to V2, 20 | * where V is the number of vertices and E is the number of edges. 21 | * Afterwards, the dist() and hasPath() methods take 22 | * constant time and the path() method takes time proportional to the 23 | * number of edges in the shortest path returned. 24 | *

25 | * For additional documentation, see Section 4.4 of 26 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 27 | * 28 | * @author Robert Sedgewick 29 | * @author Kevin Wayne 30 | */ 31 | public class DijkstraAllPairsSP { 32 | private DijkstraSP[] all; 33 | 34 | /** 35 | * Computes a shortest paths tree from each vertex to to every other vertex in 36 | * the edge-weighted digraph G. 37 | * @param G the edge-weighted digraph 38 | * @throws IllegalArgumentException if an edge weight is negative 39 | * @throws IllegalArgumentException unless 0 ≤ sV - 1 40 | */ 41 | public DijkstraAllPairsSP(EdgeWeightedDigraph G) { 42 | all = new DijkstraSP[G.V()]; 43 | for (int v = 0; v < G.V(); v++) 44 | all[v] = new DijkstraSP(G, v); 45 | } 46 | 47 | /** 48 | * Returns a shortest path from vertex s to vertex t. 49 | * @param s the source vertex 50 | * @param t the destination vertex 51 | * @return a shortest path from vertex s to vertex t 52 | * as an iterable of edges, and null if no such path 53 | */ 54 | public Iterable path(int s, int t) { 55 | return all[s].pathTo(t); 56 | } 57 | 58 | /** 59 | * Is there a path from the vertex s to vertex t? 60 | * @param s the source vertex 61 | * @param t the destination vertex 62 | * @return true if there is a path from vertex s 63 | * to vertex t, and false otherwise 64 | */ 65 | public boolean hasPath(int s, int t) { 66 | return dist(s, t) < Double.POSITIVE_INFINITY; 67 | } 68 | 69 | /** 70 | * Returns the length of a shortest path from vertex s to vertex t. 71 | * @param s the source vertex 72 | * @param t the destination vertex 73 | * @return the length of a shortest path from vertex s to vertex t; 74 | * Double.POSITIVE_INFINITY if no such path 75 | */ 76 | public double dist(int s, int t) { 77 | return all[s].distTo(t); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/DirectedDFS.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.In; 4 | import edu.princeton.cs.introcs.StdOut; 5 | 6 | /************************************************************************* 7 | * Compilation: javac DirectedDFS.java 8 | * Execution: java DirectedDFS V E 9 | * Dependencies: Digraph.java Bag.java In.java StdOut.java 10 | * Data files: http://www.cs.princeton.edu/algs4/42directed/tinyDG.txt 11 | * 12 | * Determine single-source or multiple-source reachability in a digraph 13 | * using depth first search. 14 | * Runs in O(E + V) time. 15 | * 16 | * % java DirectedDFS tinyDG.txt 1 17 | * 1 18 | * 19 | * % java DirectedDFS tinyDG.txt 2 20 | * 0 1 2 3 4 5 21 | * 22 | * % java DirectedDFS tinyDG.txt 1 2 6 23 | * 0 1 2 3 4 5 6 8 9 10 11 12 24 | * 25 | *************************************************************************/ 26 | /** 27 | * The DirectedDFS class represents a data type for 28 | * determining the vertices reachable from a given source vertex s 29 | * (or set of source vertices) in a digraph. For versions that find the paths, 30 | * see {@link DepthFirstDirectedPaths} and {@link BreadthFirstDirectedPaths}. 31 | *

32 | * This implementation uses depth-first search. 33 | * The constructor takes time proportional to V + E 34 | * (in the worst case), 35 | * where V is the number of vertices and E is the number of edges. 36 | *

37 | * For additional documentation, see Section 4.1 of 38 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 39 | * 40 | * @author Robert Sedgewick 41 | * @author Kevin Wayne 42 | */ 43 | public class DirectedDFS { 44 | private boolean[] marked; // marked[v] = true if v is reachable 45 | // from source (or sources) 46 | private int count; // number of vertices reachable from s 47 | 48 | /** 49 | * Computes the vertices in digraph G that are 50 | * reachable from the source vertex s. 51 | * @param G the digraph 52 | * @param s the source vertex 53 | */ 54 | public DirectedDFS(Digraph G, int s) { 55 | marked = new boolean[G.V()]; 56 | dfs(G, s); 57 | } 58 | 59 | /** 60 | * Computes the vertices in digraph G that are 61 | * connected to any of the source vertices sources. 62 | * @param G the graph 63 | * @param sources the source vertices 64 | */ 65 | public DirectedDFS(Digraph G, Iterable sources) { 66 | marked = new boolean[G.V()]; 67 | for (int v : sources) { 68 | if (!marked[v]) dfs(G, v); 69 | } 70 | } 71 | 72 | private void dfs(Digraph G, int v) { 73 | count++; 74 | marked[v] = true; 75 | for (int w : G.adj(v)) { 76 | if (!marked[w]) dfs(G, w); 77 | } 78 | } 79 | 80 | /** 81 | * Is there a directed path from the source vertex (or any 82 | * of the source vertices) and vertex v? 83 | * @param v the vertex 84 | * @return true if there is a directed path, false otherwise 85 | */ 86 | public boolean marked(int v) { 87 | return marked[v]; 88 | } 89 | 90 | /** 91 | * Returns the number of vertices reachable from the source vertex 92 | * (or source vertices). 93 | * @return the number of vertices reachable from the source vertex 94 | * (or source vertices) 95 | */ 96 | public int count() { 97 | return count; 98 | } 99 | 100 | /** 101 | * Unit tests the DirectedDFS data type. 102 | */ 103 | public static void main(String[] args) { 104 | 105 | // read in digraph from command-line argument 106 | In in = new In(args[0]); 107 | Digraph G = new Digraph(in); 108 | 109 | // read in sources from command-line arguments 110 | Bag sources = new Bag(); 111 | for (int i = 1; i < args.length; i++) { 112 | int s = Integer.parseInt(args[i]); 113 | sources.add(s); 114 | } 115 | 116 | // multiple-source reachability 117 | DirectedDFS dfs = new DirectedDFS(G, sources); 118 | 119 | // print out vertices reachable from sources 120 | for (int v = 0; v < G.V(); v++) { 121 | if (dfs.marked(v)) StdOut.print(v + " "); 122 | } 123 | StdOut.println(); 124 | } 125 | 126 | } 127 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/DirectedEdge.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdOut; 4 | 5 | /************************************************************************* 6 | * Compilation: javac DirectedEdge.java 7 | * Execution: java DirectedEdge 8 | * 9 | * Immutable weighted directed edge. 10 | * 11 | *************************************************************************/ 12 | /** 13 | * The DirectedEdge class represents a weighted edge in an 14 | * {@link EdgeWeightedDigraph}. Each edge consists of two integers 15 | * (naming the two vertices) and a real-value weight. The data type 16 | * provides methods for accessing the two endpoints of the directed edge and 17 | * the weight. 18 | *

19 | * For additional documentation, see Section 4.4 of 20 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 21 | * 22 | * @author Robert Sedgewick 23 | * @author Kevin Wayne 24 | */ 25 | 26 | public class DirectedEdge { 27 | private final int v; 28 | private final int w; 29 | private final double weight; 30 | 31 | /** 32 | * Initializes a directed edge from vertex v to vertex w with 33 | * the given weight. 34 | * @param v the tail vertex 35 | * @param w the head vertex 36 | * @param weight the weight of the directed edge 37 | * @throws java.lang.IndexOutOfBoundsException if either v or w 38 | * is a negative integer 39 | * @throws IllegalArgumentException if weight is NaN 40 | */ 41 | public DirectedEdge(int v, int w, double weight) { 42 | if (v < 0) throw new IndexOutOfBoundsException("Vertex names must be nonnegative integers"); 43 | if (w < 0) throw new IndexOutOfBoundsException("Vertex names must be nonnegative integers"); 44 | if (Double.isNaN(weight)) throw new IllegalArgumentException("Weight is NaN"); 45 | this.v = v; 46 | this.w = w; 47 | this.weight = weight; 48 | } 49 | 50 | /** 51 | * Returns the tail vertex of the directed edge. 52 | * @return the tail vertex of the directed edge 53 | */ 54 | public int from() { 55 | return v; 56 | } 57 | 58 | /** 59 | * Returns the head vertex of the directed edge. 60 | * @return the head vertex of the directed edge 61 | */ 62 | public int to() { 63 | return w; 64 | } 65 | 66 | /** 67 | * Returns the weight of the directed edge. 68 | * @return the weight of the directed edge 69 | */ 70 | public double weight() { 71 | return weight; 72 | } 73 | 74 | /** 75 | * Returns a string representation of the directed edge. 76 | * @return a string representation of the directed edge 77 | */ 78 | @Override 79 | public String toString() { 80 | return v + "->" + w + " " + String.format("%5.2f", weight); 81 | } 82 | 83 | /** 84 | * Unit tests the DirectedEdge data type. 85 | */ 86 | public static void main(String[] args) { 87 | DirectedEdge e = new DirectedEdge(12, 23, 3.14); 88 | StdOut.println(e); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/DoublingRatio.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdOut; 4 | import edu.princeton.cs.introcs.StdRandom; 5 | 6 | /************************************************************************* 7 | * Compilation: javac DoublingRatio.java 8 | * Execution: java DoublingRatio 9 | * Dependencies: ThreeSum.java Stopwatch.java StdRandom.java StdOut.java 10 | * 11 | * 12 | * % java DoublingRatio 13 | * 250 0.0 2.7 14 | * 500 0.0 4.8 15 | * 1000 0.1 6.9 16 | * 2000 0.6 7.7 17 | * 4000 4.5 8.0 18 | * 8000 35.7 8.0 19 | * ... 20 | * 21 | *************************************************************************/ 22 | 23 | /** 24 | * The DoublingRatio class provides a client for measuring 25 | * the running time of a method using a doubling ratio test. 26 | *

27 | * For additional documentation, see Section 1.4 28 | * of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 29 | * 30 | * @author Robert Sedgewick 31 | * @author Kevin Wayne 32 | */ 33 | public class DoublingRatio { 34 | 35 | // This class should not be instantiated. 36 | private DoublingRatio() { } 37 | 38 | /** 39 | * Returns the amount of time to call ThreeSum.count() with N 40 | * random 6-digit integers. 41 | * @param N the number of integers 42 | * @return amount of time (in seconds) to call ThreeSum.count() 43 | * with N random 6-digit integers 44 | */ 45 | public static double timeTrial(int N) { 46 | int MAX = 1000000; 47 | int[] a = new int[N]; 48 | for (int i = 0; i < N; i++) { 49 | a[i] = StdRandom.uniform(-MAX, MAX); 50 | } 51 | Stopwatch timer = new Stopwatch(); 52 | int cnt = ThreeSum.count(a); 53 | return timer.elapsedTime(); 54 | } 55 | 56 | /** 57 | * Prints table of running times to call ThreeSum.count() 58 | * for arrays of size 250, 500, 1000, 2000, and so forth, along 59 | * with ratios of running times between successive array sizes. 60 | */ 61 | public static void main(String[] args) { 62 | double prev = timeTrial(125); 63 | for (int N = 250; true; N += N) { 64 | double time = timeTrial(N); 65 | StdOut.printf("%6d %7.1f %5.1f\n", N, time, time/prev); 66 | prev = time; 67 | } 68 | } 69 | } 70 | 71 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/DoublingTest.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdOut; 4 | import edu.princeton.cs.introcs.StdRandom; 5 | 6 | /************************************************************************* 7 | * Compilation: javac DoublingTest.java 8 | * Execution: java DoublingTest 9 | * Dependencies: ThreeSum.java Stopwatch.java StdRandom.java StdOut.java 10 | * 11 | * % java DoublingTest 12 | * 250 0.0 13 | * 500 0.0 14 | * 1000 0.1 15 | * 2000 0.6 16 | * 4000 4.5 17 | * 8000 35.7 18 | * ... 19 | * 20 | *************************************************************************/ 21 | 22 | /** 23 | * The DoublingTest class provides a client for measuring 24 | * the running time of a method using a doubling test. 25 | *

26 | * For additional documentation, see Section 1.4 27 | * of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 28 | * 29 | * @author Robert Sedgewick 30 | * @author Kevin Wayne 31 | */ 32 | public class DoublingTest { 33 | 34 | // This class should not be instantiated. 35 | private DoublingTest() { } 36 | 37 | /** 38 | * Returns the amount of time to call ThreeSum.count() with N 39 | * random 6-digit integers. 40 | * @param N the number of integers 41 | * @return amount of time (in seconds) to call ThreeSum.count() 42 | * with N random 6-digit integers 43 | */ 44 | public static double timeTrial(int N) { 45 | int MAX = 1000000; 46 | int[] a = new int[N]; 47 | for (int i = 0; i < N; i++) { 48 | a[i] = StdRandom.uniform(-MAX, MAX); 49 | } 50 | Stopwatch timer = new Stopwatch(); 51 | int cnt = ThreeSum.count(a); 52 | return timer.elapsedTime(); 53 | } 54 | 55 | /** 56 | * Prints table of running times to call ThreeSum.count() 57 | * for arrays of size 250, 500, 1000, 2000, and so forth. 58 | */ 59 | public static void main(String[] args) { 60 | for (int N = 250; true; N += N) { 61 | double time = timeTrial(N); 62 | StdOut.printf("%7d %5.1f\n", N, time); 63 | } 64 | } 65 | } 66 | 67 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/Edge.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdOut; 4 | 5 | /************************************************************************* 6 | * Compilation: javac Edge.java 7 | * Execution: java Edge 8 | * 9 | * Immutable weighted edge. 10 | * 11 | *************************************************************************/ 12 | 13 | /** 14 | * The Edge class represents a weighted edge in an 15 | * {@link EdgeWeightedGraph}. Each edge consists of two integers 16 | * (naming the two vertices) and a real-value weight. The data type 17 | * provides methods for accessing the two endpoints of the edge and 18 | * the weight. The natural order for this data type is by 19 | * ascending order of weight. 20 | *

21 | * For additional documentation, see Section 4.3 of 22 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 23 | * 24 | * @author Robert Sedgewick 25 | * @author Kevin Wayne 26 | */ 27 | public class Edge implements Comparable { 28 | 29 | private final int v; 30 | private final int w; 31 | private final double weight; 32 | 33 | /** 34 | * Initializes an edge between vertices v/tt> and w of 35 | * the given weight. 36 | * param v one vertex 37 | * param w the other vertex 38 | * param weight the weight of the edge 39 | * @throws IndexOutOfBoundsException if either v or w 40 | * is a negative integer 41 | * @throws IllegalArgumentException if weight is NaN 42 | */ 43 | public Edge(int v, int w, double weight) { 44 | if (v < 0) throw new IndexOutOfBoundsException("Vertex name must be a nonnegative integer"); 45 | if (w < 0) throw new IndexOutOfBoundsException("Vertex name must be a nonnegative integer"); 46 | if (Double.isNaN(weight)) throw new IllegalArgumentException("Weight is NaN"); 47 | this.v = v; 48 | this.w = w; 49 | this.weight = weight; 50 | } 51 | 52 | /** 53 | * Returns the weight of the edge. 54 | * @return the weight of the edge 55 | */ 56 | public double weight() { 57 | return weight; 58 | } 59 | 60 | /** 61 | * Returns either endpoint of the edge. 62 | * @return either endpoint of the edge 63 | */ 64 | public int either() { 65 | return v; 66 | } 67 | 68 | /** 69 | * Returns the endpoint of the edge that is different from the given vertex 70 | * (unless the edge represents a self-loop in which case it returns the same vertex). 71 | * @param vertex one endpoint of the edge 72 | * @return the endpoint of the edge that is different from the given vertex 73 | * (unless the edge represents a self-loop in which case it returns the same vertex) 74 | * @throws java.lang.IllegalArgumentException if the vertex is not one of the endpoints 75 | * of the edge 76 | */ 77 | public int other(int vertex) { 78 | if (vertex == v) return w; 79 | else if (vertex == w) return v; 80 | else throw new IllegalArgumentException("Illegal endpoint"); 81 | } 82 | 83 | /** 84 | * Compares two edges by weight. 85 | * @param that the other edge 86 | * @return a negative integer, zero, or positive integer depending on whether 87 | * this edge is less than, equal to, or greater than that edge 88 | */ 89 | public int compareTo(Edge that) { 90 | if (this.weight() < that.weight()) return -1; 91 | else if (this.weight() > that.weight()) return +1; 92 | else return 0; 93 | } 94 | 95 | /** 96 | * Returns a string representation of the edge. 97 | * @return a string representation of the edge 98 | */ 99 | @Override 100 | public String toString() { 101 | return String.format("%d-%d %.5f", v, w, weight); 102 | } 103 | 104 | /** 105 | * Unit tests the Edge data type. 106 | */ 107 | public static void main(String[] args) { 108 | Edge e = new Edge(12, 23, 3.14); 109 | StdOut.println(e); 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/FarthestPair.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdIn; 4 | import edu.princeton.cs.introcs.StdOut; 5 | 6 | /************************************************************************* 7 | * Compilation: javac FarthestPair.java 8 | * Execution: java FarthestPair < input.txt 9 | * Dependencies: GrahamScan.java Point2D.java 10 | * 11 | * Given a set of N points in the plane, find the farthest pair 12 | * (equivalently, compute the diameter of the set of points). 13 | * 14 | * Computes the convex hull of the set of points and using the 15 | * rotating callipers method to find all antipodal point pairs 16 | * and the farthest pair. 17 | * 18 | *************************************************************************/ 19 | 20 | public class FarthestPair { 21 | 22 | // farthest pair of points and distance 23 | private Point2D best1, best2; 24 | private double bestDistance = Double.NEGATIVE_INFINITY; 25 | 26 | public FarthestPair(Point2D[] points) { 27 | GrahamScan graham = new GrahamScan(points); 28 | 29 | // single point 30 | if (points.length <= 1) return; 31 | 32 | // number of points on the hull 33 | int M = 0; 34 | for (Point2D p : graham.hull()) 35 | M++; 36 | 37 | // the hull, in counterclockwise order 38 | Point2D[] hull = new Point2D[M+1]; 39 | int m = 1; 40 | for (Point2D p : graham.hull()) { 41 | hull[m++] = p; 42 | } 43 | 44 | // all points are equal 45 | if (M == 1) return; 46 | 47 | // points are collinear 48 | if (M == 2) { 49 | best1 = hull[1]; 50 | best2 = hull[2]; 51 | bestDistance = best1.distanceTo(best2); 52 | return; 53 | } 54 | 55 | // k = farthest vertex from edge from hull[1] to hull[M] 56 | int k = 2; 57 | while (Point2D.area2(hull[M], hull[k+1], hull[1]) > Point2D.area2(hull[M], hull[k], hull[1])) { 58 | k++; 59 | } 60 | 61 | int j = k; 62 | for (int i = 1; i <= k; i++) { 63 | // StdOut.println("hull[i] + " and " + hull[j] + " are antipodal"); 64 | if (hull[i].distanceTo(hull[j]) > bestDistance) { 65 | best1 = hull[i]; 66 | best2 = hull[j]; 67 | bestDistance = hull[i].distanceTo(hull[j]); 68 | } 69 | while ((j < M) && Point2D.area2(hull[i], hull[j+1], hull[i+1]) > Point2D.area2(hull[i], hull[j], hull[i+1])) { 70 | j++; 71 | // StdOut.println(hull[i] + " and " + hull[j] + " are antipodal"); 72 | double distance = hull[i].distanceTo(hull[j]); 73 | if (distance > bestDistance) { 74 | best1 = hull[i]; 75 | best2 = hull[j]; 76 | bestDistance = hull[i].distanceTo(hull[j]); 77 | } 78 | } 79 | } 80 | } 81 | 82 | public Point2D either() { return best1; } 83 | public Point2D other() { return best2; } 84 | public double distance() { return bestDistance; } 85 | 86 | 87 | public static void main(String[] args) { 88 | int N = StdIn.readInt(); 89 | Point2D[] points = new Point2D[N]; 90 | for (int i = 0; i < N; i++) { 91 | int x = StdIn.readInt(); 92 | int y = StdIn.readInt(); 93 | points[i] = new Point2D(x, y); 94 | } 95 | FarthestPair farthest = new FarthestPair(points); 96 | StdOut.println(farthest.distance() + " from " + farthest.either() + " to " + farthest.other()); 97 | } 98 | 99 | } 100 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/FileIndex.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | /************************************************************************* 4 | * Compilation: javac FileIndex.java 5 | * Execution: java FileIndex file1.txt file2.txt file3.txt ... 6 | * Dependencies: ST.java SET.java In.java StdIn.java StdOut.java 7 | * Data files: http://algs4.cs.princeton.edu/35applications/ex1.txt 8 | * http://algs4.cs.princeton.edu/35applications/ex2.txt 9 | * http://algs4.cs.princeton.edu/35applications/ex3.txt 10 | * http://algs4.cs.princeton.edu/35applications/ex4.txt 11 | * 12 | * % java FileIndex ex*.txt 13 | * age 14 | * ex3.txt 15 | * ex4.txt 16 | * best 17 | * ex1.txt 18 | * was 19 | * ex1.txt 20 | * ex2.txt 21 | * ex3.txt 22 | * ex4.txt 23 | * 24 | * % java FileIndex *.txt 25 | * 26 | * % java FileIndex *.java 27 | * 28 | *************************************************************************/ 29 | 30 | import java.io.File; 31 | 32 | import edu.princeton.cs.introcs.In; 33 | import edu.princeton.cs.introcs.StdIn; 34 | import edu.princeton.cs.introcs.StdOut; 35 | 36 | public class FileIndex { 37 | 38 | public static void main(String[] args) { 39 | 40 | // key = word, value = set of files containing that word 41 | ST> st = new ST>(); 42 | 43 | // create inverted index of all files 44 | StdOut.println("Indexing files"); 45 | for (String filename : args) { 46 | StdOut.println(" " + filename); 47 | File file = new File(filename); 48 | In in = new In(file); 49 | while (!in.isEmpty()) { 50 | String word = in.readString(); 51 | if (!st.contains(word)) st.put(word, new SET()); 52 | SET set = st.get(word); 53 | set.add(file); 54 | } 55 | } 56 | 57 | 58 | // read queries from standard input, one per line 59 | while (!StdIn.isEmpty()) { 60 | String query = StdIn.readString(); 61 | if (st.contains(query)) { 62 | SET set = st.get(query); 63 | for (File file : set) { 64 | StdOut.println(" " + file.getName()); 65 | } 66 | } 67 | } 68 | 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/FrequencyCounter.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdIn; 4 | import edu.princeton.cs.introcs.StdOut; 5 | 6 | /************************************************************************* 7 | * Compilation: javac FrequencyCounter.java 8 | * Execution: java FrequencyCounter L < input.txt 9 | * Dependencies: ST.java StdIn.java StdOut.java 10 | * Data files: http://algs4.cs.princeton.edu/31elementary/tnyTale.txt 11 | * http://algs4.cs.princeton.edu/31elementary/tale.txt 12 | * http://algs4.cs.princeton.edu/31elementary/leipzig100K.txt 13 | * http://algs4.cs.princeton.edu/31elementary/leipzig300K.txt 14 | * http://algs4.cs.princeton.edu/31elementary/leipzig1M.txt 15 | * 16 | * Read in a list of words from standard input and print out 17 | * the most frequently occurring word that has length greater than 18 | * a given threshold. 19 | * 20 | * % java FrequencyCounter 1 < tinyTale.txt 21 | * it 10 22 | * 23 | * % java FrequencyCounter 8 < tale.txt 24 | * business 122 25 | * 26 | * % java FrequencyCounter 10 < leipzig1M.txt 27 | * government 24763 28 | * 29 | * 30 | *************************************************************************/ 31 | 32 | /** 33 | * The FrequencyCounter class provides a client for 34 | * reading in a sequence of words and printing a word (exceeding 35 | * a given length) that occurs most frequently. It is useful as 36 | * a test client for various symbol table implementations. 37 | *

38 | * For additional documentation, see Section 3.1 of 39 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 40 | * 41 | * @author Robert Sedgewick 42 | * @author Kevin Wayne 43 | */ 44 | public class FrequencyCounter { 45 | 46 | /** 47 | * Reads in a command-line integer and sequence of words from 48 | * standard input and prints out a word (whose length exceeds 49 | * the threshold) that occurs most frequently to standard output. 50 | * It also prints out the number of words whose length exceeds 51 | * the threshold and the number of distinct such words. 52 | */ 53 | public static void main(String[] args) { 54 | int distinct = 0, words = 0; 55 | int minlen = Integer.parseInt(args[0]); 56 | ST st = new ST(); 57 | 58 | // compute frequency counts 59 | while (!StdIn.isEmpty()) { 60 | String key = StdIn.readString(); 61 | if (key.length() < minlen) continue; 62 | words++; 63 | if (st.contains(key)) { 64 | st.put(key, st.get(key) + 1); 65 | } 66 | else { 67 | st.put(key, 1); 68 | distinct++; 69 | } 70 | } 71 | 72 | // find a key with the highest frequency count 73 | String max = ""; 74 | st.put(max, 0); 75 | for (String word : st.keys()) { 76 | if (st.get(word) > st.get(max)) 77 | max = word; 78 | } 79 | 80 | StdOut.println(max + " " + st.get(max)); 81 | StdOut.println("distinct = " + distinct); 82 | StdOut.println("words = " + words); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/GREP.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdIn; 4 | import edu.princeton.cs.introcs.StdOut; 5 | 6 | /************************************************************************* 7 | * Compilation: javac GREP.java 8 | * Execution: java GREP regexp < input.txt 9 | * Dependencies: NFA.java 10 | * Data files: http://algs4.cs.princeton.edu/54regexp/tinyL.txt 11 | * 12 | * This program takes an RE as a command-line argument and prints 13 | * the lines from standard input having some substring that 14 | * is in the language described by the RE. 15 | * 16 | * % more tinyL.txt 17 | * AC 18 | * AD 19 | * AAA 20 | * ABD 21 | * ADD 22 | * BCD 23 | * ABCCBD 24 | * BABAAA 25 | * BABBAAA 26 | * 27 | * % java GREP "(A*B|AC)D" < tinyL.txt 28 | * ABD 29 | * ABCCBD 30 | * 31 | *************************************************************************/ 32 | 33 | public class GREP { 34 | public static void main(String[] args) { 35 | String regexp = "(.*" + args[0] + ".*)"; 36 | NFA nfa = new NFA(regexp); 37 | while (StdIn.hasNextLine()) { 38 | String txt = StdIn.readLine(); 39 | if (nfa.recognizes(txt)) { 40 | StdOut.println(txt); 41 | } 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/GaussianElimination.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdOut; 4 | 5 | /************************************************************************* 6 | * Compilation: javac GaussianElimination.java 7 | * Execution: java GaussianElimination 8 | * 9 | * Gaussian elimination with partial pivoting. 10 | * 11 | * % java GaussianElimination 12 | * -1.0 13 | * 2.0 14 | * 2.0 15 | * 16 | *************************************************************************/ 17 | 18 | public class GaussianElimination { 19 | private static final double EPSILON = 1e-10; 20 | 21 | // Gaussian elimination with partial pivoting 22 | public static double[] lsolve(double[][] A, double[] b) { 23 | int N = b.length; 24 | 25 | for (int p = 0; p < N; p++) { 26 | 27 | // find pivot row and swap 28 | int max = p; 29 | for (int i = p + 1; i < N; i++) { 30 | if (Math.abs(A[i][p]) > Math.abs(A[max][p])) { 31 | max = i; 32 | } 33 | } 34 | double[] temp = A[p]; A[p] = A[max]; A[max] = temp; 35 | double t = b[p]; b[p] = b[max]; b[max] = t; 36 | 37 | // singular or nearly singular 38 | if (Math.abs(A[p][p]) <= EPSILON) { 39 | throw new ArithmeticException("Matrix is singular or nearly singular"); 40 | } 41 | 42 | // pivot within A and b 43 | for (int i = p + 1; i < N; i++) { 44 | double alpha = A[i][p] / A[p][p]; 45 | b[i] -= alpha * b[p]; 46 | for (int j = p; j < N; j++) { 47 | A[i][j] -= alpha * A[p][j]; 48 | } 49 | } 50 | } 51 | 52 | // back substitution 53 | double[] x = new double[N]; 54 | for (int i = N - 1; i >= 0; i--) { 55 | double sum = 0.0; 56 | for (int j = i + 1; j < N; j++) { 57 | sum += A[i][j] * x[j]; 58 | } 59 | x[i] = (b[i] - sum) / A[i][i]; 60 | } 61 | return x; 62 | } 63 | 64 | 65 | // sample client 66 | public static void main(String[] args) { 67 | int N = 3; 68 | double[][] A = { 69 | { 0, 1, 1 }, 70 | { 2, 4, -2 }, 71 | { 0, 3, 15 } 72 | }; 73 | double[] b = { 4, 2, 36 }; 74 | double[] x = lsolve(A, b); 75 | 76 | 77 | // print results 78 | for (int i = 0; i < N; i++) { 79 | StdOut.println(x[i]); 80 | } 81 | 82 | } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/Genome.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.BinaryStdIn; 4 | import edu.princeton.cs.introcs.BinaryStdOut; 5 | 6 | /************************************************************************* 7 | * Compilation: javac Genome.java 8 | * Execution: java Genome - < input.txt (compress) 9 | * Execution: java Genome + < input.txt (expand) 10 | * Dependencies: BinaryIn.java BinaryOut.java 11 | * 12 | * Compress or expand a genomic sequence using a 2-bit code. 13 | * 14 | * % more genomeTiny.txt 15 | * ATAGATGCATAGCGCATAGCTAGATGTGCTAGC 16 | * 17 | * % java Genome - < genomeTiny.txt | java Genome + 18 | * ATAGATGCATAGCGCATAGCTAGATGTGCTAGC 19 | * 20 | *************************************************************************/ 21 | 22 | public class Genome { 23 | 24 | public static void compress() { 25 | Alphabet DNA = new Alphabet("ACTG"); 26 | String s = BinaryStdIn.readString(); 27 | int N = s.length(); 28 | BinaryStdOut.write(N); 29 | 30 | // Write two-bit code for char. 31 | for (int i = 0; i < N; i++) { 32 | int d = DNA.toIndex(s.charAt(i)); 33 | BinaryStdOut.write(d, 2); 34 | } 35 | BinaryStdOut.close(); 36 | } 37 | 38 | public static void expand() { 39 | Alphabet DNA = new Alphabet("ACTG"); 40 | int N = BinaryStdIn.readInt(); 41 | // Read two bits; write char. 42 | for (int i = 0; i < N; i++) { 43 | char c = BinaryStdIn.readChar(2); 44 | BinaryStdOut.write(DNA.toChar(c), 8); 45 | } 46 | BinaryStdOut.close(); 47 | } 48 | 49 | 50 | public static void main(String[] args) { 51 | if (args[0].equals("-")) compress(); 52 | else if (args[0].equals("+")) expand(); 53 | else throw new IllegalArgumentException("Illegal command line argument"); 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/GrahamScan.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | /************************************************************************* 4 | * Compilation: javac GrahamaScan.java 5 | * Execution: java GrahamScan < input.txt 6 | * Dependencies: Point2D.java 7 | * 8 | * Create points from standard input and compute the convex hull using 9 | * Graham scan algorithm. 10 | * 11 | * May be floating-point issues if x- and y-coordinates are not integers. 12 | * 13 | *************************************************************************/ 14 | 15 | import java.util.Arrays; 16 | 17 | import edu.princeton.cs.introcs.StdIn; 18 | import edu.princeton.cs.introcs.StdOut; 19 | 20 | public class GrahamScan { 21 | private Stack hull = new Stack(); 22 | 23 | public GrahamScan(Point2D[] pts) { 24 | 25 | // defensive copy 26 | int N = pts.length; 27 | Point2D[] points = new Point2D[N]; 28 | for (int i = 0; i < N; i++) 29 | points[i] = pts[i]; 30 | 31 | // preprocess so that points[0] has lowest y-coordinate; break ties by x-coordinate 32 | // points[0] is an extreme point of the convex hull 33 | // (alternatively, could do easily in linear time) 34 | Arrays.sort(points); 35 | 36 | // sort by polar angle with respect to base point points[0], 37 | // breaking ties by distance to points[0] 38 | Arrays.sort(points, 1, N, points[0].POLAR_ORDER); 39 | 40 | hull.push(points[0]); // p[0] is first extreme point 41 | 42 | // find index k1 of first point not equal to points[0] 43 | int k1; 44 | for (k1 = 1; k1 < N; k1++) 45 | if (!points[0].equals(points[k1])) break; 46 | if (k1 == N) return; // all points equal 47 | 48 | // find index k2 of first point not collinear with points[0] and points[k1] 49 | int k2; 50 | for (k2 = k1 + 1; k2 < N; k2++) 51 | if (Point2D.ccw(points[0], points[k1], points[k2]) != 0) break; 52 | hull.push(points[k2-1]); // points[k2-1] is second extreme point 53 | 54 | // Graham scan; note that points[N-1] is extreme point different from points[0] 55 | for (int i = k2; i < N; i++) { 56 | Point2D top = hull.pop(); 57 | while (Point2D.ccw(hull.peek(), top, points[i]) <= 0) { 58 | top = hull.pop(); 59 | } 60 | hull.push(top); 61 | hull.push(points[i]); 62 | } 63 | 64 | assert isConvex(); 65 | } 66 | 67 | // return extreme points on convex hull in counterclockwise order as an Iterable 68 | public Iterable hull() { 69 | Stack s = new Stack(); 70 | for (Point2D p : hull) s.push(p); 71 | return s; 72 | } 73 | 74 | // check that boundary of hull is strictly convex 75 | private boolean isConvex() { 76 | int N = hull.size(); 77 | if (N <= 2) return true; 78 | 79 | Point2D[] points = new Point2D[N]; 80 | int n = 0; 81 | for (Point2D p : hull()) { 82 | points[n++] = p; 83 | } 84 | 85 | for (int i = 0; i < N; i++) { 86 | if (Point2D.ccw(points[i], points[(i+1) % N], points[(i+2) % N]) <= 0) { 87 | return false; 88 | } 89 | } 90 | return true; 91 | } 92 | 93 | // test client 94 | public static void main(String[] args) { 95 | int N = StdIn.readInt(); 96 | Point2D[] points = new Point2D[N]; 97 | for (int i = 0; i < N; i++) { 98 | int x = StdIn.readInt(); 99 | int y = StdIn.readInt(); 100 | points[i] = new Point2D(x, y); 101 | } 102 | GrahamScan graham = new GrahamScan(points); 103 | for (Point2D p : graham.hull()) 104 | StdOut.println(p); 105 | } 106 | 107 | } 108 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/Heap.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdIn; 4 | import edu.princeton.cs.introcs.StdOut; 5 | 6 | /************************************************************************* 7 | * Compilation: javac Heap.java 8 | * Execution: java Heap < input.txt 9 | * Dependencies: StdOut.java StdIn.java 10 | * Data files: http://algs4.cs.princeton.edu/24pq/tiny.txt 11 | * http://algs4.cs.princeton.edu/24pq/words3.txt 12 | * 13 | * Sorts a sequence of strings from standard input using heapsort. 14 | * 15 | * % more tiny.txt 16 | * S O R T E X A M P L E 17 | * 18 | * % java Heap < tiny.txt 19 | * A E E L M O P R S T X [ one string per line ] 20 | * 21 | * % more words3.txt 22 | * bed bug dad yes zoo ... all bad yet 23 | * 24 | * % java Heap < words3.txt 25 | * all bad bed bug dad ... yes yet zoo [ one string per line ] 26 | * 27 | *************************************************************************/ 28 | 29 | /** 30 | * The Heap class provides a static methods for heapsorting 31 | * an array. 32 | *

33 | * For additional documentation, see Section 2.4 of 34 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 35 | * 36 | * @author Robert Sedgewick 37 | * @author Kevin Wayne 38 | */ 39 | public class Heap { 40 | 41 | // This class should not be instantiated. 42 | private Heap() { } 43 | 44 | /** 45 | * Rearranges the array in ascending order, using the natural order. 46 | * @param pq the array to be sorted 47 | */ 48 | public static void sort(Comparable[] pq) { 49 | int N = pq.length; 50 | for (int k = N/2; k >= 1; k--) 51 | sink(pq, k, N); 52 | while (N > 1) { 53 | exch(pq, 1, N--); 54 | sink(pq, 1, N); 55 | } 56 | } 57 | 58 | /*********************************************************************** 59 | * Helper functions to restore the heap invariant. 60 | **********************************************************************/ 61 | 62 | private static void sink(Comparable[] pq, int k, int N) { 63 | while (2*k <= N) { 64 | int j = 2*k; 65 | if (j < N && less(pq, j, j+1)) j++; 66 | if (!less(pq, k, j)) break; 67 | exch(pq, k, j); 68 | k = j; 69 | } 70 | } 71 | 72 | /*********************************************************************** 73 | * Helper functions for comparisons and swaps. 74 | * Indices are "off-by-one" to support 1-based indexing. 75 | **********************************************************************/ 76 | private static boolean less(Comparable[] pq, int i, int j) { 77 | return pq[i-1].compareTo(pq[j-1]) < 0; 78 | } 79 | 80 | private static void exch(Object[] pq, int i, int j) { 81 | Object swap = pq[i-1]; 82 | pq[i-1] = pq[j-1]; 83 | pq[j-1] = swap; 84 | } 85 | 86 | // is v < w ? 87 | private static boolean less(Comparable v, Comparable w) { 88 | return (v.compareTo(w) < 0); 89 | } 90 | 91 | 92 | /*********************************************************************** 93 | * Check if array is sorted - useful for debugging 94 | ***********************************************************************/ 95 | private static boolean isSorted(Comparable[] a) { 96 | for (int i = 1; i < a.length; i++) 97 | if (less(a[i], a[i-1])) return false; 98 | return true; 99 | } 100 | 101 | 102 | // print array to standard output 103 | private static void show(Comparable[] a) { 104 | for (int i = 0; i < a.length; i++) { 105 | StdOut.println(a[i]); 106 | } 107 | } 108 | 109 | /** 110 | * Reads in a sequence of strings from standard input; heapsorts them; 111 | * and prints them to standard output in ascending order. 112 | */ 113 | public static void main(String[] args) { 114 | String[] a = StdIn.readAllStrings(); 115 | Heap.sort(a); 116 | show(a); 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/HexDump.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.BinaryStdIn; 4 | import edu.princeton.cs.introcs.StdOut; 5 | 6 | /************************************************************************* 7 | * Compilation: javac HexDump.java 8 | * Execution: java HexDump < file 9 | * Dependencies: BinaryStdIn.java 10 | * Data file: http://introcs.cs.princeton.edu/stdlib/abra.txt 11 | * 12 | * Reads in a binary file and writes out the bytes in hex, 16 per line. 13 | * 14 | * % more abra.txt 15 | * ABRACADABRA! 16 | * 17 | * % java HexDump 16 < abra.txt 18 | * 41 42 52 41 43 41 44 41 42 52 41 21 19 | * 96 bits 20 | * 21 | * 22 | * Remark 23 | * -------------------------- 24 | * - Similar to the Unix utilities od (octal dump) or hexdump (hexadecimal dump). 25 | * 26 | * % od -t x1 < abra.txt 27 | * 0000000 41 42 52 41 43 41 44 41 42 52 41 21 28 | * 0000014 29 | * 30 | *************************************************************************/ 31 | 32 | public class HexDump { 33 | 34 | public static void main(String[] args) { 35 | int BYTES_PER_LINE = 16; 36 | if (args.length == 1) { 37 | BYTES_PER_LINE = Integer.parseInt(args[0]); 38 | } 39 | 40 | int i; 41 | for (i = 0; !BinaryStdIn.isEmpty(); i++) { 42 | if (BYTES_PER_LINE == 0) { BinaryStdIn.readChar(); continue; } 43 | if (i == 0) StdOut.printf(""); 44 | else if (i % BYTES_PER_LINE == 0) StdOut.printf("\n", i); 45 | else StdOut.print(" "); 46 | char c = BinaryStdIn.readChar(); 47 | StdOut.printf("%02x", c & 0xff); 48 | } 49 | if (BYTES_PER_LINE != 0) StdOut.println(); 50 | StdOut.println((i*8) + " bits"); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/InsertionX.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdIn; 4 | import edu.princeton.cs.introcs.StdOut; 5 | 6 | /************************************************************************* 7 | * Compilation: javac InsertionX.java 8 | * Execution: java InsertionX < input.txt 9 | * Dependencies: StdOut.java StdIn.java 10 | * Data files: http://algs4.cs.princeton.edu/21sort/tiny.txt 11 | * http://algs4.cs.princeton.edu/21sort/words3.txt 12 | * 13 | * Sorts a sequence of strings from standard input using an optimized 14 | * version of insertion sort. 15 | * 16 | * % more tiny.txt 17 | * S O R T E X A M P L E 18 | * 19 | * % java InsertionX < tiny.txt 20 | * A E E L M O P R S T X [ one string per line ] 21 | * 22 | * % more words3.txt 23 | * bed bug dad yes zoo ... all bad yet 24 | * 25 | * % java InsertionX < words3.txt 26 | * all bad bed bug dad ... yes yet zoo [ one string per line ] 27 | * 28 | *************************************************************************/ 29 | /** 30 | * The InsertionX class provides static methods for sorting an 31 | * array using an optimized version of insertion sort (with half exchanges 32 | * and a sentinel). 33 | *

34 | * For additional documentation, see Section 2.1 of 35 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 36 | * 37 | * @author Robert Sedgewick 38 | * @author Kevin Wayne 39 | */ 40 | 41 | public class InsertionX { 42 | 43 | // This class should not be instantiated. 44 | private InsertionX() { } 45 | 46 | /** 47 | * Rearranges the array in ascending order, using the natural order. 48 | * @param a the array to be sorted 49 | */ 50 | public static void sort(Comparable[] a) { 51 | int N = a.length; 52 | 53 | // put smallest element in position to serve as sentinel 54 | for (int i = N-1; i > 0; i--) 55 | if (less(a[i], a[i-1])) exch(a, i, i-1); 56 | 57 | // insertion sort with half-exchanges 58 | for (int i = 2; i < N; i++) { 59 | Comparable v = a[i]; 60 | int j = i; 61 | while (less(v, a[j-1])) { 62 | a[j] = a[j-1]; 63 | j--; 64 | } 65 | a[j] = v; 66 | } 67 | 68 | assert isSorted(a); 69 | } 70 | 71 | 72 | /*********************************************************************** 73 | * Helper sorting functions 74 | ***********************************************************************/ 75 | 76 | // is v < w ? 77 | private static boolean less(Comparable v, Comparable w) { 78 | return v.compareTo(w) < 0; 79 | } 80 | 81 | // exchange a[i] and a[j] 82 | private static void exch(Object[] a, int i, int j) { 83 | Object swap = a[i]; 84 | a[i] = a[j]; 85 | a[j] = swap; 86 | } 87 | 88 | 89 | /*********************************************************************** 90 | * Check if array is sorted - useful for debugging 91 | ***********************************************************************/ 92 | private static boolean isSorted(Comparable[] a) { 93 | for (int i = 1; i < a.length; i++) 94 | if (less(a[i], a[i-1])) return false; 95 | return true; 96 | } 97 | 98 | // print array to standard output 99 | private static void show(Comparable[] a) { 100 | for (int i = 0; i < a.length; i++) { 101 | StdOut.println(a[i]); 102 | } 103 | } 104 | 105 | /** 106 | * Reads in a sequence of strings from standard input; insertion sorts them; 107 | * and prints them to standard output in ascending order. 108 | */ 109 | public static void main(String[] args) { 110 | String[] a = StdIn.readAllStrings(); 111 | InsertionX.sort(a); 112 | show(a); 113 | } 114 | 115 | } 116 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/Interval2D.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdDraw; 4 | import edu.princeton.cs.introcs.StdOut; 5 | import edu.princeton.cs.introcs.StdRandom; 6 | 7 | /************************************************************************* 8 | * Compilation: javac Interval2D.java 9 | * Execution: java Interval2D 10 | * 11 | * 2-dimensional interval data type. 12 | * 13 | *************************************************************************/ 14 | 15 | /** 16 | * The Interval2D class represents a closed two-dimensional interval, 17 | * which represents all points (x, y) with both xleft <= x <= xright and 18 | * yleft <= y <= right. 19 | * Two-dimensional intervals are immutable: their values cannot be changed 20 | * after they are created. 21 | * The class Interval2D includes methods for checking whether 22 | * a two-dimensional interval contains a point and determining whether 23 | * two two-dimensional intervals intersect. 24 | *

25 | * For additional documentation, see Section 1.2 of 26 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 27 | * 28 | * @author Robert Sedgewick 29 | * @author Kevin Wayne 30 | */ 31 | public class Interval2D { 32 | private final Interval1D x; 33 | private final Interval1D y; 34 | 35 | /** 36 | * Initializes a two-dimensional interval. 37 | * @param x the one-dimensional interval of x-coordinates 38 | * @param y the one-dimensional interval of y-coordinates 39 | */ 40 | public Interval2D(Interval1D x, Interval1D y) { 41 | this.x = x; 42 | this.y = y; 43 | } 44 | 45 | /** 46 | * Does this two-dimensional interval intersect that two-dimensional interval? 47 | * @param that the other two-dimensional interval 48 | * @return true if this two-dimensional interval intersects 49 | * that two-dimensional interval; false otherwise 50 | */ 51 | public boolean intersects(Interval2D that) { 52 | if (!this.x.intersects(that.x)) return false; 53 | if (!this.y.intersects(that.y)) return false; 54 | return true; 55 | } 56 | 57 | /** 58 | * Does this two-dimensional interval contain the point p? 59 | * @param p the two-dimensional point 60 | * @return true if this two-dimensional interval contains the point p; false otherwise 61 | */ 62 | public boolean contains(Point2D p) { 63 | return x.contains(p.x()) && y.contains(p.y()); 64 | } 65 | 66 | /** 67 | * Returns the area of this two-dimensional interval. 68 | * @return the area of this two-dimensional interval 69 | */ 70 | public double area() { 71 | return x.length() * y.length(); 72 | } 73 | 74 | /** 75 | * Returns a string representation of this two-dimensional interval. 76 | * @return a string representation of this two-dimensional interval 77 | * in the form [xleft, xright] x [yleft, yright] 78 | */ 79 | @Override 80 | public String toString() { 81 | return x + " x " + y; 82 | } 83 | 84 | /** 85 | * Draws this two-dimensional interval to standard draw. 86 | */ 87 | public void draw() { 88 | double xc = (x.left() + x.right()) / 2.0; 89 | double yc = (y.left() + y.right()) / 2.0; 90 | StdDraw.rectangle(xc, yc, x.length() / 2.0, y.length() / 2.0); 91 | } 92 | 93 | /** 94 | * Unit tests the Interval2D data type. 95 | */ 96 | public static void main(String[] args) { 97 | double xlo = Double.parseDouble(args[0]); 98 | double xhi = Double.parseDouble(args[1]); 99 | double ylo = Double.parseDouble(args[2]); 100 | double yhi = Double.parseDouble(args[3]); 101 | int T = Integer.parseInt(args[4]); 102 | 103 | Interval1D xinterval = new Interval1D(xlo, xhi); 104 | Interval1D yinterval = new Interval1D(ylo, yhi); 105 | Interval2D box = new Interval2D(xinterval, yinterval); 106 | box.draw(); 107 | 108 | Counter counter = new Counter("hits"); 109 | for (int t = 0; t < T; t++) { 110 | double x = StdRandom.uniform(0.0, 1.0); 111 | double y = StdRandom.uniform(0.0, 1.0); 112 | Point2D p = new Point2D(x, y); 113 | 114 | if (box.contains(p)) counter.increment(); 115 | else p.draw(); 116 | } 117 | 118 | StdOut.println(counter); 119 | StdOut.printf("box area = %.2f\n", box.area()); 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/KMP.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdOut; 4 | 5 | /*************************************************************** 6 | * 7 | * Compilation: javac KMP.java 8 | * Execution: java KMP pattern text 9 | * 10 | * Reads in two strings, the pattern and the input text, and 11 | * searches for the pattern in the input text using the 12 | * KMP algorithm. 13 | * 14 | * % java KMP abracadabra abacadabrabracabracadabrabrabracad 15 | * text: abacadabrabracabracadabrabrabracad 16 | * pattern: abracadabra 17 | * 18 | * % java KMP rab abacadabrabracabracadabrabrabracad 19 | * text: abacadabrabracabracadabrabrabracad 20 | * pattern: rab 21 | * 22 | * % java KMP bcara abacadabrabracabracadabrabrabracad 23 | * text: abacadabrabracabracadabrabrabracad 24 | * pattern: bcara 25 | * 26 | * % java KMP rabrabracad abacadabrabracabracadabrabrabracad 27 | * text: abacadabrabracabracadabrabrabracad 28 | * pattern: rabrabracad 29 | * 30 | * % java KMP abacad abacadabrabracabracadabrabrabracad 31 | * text: abacadabrabracabracadabrabrabracad 32 | * pattern: abacad 33 | * 34 | ***************************************************************/ 35 | 36 | public class KMP { 37 | private final int R; // the radix 38 | private int[][] dfa; // the KMP automoton 39 | 40 | private char[] pattern; // either the character array for the pattern 41 | private String pat; // or the pattern string 42 | 43 | // create the DFA from a String 44 | public KMP(String pat) { 45 | this.R = 256; 46 | this.pat = pat; 47 | 48 | // build DFA from pattern 49 | int M = pat.length(); 50 | dfa = new int[R][M]; 51 | dfa[pat.charAt(0)][0] = 1; 52 | for (int X = 0, j = 1; j < M; j++) { 53 | for (int c = 0; c < R; c++) 54 | dfa[c][j] = dfa[c][X]; // Copy mismatch cases. 55 | dfa[pat.charAt(j)][j] = j+1; // Set match case. 56 | X = dfa[pat.charAt(j)][X]; // Update restart state. 57 | } 58 | } 59 | 60 | // create the DFA from a character array over R-character alphabet 61 | public KMP(char[] pattern, int R) { 62 | this.R = R; 63 | this.pattern = new char[pattern.length]; 64 | for (int j = 0; j < pattern.length; j++) 65 | this.pattern[j] = pattern[j]; 66 | 67 | // build DFA from pattern 68 | int M = pattern.length; 69 | dfa = new int[R][M]; 70 | dfa[pattern[0]][0] = 1; 71 | for (int X = 0, j = 1; j < M; j++) { 72 | for (int c = 0; c < R; c++) 73 | dfa[c][j] = dfa[c][X]; // Copy mismatch cases. 74 | dfa[pattern[j]][j] = j+1; // Set match case. 75 | X = dfa[pattern[j]][X]; // Update restart state. 76 | } 77 | } 78 | 79 | // return offset of first match; N if no match 80 | public int search(String txt) { 81 | 82 | // simulate operation of DFA on text 83 | int M = pat.length(); 84 | int N = txt.length(); 85 | int i, j; 86 | for (i = 0, j = 0; i < N && j < M; i++) { 87 | j = dfa[txt.charAt(i)][j]; 88 | } 89 | if (j == M) return i - M; // found 90 | return N; // not found 91 | } 92 | 93 | 94 | // return offset of first match; N if no match 95 | public int search(char[] text) { 96 | 97 | // simulate operation of DFA on text 98 | int M = pattern.length; 99 | int N = text.length; 100 | int i, j; 101 | for (i = 0, j = 0; i < N && j < M; i++) { 102 | j = dfa[text[i]][j]; 103 | } 104 | if (j == M) return i - M; // found 105 | return N; // not found 106 | } 107 | 108 | 109 | // test client 110 | public static void main(String[] args) { 111 | String pat = args[0]; 112 | String txt = args[1]; 113 | char[] pattern = pat.toCharArray(); 114 | char[] text = txt.toCharArray(); 115 | 116 | KMP kmp1 = new KMP(pat); 117 | int offset1 = kmp1.search(txt); 118 | 119 | KMP kmp2 = new KMP(pattern, 256); 120 | int offset2 = kmp2.search(text); 121 | 122 | // print results 123 | StdOut.println("text: " + txt); 124 | 125 | StdOut.print("pattern: "); 126 | for (int i = 0; i < offset1; i++) 127 | StdOut.print(" "); 128 | StdOut.println(pat); 129 | 130 | StdOut.print("pattern: "); 131 | for (int i = 0; i < offset2; i++) 132 | StdOut.print(" "); 133 | StdOut.println(pat); 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/KWIK.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.In; 4 | import edu.princeton.cs.introcs.StdIn; 5 | import edu.princeton.cs.introcs.StdOut; 6 | 7 | /************************************************************************* 8 | * Compilation: javac KWIK.java 9 | * Execution: java KWIK file.txt 10 | * Dependencies: StdIn.java StdOut.java In.java SuffixArray.java 11 | * Data files: http://algs4.cs.princeton.edu/63suffix/tale.txt 12 | * 13 | * % java KWIK tale.txt 15 14 | * majesty 15 | * most gracious majesty king george th 16 | * rnkeys and the majesty of the law fir 17 | * on against the majesty of the people 18 | * se them to his majestys chief secreta 19 | * h lists of his majestys forces and of 20 | * 21 | * the worst 22 | * w the best and the worst are known to y 23 | * f them give me the worst first there th 24 | * for in case of the worst is a friend in 25 | * e roomdoor and the worst is over then a 26 | * pect mr darnay the worst its the wisest 27 | * is his brother the worst of a bad race 28 | * ss in them for the worst of health for 29 | * you have seen the worst of her agitati 30 | * cumwented into the worst of luck buuust 31 | * n your brother the worst of the bad rac 32 | * full share in the worst of the day pla 33 | * mes to himself the worst of the strife 34 | * f times it was the worst of times it wa 35 | * ould hope that the worst was over well 36 | * urage business the worst will be over i 37 | * clesiastics of the worst world worldly 38 | * 39 | *************************************************************************/ 40 | 41 | public class KWIK { 42 | 43 | public static void main(String[] args) { 44 | In in = new In(args[0]); 45 | int context = Integer.parseInt(args[1]); 46 | 47 | // read in text 48 | String text = in.readAll().replaceAll("\\s+", " "); 49 | int N = text.length(); 50 | 51 | // build suffix array 52 | SuffixArray sa = new SuffixArray(text); 53 | 54 | // find all occurrences of queries and give context 55 | while (StdIn.hasNextLine()) { 56 | String query = StdIn.readLine(); 57 | for (int i = sa.rank(query); i < N; i++) { 58 | int from1 = sa.index(i); 59 | int to1 = Math.min(N, from1 + query.length()); 60 | if (!query.equals(text.substring(from1, to1))) break; 61 | int from2 = Math.max(0, sa.index(i) - context); 62 | int to2 = Math.min(N, sa.index(i) + context + query.length()); 63 | StdOut.println(text.substring(from2, to2)); 64 | } 65 | StdOut.println(); 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/Knuth.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdIn; 4 | import edu.princeton.cs.introcs.StdOut; 5 | import edu.princeton.cs.introcs.StdRandom; 6 | 7 | /************************************************************************* 8 | * Compilation: javac Knuth.java 9 | * Execution: java Knuth < list.txt 10 | * Dependencies: StdIn.java StdOut.java 11 | * Data files: http://algs4.cs.princeton.edu/11model/cards.txt 12 | * 13 | * Reads in a list of strings and prints them in random order. 14 | * The Knuth (or Fisher-Yates) shuffling algorithm guarantees 15 | * to rearrange the elements in uniformly random order, under 16 | * the assumption that Math.random() generates independent and 17 | * uniformly distributed numbers between 0 and 1. 18 | * 19 | * % more cards.txt 20 | * 2C 3C 4C 5C 6C 7C 8C 9C 10C JC QC KC AC 21 | * 2D 3D 4D 5D 6D 7D 8D 9D 10D JD QD KD AD 22 | * 2H 3H 4H 5H 6H 7H 8H 9H 10H JH QH KH AH 23 | * 2S 3S 4S 5S 6S 7S 8S 9S 10S JS QS KS AS 24 | * 25 | * % java Knuth < cards.txt 26 | * 6H 27 | * 9C 28 | * 8H 29 | * 7C 30 | * JS 31 | * ... 32 | * KH 33 | * 34 | *************************************************************************/ 35 | 36 | /** 37 | * The Knuth class provides a client for reading in a 38 | * sequence of strings and shuffling them using the Knuth (or Fisher-Yates) 39 | * shuffling algorithm. This algorithm guarantees to rearrange the 40 | * elements in uniformly random order, under 41 | * the assumption that Math.random() generates independent and 42 | * uniformly distributed numbers between 0 and 1. 43 | *

44 | * For additional documentation, see Section 1.1 of 45 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 46 | * 47 | * @author Robert Sedgewick 48 | * @author Kevin Wayne 49 | */ 50 | public class Knuth { 51 | 52 | // this class should not be instantiated 53 | private Knuth() { } 54 | 55 | /** 56 | * Rearranges an array of objects in uniformly random order 57 | * (under the assumption that Math.random() generates independent 58 | * and uniformly distributed numbers between 0 and 1). 59 | * @param a the array to be shuffled 60 | * @see StdRandom 61 | */ 62 | public static void shuffle(Object[] a) { 63 | int N = a.length; 64 | for (int i = 0; i < N; i++) { 65 | // choose index uniformly in [i, N-1] 66 | int r = i + (int) (Math.random() * (N - i)); 67 | Object swap = a[r]; 68 | a[r] = a[i]; 69 | a[i] = swap; 70 | } 71 | } 72 | 73 | /** 74 | * Reads in a sequence of strings from standard input, shuffles 75 | * them, and prints out the results. 76 | */ 77 | public static void main(String[] args) { 78 | 79 | // read in the data 80 | String[] a = StdIn.readAllStrings(); 81 | 82 | // shuffle the array 83 | Knuth.shuffle(a); 84 | 85 | // print results. 86 | for (int i = 0; i < a.length; i++) 87 | StdOut.println(a[i]); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/LRS.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdIn; 4 | import edu.princeton.cs.introcs.StdOut; 5 | 6 | /************************************************************************* 7 | * Compilation: javac LRS.java 8 | * Execution: java LRS < file.txt 9 | * Dependencies: StdIn.java SuffixArray.java 10 | * Data files: http://algs4.cs.princeton.edu/63suffix/tinyTale.txt 11 | * http://algs4.cs.princeton.edu/63suffix/mobydick.txt 12 | * 13 | * Reads a text string from stdin, replaces all consecutive blocks of 14 | * whitespace with a single space, and then computes the longest 15 | * repeated substring in that text using a suffix array. 16 | * 17 | * % java LRS < tinyTale.txt 18 | * 'st of times it was the ' 19 | * 20 | * % java LRS < mobydick.txt 21 | * ',- Such a funny, sporty, gamy, jesty, joky, hoky-poky lad, is the Ocean, oh! Th' 22 | * 23 | * % java LRS 24 | * aaaaaaaaa 25 | * 'aaaaaaaa' 26 | * 27 | * % java LRS 28 | * abcdefg 29 | * '' 30 | * 31 | *************************************************************************/ 32 | 33 | 34 | public class LRS { 35 | 36 | public static void main(String[] args) { 37 | String text = StdIn.readAll().replaceAll("\\s+", " "); 38 | SuffixArray sa = new SuffixArray(text); 39 | 40 | int N = sa.length(); 41 | 42 | String lrs = ""; 43 | for (int i = 1; i < N; i++) { 44 | int length = sa.lcp(i); 45 | if (length > lrs.length()) { 46 | // lrs = sa.select(i).substring(0, length); 47 | lrs = text.substring(sa.index(i), sa.index(i) + length); 48 | } 49 | } 50 | 51 | StdOut.println("'" + lrs + "'"); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/LSD.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdIn; 4 | import edu.princeton.cs.introcs.StdOut; 5 | 6 | /*********************************************************************************** 7 | * Compilation: javac LSD.java 8 | * Execution: java LSD < input.txt 9 | * 10 | * LSD radix sort an array of extended ASCII strings, each of length W. 11 | * 12 | * % java LSD < words3.txt 13 | * all 14 | * bad 15 | * bed 16 | * bug 17 | * dad 18 | * ... 19 | * yes 20 | * yet 21 | * zoo 22 | * 23 | ***********************************************************************************/ 24 | 25 | public class LSD { 26 | 27 | // LSD radix sort 28 | public static void sort(String[] a, int W) { 29 | int N = a.length; 30 | int R = 256; // extend ASCII alphabet size 31 | String[] aux = new String[N]; 32 | 33 | for (int d = W-1; d >= 0; d--) { 34 | // sort by key-indexed counting on dth character 35 | 36 | // compute frequency counts 37 | int[] count = new int[R+1]; 38 | for (int i = 0; i < N; i++) 39 | count[a[i].charAt(d) + 1]++; 40 | 41 | // compute cumulates 42 | for (int r = 0; r < R; r++) 43 | count[r+1] += count[r]; 44 | 45 | // move data 46 | for (int i = 0; i < N; i++) 47 | aux[count[a[i].charAt(d)]++] = a[i]; 48 | 49 | // copy back 50 | for (int i = 0; i < N; i++) 51 | a[i] = aux[i]; 52 | } 53 | } 54 | 55 | 56 | public static void main(String[] args) { 57 | String[] a = StdIn.readAllStrings(); 58 | int N = a.length; 59 | 60 | // check that strings have fixed length 61 | int W = a[0].length(); 62 | for (int i = 0; i < N; i++) 63 | assert a[i].length() == W : "Strings must have fixed length"; 64 | 65 | // sort the strings 66 | sort(a, W); 67 | 68 | // print results 69 | for (int i = 0; i < N; i++) 70 | StdOut.println(a[i]); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/LZW.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.BinaryStdIn; 4 | import edu.princeton.cs.introcs.BinaryStdOut; 5 | 6 | /************************************************************************* 7 | * Compilation: javac LZW.java 8 | * Execution: java LZW - < input.txt (compress) 9 | * Execution: java LZW + < input.txt (expand) 10 | * Dependencies: BinaryIn.java BinaryOut.java 11 | * 12 | * Compress or expand binary input from standard input using LZW. 13 | * 14 | * WARNING: STARTING WITH ORACLE JAVA 6, UPDATE 7 the SUBSTRING 15 | * METHOD TAKES TIME AND SPACE LINEAR IN THE SIZE OF THE EXTRACTED 16 | * SUBSTRING (INSTEAD OF CONSTANT SPACE AND TIME AS IN EARLIER 17 | * IMPLEMENTATIONS). 18 | * 19 | * See this article 20 | * for more details. 21 | * 22 | *************************************************************************/ 23 | 24 | public class LZW { 25 | private static final int R = 256; // number of input chars 26 | private static final int L = 4096; // number of codewords = 2^W 27 | private static final int W = 12; // codeword width 28 | 29 | public static void compress() { 30 | String input = BinaryStdIn.readString(); 31 | TST st = new TST(); 32 | for (int i = 0; i < R; i++) 33 | st.put("" + (char) i, i); 34 | int code = R+1; // R is codeword for EOF 35 | 36 | while (input.length() > 0) { 37 | String s = st.longestPrefixOf(input); // Find max prefix match s. 38 | BinaryStdOut.write(st.get(s), W); // Print s's encoding. 39 | int t = s.length(); 40 | if (t < input.length() && code < L) // Add s to symbol table. 41 | st.put(input.substring(0, t + 1), code++); 42 | input = input.substring(t); // Scan past s in input. 43 | } 44 | BinaryStdOut.write(R, W); 45 | BinaryStdOut.close(); 46 | } 47 | 48 | 49 | public static void expand() { 50 | String[] st = new String[L]; 51 | int i; // next available codeword value 52 | 53 | // initialize symbol table with all 1-character strings 54 | for (i = 0; i < R; i++) 55 | st[i] = "" + (char) i; 56 | st[i++] = ""; // (unused) lookahead for EOF 57 | 58 | int codeword = BinaryStdIn.readInt(W); 59 | String val = st[codeword]; 60 | 61 | while (true) { 62 | BinaryStdOut.write(val); 63 | codeword = BinaryStdIn.readInt(W); 64 | if (codeword == R) break; 65 | String s = st[codeword]; 66 | if (i == codeword) s = val + val.charAt(0); // special case hack 67 | if (i < L) st[i++] = val + s.charAt(0); 68 | val = s; 69 | } 70 | BinaryStdOut.close(); 71 | } 72 | 73 | 74 | 75 | public static void main(String[] args) { 76 | if (args[0].equals("-")) compress(); 77 | else if (args[0].equals("+")) expand(); 78 | else throw new IllegalArgumentException("Illegal command line argument"); 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/LinkedBag.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | /************************************************************************* 4 | * Compilation: javac LinkedBag.java 5 | * Execution: java LinkedBag < input.txt 6 | * 7 | * A generic bag or multiset, implemented using a singly-linked list. 8 | * 9 | * % more tobe.txt 10 | * to be or not to - be - - that - - - is 11 | * 12 | * % java Bag < tobe.txt 13 | * size of bag = 14 14 | * is 15 | * - 16 | * - 17 | * - 18 | * that 19 | * - 20 | * - 21 | * be 22 | * - 23 | * to 24 | * not 25 | * or 26 | * be 27 | * to 28 | * 29 | *************************************************************************/ 30 | 31 | import java.util.Iterator; 32 | import java.util.NoSuchElementException; 33 | 34 | import edu.princeton.cs.introcs.StdIn; 35 | import edu.princeton.cs.introcs.StdOut; 36 | 37 | /** 38 | * The LinkedBag class represents a bag (or multiset) of 39 | * generic items. It supports insertion and iterating over the 40 | * items in arbitrary order. 41 | *

42 | * This implementation uses a singly-linked list with a non-static nested class Node. 43 | * See {@link Bag} for a version that uses a static nested class. 44 | * The add, isEmpty, and size operations 45 | * take constant time. Iteration takes time proportional to the number of items. 46 | *

47 | * For additional documentation, see Section 1.3 of 48 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 49 | * 50 | * @author Robert Sedgewick 51 | * @author Kevin Wayne 52 | */ 53 | public class LinkedBag implements Iterable { 54 | private int N; // number of elements in bag 55 | private Node first; // beginning of bag 56 | 57 | // helper linked list class 58 | private class Node { 59 | private Item item; 60 | private Node next; 61 | } 62 | 63 | /** 64 | * Initializes an empty bag. 65 | */ 66 | public LinkedBag() { 67 | first = null; 68 | N = 0; 69 | } 70 | 71 | /** 72 | * Is this bag empty? 73 | * @return true if this bag is empty; false otherwise 74 | */ 75 | public boolean isEmpty() { 76 | return first == null; 77 | } 78 | 79 | /** 80 | * Returns the number of items in this bag. 81 | * @return the number of items in this bag 82 | */ 83 | public int size() { 84 | return N; 85 | } 86 | 87 | /** 88 | * Adds the item to this bag. 89 | * @param item the item to add to this bag 90 | */ 91 | public void add(Item item) { 92 | Node oldfirst = first; 93 | first = new Node(); 94 | first.item = item; 95 | first.next = oldfirst; 96 | N++; 97 | } 98 | 99 | 100 | /** 101 | * Returns an iterator that iterates over the items in the bag. 102 | */ 103 | public Iterator iterator() { 104 | return new ListIterator(); 105 | } 106 | 107 | // an iterator, doesn't implement remove() since it's optional 108 | private class ListIterator implements Iterator { 109 | private Node current = first; 110 | 111 | public boolean hasNext() { return current != null; } 112 | public void remove() { throw new UnsupportedOperationException(); } 113 | 114 | public Item next() { 115 | if (!hasNext()) throw new NoSuchElementException(); 116 | Item item = current.item; 117 | current = current.next; 118 | return item; 119 | } 120 | } 121 | 122 | /** 123 | * Unit tests the LinkedBag data type. 124 | */ 125 | public static void main(String[] args) { 126 | LinkedBag bag = new LinkedBag(); 127 | while (!StdIn.isEmpty()) { 128 | String item = StdIn.readString(); 129 | bag.add(item); 130 | } 131 | 132 | StdOut.println("size of bag = " + bag.size()); 133 | for (String s : bag) { 134 | StdOut.println(s); 135 | } 136 | } 137 | 138 | 139 | } 140 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/LongestCommonSubstring.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.In; 4 | import edu.princeton.cs.introcs.StdOut; 5 | 6 | /************************************************************************* 7 | * Compilation: javac LongestCommonSubstring.java 8 | * Execution: java LongestCommonSubstring file1.txt file2.txt 9 | * Dependencies: SuffixArray.java StdOut.java In.java 10 | * 11 | * Reads in two text strings, replaces all consecutive blocks of 12 | * whitespace with a single space, and then computes the longest 13 | * common substring. 14 | * 15 | * Assumes that the character '\1' does not appear in either text. 16 | * Perhaps, search for a character that does not appear in either text 17 | * (and make sure SuffixArray.java doesn't choose the same one). 18 | * 19 | * % java LongestCommonSubstring tale.txt mobydick.txt 20 | * ' seemed on the point of being ' 21 | * 22 | *************************************************************************/ 23 | 24 | 25 | public class LongestCommonSubstring { 26 | 27 | public static void main(String[] args) { 28 | 29 | // read in two string from two files 30 | In in1 = new In(args[0]); 31 | In in2 = new In(args[1]); 32 | String text1 = in1.readAll().trim().replaceAll("\\s+", " "); 33 | String text2 = in2.readAll().trim().replaceAll("\\s+", " "); 34 | int N1 = text1.length(); 35 | int N2 = text2.length(); 36 | 37 | // concatenate two string with intervening '\1' 38 | String text = text1 + '\1' + text2; 39 | int N = text.length(); 40 | 41 | // compute suffix array of concatenated text 42 | SuffixArray suffix = new SuffixArray(text); 43 | 44 | // search for longest common substring 45 | String lcs = ""; 46 | for (int i = 1; i < N; i++) { 47 | 48 | // adjacent suffixes both from first text string 49 | if (suffix.index(i) < N1 && suffix.index(i-1) < N1) continue; 50 | 51 | // adjacent suffixes both from secondt text string 52 | if (suffix.index(i) > N1 && suffix.index(i-1) > N1) continue; 53 | 54 | // check if adjacent suffixes longer common substring 55 | int length = suffix.lcp(i); 56 | if (length > lcs.length()) { 57 | lcs = text.substring(suffix.index(i), suffix.index(i) + length); 58 | } 59 | } 60 | 61 | // print out longest common substring 62 | StdOut.println(lcs.length()); 63 | StdOut.println("'" + lcs + "'"); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/LookupCSV.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.In; 4 | import edu.princeton.cs.introcs.StdIn; 5 | import edu.princeton.cs.introcs.StdOut; 6 | 7 | /************************************************************************* 8 | * Compilation: javac LookupCSV.java 9 | * Execution: java LookupCSV file.csv keyField valField 10 | * Dependencies: ST.java In.java StdIn.java StdOut.java 11 | * Data files: http://algs4.cs.princeton.edu/35applications/DJIA.csv 12 | * http://algs4.cs.princeton.edu/35applications/UPC.csv 13 | * http://algs4.cs.princeton.edu/35applications/amino.csv 14 | * http://algs4.cs.princeton.edu/35applications/elements.csv 15 | * http://algs4.cs.princeton.edu/35applications/ip.csv 16 | * http://algs4.cs.princeton.edu/35applications/morse.csv 17 | * 18 | * Reads in a set of key-value pairs from a two-column CSV file 19 | * specified on the command line; then, reads in keys from standard 20 | * input and prints out corresponding values. 21 | * 22 | * % java LookupCSV amino.csv 0 3 % java LookupCSV ip.csv 0 1 23 | * TTA www.google.com 24 | * Leucine 216.239.41.99 25 | * ABC 26 | * Not found % java LookupCSV ip.csv 1 0 27 | * TCT 216.239.41.99 28 | * Serine www.google.com 29 | * 30 | * % java LookupCSV amino.csv 3 0 % java LookupCSV DJIA.csv 0 1 31 | * Glycine 29-Oct-29 32 | * GGG 252.38 33 | * 20-Oct-87 34 | * 1738.74 35 | * 36 | * 37 | *************************************************************************/ 38 | 39 | public class LookupCSV { 40 | public static void main(String[] args) { 41 | int keyField = Integer.parseInt(args[1]); 42 | int valField = Integer.parseInt(args[2]); 43 | 44 | // symbol table 45 | ST st = new ST(); 46 | 47 | // read in the data from csv file 48 | In in = new In(args[0]); 49 | while (in.hasNextLine()) { 50 | String line = in.readLine(); 51 | String[] tokens = line.split(","); 52 | String key = tokens[keyField]; 53 | String val = tokens[valField]; 54 | st.put(key, val); 55 | } 56 | 57 | while (!StdIn.isEmpty()) { 58 | String s = StdIn.readString(); 59 | if (st.contains(s)) StdOut.println(st.get(s)); 60 | else StdOut.println("Not found"); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/LookupIndex.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.In; 4 | import edu.princeton.cs.introcs.StdIn; 5 | import edu.princeton.cs.introcs.StdOut; 6 | 7 | /************************************************************************* 8 | * Compilation: javac LookupIndex.java 9 | * Execution: java LookupIndex movies.txt "/" 10 | * Dependencies: ST.java Queue.java In.java StdIn.java StdOut.java 11 | * Data files: http://algs4.cs.princeton.edu/35applications/aminoI.csv 12 | * http://algs4.cs.princeton.edu/35applications/movies.txt 13 | * 14 | * % java LookupIndex aminoI.csv "," 15 | * Serine 16 | * TCT 17 | * TCA 18 | * TCG 19 | * AGT 20 | * AGC 21 | * TCG 22 | * Serine 23 | * 24 | * % java LookupIndex movies.txt "/" 25 | * Bacon, Kevin 26 | * Animal House (1978) 27 | * Apollo 13 (1995) 28 | * Beauty Shop (2005) 29 | * Diner (1982) 30 | * Few Good Men, A (1992) 31 | * Flatliners (1990) 32 | * Footloose (1984) 33 | * Friday the 13th (1980) 34 | * ... 35 | * Tin Men (1987) 36 | * DeBoy, David 37 | * Blumenfeld, Alan 38 | * ... 39 | * 40 | *************************************************************************/ 41 | 42 | public class LookupIndex { 43 | 44 | public static void main(String[] args) { 45 | String filename = args[0]; 46 | String separator = args[1]; 47 | In in = new In(filename); 48 | 49 | ST> st = new ST>(); 50 | ST> ts = new ST>(); 51 | 52 | while (in.hasNextLine()) { 53 | String line = in.readLine(); 54 | String[] fields = line.split(separator); 55 | String key = fields[0]; 56 | for (int i = 1; i < fields.length; i++) { 57 | String val = fields[i]; 58 | if (!st.contains(key)) st.put(key, new Queue()); 59 | if (!ts.contains(val)) ts.put(val, new Queue()); 60 | st.get(key).enqueue(val); 61 | ts.get(val).enqueue(key); 62 | } 63 | } 64 | 65 | StdOut.println("Done indexing"); 66 | 67 | // read queries from standard input, one per line 68 | while (!StdIn.isEmpty()) { 69 | String query = StdIn.readLine(); 70 | if (st.contains(query)) 71 | for (String vals : st.get(query)) 72 | StdOut.println(" " + vals); 73 | if (ts.contains(query)) 74 | for (String keys : ts.get(query)) 75 | StdOut.println(" " + keys); 76 | } 77 | 78 | } 79 | 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/MSD.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdIn; 4 | import edu.princeton.cs.introcs.StdOut; 5 | 6 | /*********************************************************************************** 7 | * Compilation: javac MSD.java 8 | * Execution: java MSD < input.txt 9 | * 10 | * Reads extended ASCII string from standard input and MSD radix sorts them. 11 | * 12 | * % java MSD < shells.txt 13 | * are 14 | * by 15 | * sea 16 | * seashells 17 | * seashells 18 | * sells 19 | * sells 20 | * she 21 | * she 22 | * shells 23 | * shore 24 | * surely 25 | * the 26 | * the 27 | * 28 | ***********************************************************************************/ 29 | 30 | public class MSD { 31 | private static final int R = 256; // extended ASCII alphabet size 32 | private static final int CUTOFF = 15; // cutoff to insertion sort 33 | 34 | // sort array of strings 35 | public static void sort(String[] a) { 36 | int N = a.length; 37 | String[] aux = new String[N]; 38 | sort(a, 0, N-1, 0, aux); 39 | } 40 | 41 | // return dth character of s, -1 if d = length of string 42 | private static int charAt(String s, int d) { 43 | assert d >= 0 && d <= s.length(); 44 | if (d == s.length()) return -1; 45 | return s.charAt(d); 46 | } 47 | 48 | // sort from a[lo] to a[hi], starting at the dth character 49 | private static void sort(String[] a, int lo, int hi, int d, String[] aux) { 50 | 51 | // cutoff to insertion sort for small subarrays 52 | if (hi <= lo + CUTOFF) { 53 | insertion(a, lo, hi, d); 54 | return; 55 | } 56 | 57 | // compute frequency counts 58 | int[] count = new int[R+2]; 59 | for (int i = lo; i <= hi; i++) { 60 | int c = charAt(a[i], d); 61 | count[c+2]++; 62 | } 63 | 64 | // transform counts to indicies 65 | for (int r = 0; r < R+1; r++) 66 | count[r+1] += count[r]; 67 | 68 | // distribute 69 | for (int i = lo; i <= hi; i++) { 70 | int c = charAt(a[i], d); 71 | aux[count[c+1]++] = a[i]; 72 | } 73 | 74 | // copy back 75 | for (int i = lo; i <= hi; i++) 76 | a[i] = aux[i - lo]; 77 | 78 | 79 | // recursively sort for each character 80 | for (int r = 0; r < R; r++) 81 | sort(a, lo + count[r], lo + count[r+1] - 1, d+1, aux); 82 | } 83 | 84 | 85 | // return dth character of s, -1 if d = length of string 86 | private static void insertion(String[] a, int lo, int hi, int d) { 87 | for (int i = lo; i <= hi; i++) 88 | for (int j = i; j > lo && less(a[j], a[j-1], d); j--) 89 | exch(a, j, j-1); 90 | } 91 | 92 | // exchange a[i] and a[j] 93 | private static void exch(String[] a, int i, int j) { 94 | String temp = a[i]; 95 | a[i] = a[j]; 96 | a[j] = temp; 97 | } 98 | 99 | // is v less than w, starting at character d 100 | // DEPRECATED BECAUSE OF SLOW SUBSTRING EXTRACTION IN JAVA 7 101 | // private static boolean less(String v, String w, int d) { 102 | // assert v.substring(0, d).equals(w.substring(0, d)); 103 | // return v.substring(d).compareTo(w.substring(d)) < 0; 104 | // } 105 | 106 | // is v less than w, starting at character d 107 | private static boolean less(String v, String w, int d) { 108 | assert v.substring(0, d).equals(w.substring(0, d)); 109 | for (int i = d; i < Math.min(v.length(), w.length()); i++) { 110 | if (v.charAt(i) < w.charAt(i)) return true; 111 | if (v.charAt(i) > w.charAt(i)) return false; 112 | } 113 | return v.length() < w.length(); 114 | } 115 | 116 | 117 | public static void main(String[] args) { 118 | String[] a = StdIn.readAllStrings(); 119 | int N = a.length; 120 | sort(a); 121 | for (int i = 0; i < N; i++) 122 | StdOut.println(a[i]); 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/MergeBU.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdIn; 4 | import edu.princeton.cs.introcs.StdOut; 5 | 6 | /************************************************************************* 7 | * Compilation: javac MergeBU.java 8 | * Execution: java MergeBU < input.txt 9 | * Dependencies: StdOut.java StdIn.java 10 | * Data files: http://algs4.cs.princeton.edu/22mergesort/tiny.txt 11 | * http://algs4.cs.princeton.edu/22mergesort/words3.txt 12 | * 13 | * Sorts a sequence of strings from standard input using 14 | * bottom-up mergesort. 15 | * 16 | * % more tiny.txt 17 | * S O R T E X A M P L E 18 | * 19 | * % java MergeBU < tiny.txt 20 | * A E E L M O P R S T X [ one string per line ] 21 | * 22 | * % more words3.txt 23 | * bed bug dad yes zoo ... all bad yet 24 | * 25 | * % java MergeBU < words3.txt 26 | * all bad bed bug dad ... yes yet zoo [ one string per line ] 27 | * 28 | *************************************************************************/ 29 | 30 | /** 31 | * The MergeBU class provides static methods for sorting an 32 | * array using bottom-up mergesort. 33 | *

34 | * For additional documentation, see Section 2.1 of 35 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 36 | * 37 | * @author Robert Sedgewick 38 | * @author Kevin Wayne 39 | */ 40 | public class MergeBU { 41 | 42 | // This class should not be instantiated. 43 | private MergeBU() { } 44 | 45 | // stably merge a[lo..mid] with a[mid+1..hi] using aux[lo..hi] 46 | private static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) { 47 | 48 | // copy to aux[] 49 | for (int k = lo; k <= hi; k++) { 50 | aux[k] = a[k]; 51 | } 52 | 53 | // merge back to a[] 54 | int i = lo, j = mid+1; 55 | for (int k = lo; k <= hi; k++) { 56 | if (i > mid) a[k] = aux[j++]; // this copying is unneccessary 57 | else if (j > hi) a[k] = aux[i++]; 58 | else if (less(aux[j], aux[i])) a[k] = aux[j++]; 59 | else a[k] = aux[i++]; 60 | } 61 | 62 | } 63 | 64 | /** 65 | * Rearranges the array in ascending order, using the natural order. 66 | * @param a the array to be sorted 67 | */ 68 | public static void sort(Comparable[] a) { 69 | int N = a.length; 70 | Comparable[] aux = new Comparable[N]; 71 | for (int n = 1; n < N; n = n+n) { 72 | for (int i = 0; i < N-n; i += n+n) { 73 | int lo = i; 74 | int m = i+n-1; 75 | int hi = Math.min(i+n+n-1, N-1); 76 | merge(a, aux, lo, m, hi); 77 | } 78 | } 79 | assert isSorted(a); 80 | } 81 | 82 | /*********************************************************************** 83 | * Helper sorting functions 84 | ***********************************************************************/ 85 | 86 | // is v < w ? 87 | private static boolean less(Comparable v, Comparable w) { 88 | return (v.compareTo(w) < 0); 89 | } 90 | 91 | // exchange a[i] and a[j] 92 | private static void exch(Object[] a, int i, int j) { 93 | Object swap = a[i]; 94 | a[i] = a[j]; 95 | a[j] = swap; 96 | } 97 | 98 | 99 | /*********************************************************************** 100 | * Check if array is sorted - useful for debugging 101 | ***********************************************************************/ 102 | private static boolean isSorted(Comparable[] a) { 103 | for (int i = 1; i < a.length; i++) 104 | if (less(a[i], a[i-1])) return false; 105 | return true; 106 | } 107 | 108 | // print array to standard output 109 | private static void show(Comparable[] a) { 110 | for (int i = 0; i < a.length; i++) { 111 | StdOut.println(a[i]); 112 | } 113 | } 114 | 115 | /** 116 | * Reads in a sequence of strings from standard input; bottom-up 117 | * mergesorts them; and prints them to standard output in ascending order. 118 | */ 119 | public static void main(String[] args) { 120 | String[] a = StdIn.readAllStrings(); 121 | MergeBU.sort(a); 122 | show(a); 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/Multiway.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.In; 4 | import edu.princeton.cs.introcs.StdOut; 5 | 6 | /************************************************************************* 7 | * Compilation: javac Multiway.java 8 | * Execution: java Multiway input1.txt input2.txt input3.txt ... 9 | * Dependencies: IndexMinPQ.java In.java StdOut.java 10 | * 11 | * Merges together the sorted input stream given as command-line arguments 12 | * into a single sorted output stream on standard output. 13 | * 14 | * % more m1.txt 15 | * A B C F G I I Z 16 | * 17 | * % more m2.txt 18 | * B D H P Q Q 19 | * 20 | * % more m3.txt 21 | * A B E F J N 22 | * 23 | * % java Multiway m1.txt m2.txt m3.txt 24 | * A A B B B C D E F F G H I I J N P Q Q Z 25 | * 26 | *************************************************************************/ 27 | 28 | /** 29 | * The Multiway class provides a client for reading in several 30 | * sorted text files and merging them together into a single sorted 31 | * text stream. 32 | * This implementation uses a {@link IndexMinPQ} to perform the multiway 33 | * merge. 34 | *

35 | * For additional documentation, see Section 2.4 36 | * of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 37 | * 38 | * @author Robert Sedgewick 39 | * @author Kevin Wayne 40 | */ 41 | 42 | public class Multiway { 43 | 44 | // This class should not be instantiated. 45 | private Multiway() { } 46 | 47 | // merge together the sorted input streams and write the sorted result to standard output 48 | private static void merge(In[] streams) { 49 | int N = streams.length; 50 | IndexMinPQ pq = new IndexMinPQ(N); 51 | for (int i = 0; i < N; i++) 52 | if (!streams[i].isEmpty()) 53 | pq.insert(i, streams[i].readString()); 54 | 55 | // Extract and print min and read next from its stream. 56 | while (!pq.isEmpty()) { 57 | StdOut.print(pq.minKey() + " "); 58 | int i = pq.delMin(); 59 | if (!streams[i].isEmpty()) 60 | pq.insert(i, streams[i].readString()); 61 | } 62 | StdOut.println(); 63 | } 64 | 65 | 66 | /** 67 | * Reads sorted text files specified as command-line arguments; 68 | * merges them together into a sorted output; and writes 69 | * the results to standard output. 70 | * Note: this client does not check that the input files are sorted. 71 | */ 72 | public static void main(String[] args) { 73 | int N = args.length; 74 | In[] streams = new In[N]; 75 | for (int i = 0; i < N; i++) 76 | streams[i] = new In(args[i]); 77 | merge(streams); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/NFA.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdOut; 4 | 5 | /************************************************************************* 6 | * Compilation: javac NFA.java 7 | * Execution: java NFA regexp text 8 | * Dependencies: Stack.java Bag.java Digraph.java DirectedDFS.java 9 | * 10 | * % java NFA "(A*B|AC)D" AAAABD 11 | * true 12 | * 13 | * % java NFA "(A*B|AC)D" AAAAC 14 | * false 15 | * 16 | * % java NFA "(a|(bc)*d)*" abcbcd 17 | * true 18 | * 19 | * % java NFA "(a|(bc)*d)*" abcbcbcdaaaabcbcdaaaddd 20 | * true 21 | * 22 | * Remarks 23 | * ----------- 24 | * - This version does not suport the + operator or multiway-or. 25 | * 26 | * - This version does not handle character classes, 27 | * metacharacters (either in the text or pattern), capturing 28 | * capabilities, greedy vs. relucantant modifier, and 29 | * other features in industrial-strength implementations such 30 | * as java.util.regexp. 31 | * 32 | *************************************************************************/ 33 | 34 | public class NFA { 35 | 36 | private Digraph G; // digraph of epsilon transitions 37 | private String regexp; // regular expression 38 | private int M; // number of characters in regular expression 39 | 40 | // Create the NFA for the given RE 41 | public NFA(String regexp) { 42 | this.regexp = regexp; 43 | M = regexp.length(); 44 | Stack ops = new Stack(); 45 | G = new Digraph(M+1); 46 | for (int i = 0; i < M; i++) { 47 | int lp = i; 48 | if (regexp.charAt(i) == '(' || regexp.charAt(i) == '|') 49 | ops.push(i); 50 | else if (regexp.charAt(i) == ')') { 51 | int or = ops.pop(); 52 | 53 | // 2-way or operator 54 | if (regexp.charAt(or) == '|') { 55 | lp = ops.pop(); 56 | G.addEdge(lp, or+1); 57 | G.addEdge(or, i); 58 | } 59 | else if (regexp.charAt(or) == '(') 60 | lp = or; 61 | else assert false; 62 | } 63 | 64 | // closure operator (uses 1-character lookahead) 65 | if (i < M-1 && regexp.charAt(i+1) == '*') { 66 | G.addEdge(lp, i+1); 67 | G.addEdge(i+1, lp); 68 | } 69 | if (regexp.charAt(i) == '(' || regexp.charAt(i) == '*' || regexp.charAt(i) == ')') 70 | G.addEdge(i, i+1); 71 | } 72 | } 73 | 74 | // Does the NFA recognize txt? 75 | public boolean recognizes(String txt) { 76 | DirectedDFS dfs = new DirectedDFS(G, 0); 77 | Bag pc = new Bag(); 78 | for (int v = 0; v < G.V(); v++) 79 | if (dfs.marked(v)) pc.add(v); 80 | 81 | // Compute possible NFA states for txt[i+1] 82 | for (int i = 0; i < txt.length(); i++) { 83 | Bag match = new Bag(); 84 | for (int v : pc) { 85 | if (v == M) continue; 86 | if ((regexp.charAt(v) == txt.charAt(i)) || regexp.charAt(v) == '.') 87 | match.add(v+1); 88 | } 89 | dfs = new DirectedDFS(G, match); 90 | pc = new Bag(); 91 | for (int v = 0; v < G.V(); v++) 92 | if (dfs.marked(v)) pc.add(v); 93 | 94 | // optimization if no states reachable 95 | if (pc.size() == 0) return false; 96 | } 97 | 98 | // check for accept state 99 | for (int v : pc) 100 | if (v == M) return true; 101 | return false; 102 | } 103 | 104 | 105 | public static void main(String[] args) { 106 | String regexp = "(" + args[0] + ")"; 107 | String txt = args[1]; 108 | if (txt.indexOf('|') >= 0) { 109 | throw new IllegalArgumentException("| character in text is not supported"); 110 | } 111 | NFA nfa = new NFA(regexp); 112 | StdOut.println(nfa.recognizes(txt)); 113 | } 114 | 115 | } 116 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/PictureDump.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | /************************************************************************* 4 | * Compilation: javac PictureDump.java 5 | * Execution: java PictureDump width height < file 6 | * Dependencies: BinaryStdIn.java Picture.java 7 | * Data file: http://introcs.cs.princeton.edu/stdlib/abra.txt 8 | * 9 | * Reads in a binary file and writes out the bits as w-by-h picture, 10 | * with the 1 bits in black and the 0 bits in white. 11 | * 12 | * % more abra.txt 13 | * ABRACADABRA! 14 | * 15 | * % java PictureDump 16 6 < abra.txt 16 | * 17 | *************************************************************************/ 18 | import java.awt.Color; 19 | 20 | import edu.princeton.cs.introcs.BinaryStdIn; 21 | import edu.princeton.cs.introcs.Picture; 22 | import edu.princeton.cs.introcs.StdOut; 23 | 24 | public class PictureDump { 25 | 26 | public static void main(String[] args) { 27 | int width = Integer.parseInt(args[0]); 28 | int height = Integer.parseInt(args[1]); 29 | Picture pic = new Picture(width, height); 30 | int count = 0; 31 | for (int i = 0; i < height; i++) { 32 | for (int j = 0; j < width; j++) { 33 | pic.set(j, i, Color.RED); 34 | if (!BinaryStdIn.isEmpty()) { 35 | count++; 36 | boolean bit = BinaryStdIn.readBoolean(); 37 | if (bit) pic.set(j, i, Color.BLACK); 38 | else pic.set(j, i, Color.WHITE); 39 | } 40 | } 41 | } 42 | pic.show(); 43 | StdOut.println(count + " bits"); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/Quick3string.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdIn; 4 | import edu.princeton.cs.introcs.StdOut; 5 | import edu.princeton.cs.introcs.StdRandom; 6 | 7 | /*********************************************************************************** 8 | * Compilation: javac Quick3string.java 9 | * Execution: java Quick3string < input.txt 10 | * 11 | * Reads string from standard input and 3-way string quicksort them. 12 | * 13 | * % java Quick3string < shell.txt 14 | * are 15 | * by 16 | * sea 17 | * seashells 18 | * seashells 19 | * sells 20 | * sells 21 | * she 22 | * she 23 | * shells 24 | * shore 25 | * surely 26 | * the 27 | * the 28 | * 29 | * 30 | ***********************************************************************************/ 31 | 32 | public class Quick3string { 33 | private static final int CUTOFF = 15; // cutoff to insertion sort 34 | 35 | // sort the array a[] of strings 36 | public static void sort(String[] a) { 37 | StdRandom.shuffle(a); 38 | sort(a, 0, a.length-1, 0); 39 | assert isSorted(a); 40 | } 41 | 42 | // return the dth character of s, -1 if d = length of s 43 | private static int charAt(String s, int d) { 44 | assert d >= 0 && d <= s.length(); 45 | if (d == s.length()) return -1; 46 | return s.charAt(d); 47 | } 48 | 49 | 50 | // 3-way string quicksort a[lo..hi] starting at dth character 51 | private static void sort(String[] a, int lo, int hi, int d) { 52 | 53 | // cutoff to insertion sort for small subarrays 54 | if (hi <= lo + CUTOFF) { 55 | insertion(a, lo, hi, d); 56 | return; 57 | } 58 | 59 | int lt = lo, gt = hi; 60 | int v = charAt(a[lo], d); 61 | int i = lo + 1; 62 | while (i <= gt) { 63 | int t = charAt(a[i], d); 64 | if (t < v) exch(a, lt++, i++); 65 | else if (t > v) exch(a, i, gt--); 66 | else i++; 67 | } 68 | 69 | // a[lo..lt-1] < v = a[lt..gt] < a[gt+1..hi]. 70 | sort(a, lo, lt-1, d); 71 | if (v >= 0) sort(a, lt, gt, d+1); 72 | sort(a, gt+1, hi, d); 73 | } 74 | 75 | // sort from a[lo] to a[hi], starting at the dth character 76 | private static void insertion(String[] a, int lo, int hi, int d) { 77 | for (int i = lo; i <= hi; i++) 78 | for (int j = i; j > lo && less(a[j], a[j-1], d); j--) 79 | exch(a, j, j-1); 80 | } 81 | 82 | // exchange a[i] and a[j] 83 | private static void exch(String[] a, int i, int j) { 84 | String temp = a[i]; 85 | a[i] = a[j]; 86 | a[j] = temp; 87 | } 88 | 89 | // is v less than w, starting at character d 90 | // DEPRECATED BECAUSE OF SLOW SUBSTRING EXTRACTION IN JAVA 7 91 | // private static boolean less(String v, String w, int d) { 92 | // assert v.substring(0, d).equals(w.substring(0, d)); 93 | // return v.substring(d).compareTo(w.substring(d)) < 0; 94 | // } 95 | 96 | // is v less than w, starting at character d 97 | private static boolean less(String v, String w, int d) { 98 | assert v.substring(0, d).equals(w.substring(0, d)); 99 | for (int i = d; i < Math.min(v.length(), w.length()); i++) { 100 | if (v.charAt(i) < w.charAt(i)) return true; 101 | if (v.charAt(i) > w.charAt(i)) return false; 102 | } 103 | return v.length() < w.length(); 104 | } 105 | 106 | // is the array sorted 107 | private static boolean isSorted(String[] a) { 108 | for (int i = 1; i < a.length; i++) 109 | if (a[i].compareTo(a[i-1]) < 0) return false; 110 | return true; 111 | } 112 | 113 | 114 | public static void main(String[] args) { 115 | 116 | // read in the strings from standard input 117 | String[] a = StdIn.readAllStrings(); 118 | int N = a.length; 119 | 120 | // sort the strings 121 | sort(a); 122 | 123 | // print the results 124 | for (int i = 0; i < N; i++) 125 | StdOut.println(a[i]); 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/Quick3way.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdIn; 4 | import edu.princeton.cs.introcs.StdOut; 5 | import edu.princeton.cs.introcs.StdRandom; 6 | 7 | /************************************************************************* 8 | * Compilation: javac Quick3way.java 9 | * Execution: java Quick3way < input.txt 10 | * Dependencies: StdOut.java StdIn.java 11 | * Data files: http://algs4.cs.princeton.edu/23quicksort/tiny.txt 12 | * http://algs4.cs.princeton.edu/23quicksort/words3.txt 13 | * 14 | * Sorts a sequence of strings from standard input using 3-way quicksort. 15 | * 16 | * % more tiny.txt 17 | * S O R T E X A M P L E 18 | * 19 | * % java Quick3way < tiny.txt 20 | * A E E L M O P R S T X [ one string per line ] 21 | * 22 | * % more words3.txt 23 | * bed bug dad yes zoo ... all bad yet 24 | * 25 | * % java Quick3way < words3.txt 26 | * all bad bed bug dad ... yes yet zoo [ one string per line ] 27 | * 28 | *************************************************************************/ 29 | 30 | /** 31 | * The Quick3way class provides static methods for sorting an 32 | * array using quicksort with 3-way partitioning. 33 | *

34 | * For additional documentation, see Section 2.1 of 35 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 36 | * 37 | * @author Robert Sedgewick 38 | * @author Kevin Wayne 39 | */ 40 | public class Quick3way { 41 | 42 | // This class should not be instantiated. 43 | private Quick3way() { } 44 | 45 | /** 46 | * Rearranges the array in ascending order, using the natural order. 47 | * @param a the array to be sorted 48 | */ 49 | public static void sort(Comparable[] a) { 50 | StdRandom.shuffle(a); 51 | sort(a, 0, a.length - 1); 52 | assert isSorted(a); 53 | } 54 | 55 | // quicksort the subarray a[lo .. hi] using 3-way partitioning 56 | private static void sort(Comparable[] a, int lo, int hi) { 57 | if (hi <= lo) return; 58 | int lt = lo, gt = hi; 59 | Comparable v = a[lo]; 60 | int i = lo; 61 | while (i <= gt) { 62 | int cmp = a[i].compareTo(v); 63 | if (cmp < 0) exch(a, lt++, i++); 64 | else if (cmp > 0) exch(a, i, gt--); 65 | else i++; 66 | } 67 | 68 | // a[lo..lt-1] < v = a[lt..gt] < a[gt+1..hi]. 69 | sort(a, lo, lt-1); 70 | sort(a, gt+1, hi); 71 | assert isSorted(a, lo, hi); 72 | } 73 | 74 | 75 | 76 | /*********************************************************************** 77 | * Helper sorting functions 78 | ***********************************************************************/ 79 | 80 | // is v < w ? 81 | private static boolean less(Comparable v, Comparable w) { 82 | return (v.compareTo(w) < 0); 83 | } 84 | 85 | // does v == w ? 86 | private static boolean eq(Comparable v, Comparable w) { 87 | return (v.compareTo(w) == 0); 88 | } 89 | 90 | // exchange a[i] and a[j] 91 | private static void exch(Object[] a, int i, int j) { 92 | Object swap = a[i]; 93 | a[i] = a[j]; 94 | a[j] = swap; 95 | } 96 | 97 | 98 | /*********************************************************************** 99 | * Check if array is sorted - useful for debugging 100 | ***********************************************************************/ 101 | private static boolean isSorted(Comparable[] a) { 102 | return isSorted(a, 0, a.length - 1); 103 | } 104 | 105 | private static boolean isSorted(Comparable[] a, int lo, int hi) { 106 | for (int i = lo + 1; i <= hi; i++) 107 | if (less(a[i], a[i-1])) return false; 108 | return true; 109 | } 110 | 111 | 112 | 113 | // print array to standard output 114 | private static void show(Comparable[] a) { 115 | for (int i = 0; i < a.length; i++) { 116 | StdOut.println(a[i]); 117 | } 118 | } 119 | 120 | /** 121 | * Reads in a sequence of strings from standard input; 3-way 122 | * quicksorts them; and prints them to standard output in ascending order. 123 | */ 124 | public static void main(String[] args) { 125 | String[] a = StdIn.readAllStrings(); 126 | Quick3way.sort(a); 127 | show(a); 128 | } 129 | 130 | } 131 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/QuickFindUF.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdIn; 4 | import edu.princeton.cs.introcs.StdOut; 5 | 6 | /**************************************************************************** 7 | * Compilation: javac QuickFindUF.java 8 | * Execution: java QuickFindUF < input.txt 9 | * Dependencies: StdIn.java StdOut.java 10 | * 11 | * Quick-find algorithm. 12 | * 13 | ****************************************************************************/ 14 | 15 | /** 16 | * The QuickFindUF class represents a union-find data structure. 17 | * It supports the union and find operations, along with 18 | * methods for determinig whether two objects are in the same component 19 | * and the total number of components. 20 | *

21 | * This implementation uses quick find. 22 | * Initializing a data structure with N objects takes linear time. 23 | * Afterwards, find, connected, and count 24 | * takes constant time but union takes linear time. 25 | *

26 | * For additional documentation, see Section 1.5 of 27 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 28 | * 29 | * @author Robert Sedgewick 30 | * @author Kevin Wayne 31 | */ 32 | public class QuickFindUF { 33 | private int[] id; // id[i] = component identifier of i 34 | private int count; // number of components 35 | 36 | /** 37 | * Initializes an empty union-find data structure with N isolated components 0 through N-1. 38 | * @throws java.lang.IllegalArgumentException if N < 0 39 | * @param N the number of objects 40 | */ 41 | public QuickFindUF(int N) { 42 | count = N; 43 | id = new int[N]; 44 | for (int i = 0; i < N; i++) 45 | id[i] = i; 46 | } 47 | 48 | /** 49 | * Returns the number of components. 50 | * @return the number of components (between 1 and N) 51 | */ 52 | public int count() { 53 | return count; 54 | } 55 | 56 | /** 57 | * Returns the component identifier for the component containing site p. 58 | * @param p the integer representing one site 59 | * @return the component identifier for the component containing site p 60 | * @throws java.lang.IndexOutOfBoundsException unless 0 <= p < N 61 | */ 62 | public int find(int p) { 63 | return id[p]; 64 | } 65 | 66 | /** 67 | * Are the two sites p and q/tt> in the same component? 68 | * @param p the integer representing one site 69 | * @param q the integer representing the other site 70 | * @return true if the two sites p and q are in 71 | * the same component, and false otherwise 72 | * @throws java.lang.IndexOutOfBoundsException unless both 0 <= p < N and 0 <= q < N 73 | */ 74 | public boolean connected(int p, int q) { 75 | return id[p] == id[q]; 76 | } 77 | 78 | /** 79 | * Merges the component containing sitep with the component 80 | * containing site q. 81 | * @param p the integer representing one site 82 | * @param q the integer representing the other site 83 | * @throws java.lang.IndexOutOfBoundsException unless both 0 <= p < N and 0 <= q < N 84 | */ 85 | public void union(int p, int q) { 86 | if (connected(p, q)) return; 87 | int pid = id[p]; 88 | for (int i = 0; i < id.length; i++) 89 | if (id[i] == pid) id[i] = id[q]; 90 | count--; 91 | } 92 | 93 | /** 94 | * Reads in a sequence of pairs of integers (between 0 and N-1) from standard input, 95 | * where each integer represents some object; 96 | * if the objects are in different components, merge the two components 97 | * and print the pair to standard output. 98 | */ 99 | public static void main(String[] args) { 100 | int N = StdIn.readInt(); 101 | QuickFindUF uf = new QuickFindUF(N); 102 | while (!StdIn.isEmpty()) { 103 | int p = StdIn.readInt(); 104 | int q = StdIn.readInt(); 105 | if (uf.connected(p, q)) continue; 106 | uf.union(p, q); 107 | StdOut.println(p + " " + q); 108 | } 109 | StdOut.println(uf.count() + " components"); 110 | } 111 | 112 | } 113 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/QuickUnionUF.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdIn; 4 | import edu.princeton.cs.introcs.StdOut; 5 | 6 | /**************************************************************************** 7 | * Compilation: javac QuickUnionUF.java 8 | * Execution: java QuickUnionUF < input.txt 9 | * Dependencies: StdIn.java StdOut.java 10 | * 11 | * Quick-union algorithm. 12 | * 13 | ****************************************************************************/ 14 | 15 | /** 16 | * The QuickUnionUF class represents a union-find data structure. 17 | * It supports the union and find operations, along with 18 | * methods for determinig whether two objects are in the same component 19 | * and the total number of components. 20 | *

21 | * This implementation uses quick union. 22 | * Initializing a data structure with N objects takes linear time. 23 | * Afterwards, union, find, and connected take 24 | * time linear time (in the worst case) and count takes constant 25 | * time. 26 | *

27 | * For additional documentation, see Section 1.5 of 28 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 29 | * 30 | * @author Robert Sedgewick 31 | * @author Kevin Wayne 32 | */ 33 | public class QuickUnionUF { 34 | private int[] id; // id[i] = parent of i 35 | private int count; // number of components 36 | 37 | /** 38 | * Initializes an empty union-find data structure with N isolated components 0 through N-1. 39 | * @throws java.lang.IllegalArgumentException if N < 0 40 | * @param N the number of objects 41 | */ 42 | public QuickUnionUF(int N) { 43 | id = new int[N]; 44 | count = N; 45 | for (int i = 0; i < N; i++) { 46 | id[i] = i; 47 | } 48 | } 49 | 50 | /** 51 | * Returns the number of components. 52 | * @return the number of components (between 1 and N) 53 | */ 54 | public int count() { 55 | return count; 56 | } 57 | 58 | /** 59 | * Returns the component identifier for the component containing site p. 60 | * @param p the integer representing one site 61 | * @return the component identifier for the component containing site p 62 | * @throws java.lang.IndexOutOfBoundsException unless 0 <= p < N 63 | */ 64 | public int find(int p) { 65 | while (p != id[p]) 66 | p = id[p]; 67 | return p; 68 | } 69 | 70 | /** 71 | * Are the two sites p and q in the same component? 72 | * @param p the integer representing one site 73 | * @param q the integer representing the other site 74 | * @return true if the sites p and q are in the same 75 | * component, and false otherwise 76 | * @throws java.lang.IndexOutOfBoundsException unless both 0 <= p < N and 0 <= q < N 77 | */ 78 | public boolean connected(int p, int q) { 79 | return find(p) == find(q); 80 | } 81 | 82 | 83 | /** 84 | * Merges the component containing sitep with the component 85 | * containing site q. 86 | * @param p the integer representing one site 87 | * @param q the integer representing the other site 88 | * @throws java.lang.IndexOutOfBoundsException unless both 0 <= p < N and 0 <= q < N 89 | */ 90 | public void union(int p, int q) { 91 | int rootP = find(p); 92 | int rootQ = find(q); 93 | if (rootP == rootQ) return; 94 | id[rootP] = rootQ; 95 | count--; 96 | } 97 | 98 | /** 99 | * Reads in a sequence of pairs of integers (between 0 and N-1) from standard input, 100 | * where each integer represents some object; 101 | * if the objects are in different components, merge the two components 102 | * and print the pair to standard output. 103 | */ 104 | public static void main(String[] args) { 105 | int N = StdIn.readInt(); 106 | QuickUnionUF uf = new QuickUnionUF(N); 107 | while (!StdIn.isEmpty()) { 108 | int p = StdIn.readInt(); 109 | int q = StdIn.readInt(); 110 | if (uf.connected(p, q)) continue; 111 | uf.union(p, q); 112 | StdOut.println(p + " " + q); 113 | } 114 | StdOut.println(uf.count() + " components"); 115 | } 116 | 117 | 118 | } 119 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/RabinKarp.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | /*************************************************************** 4 | * Compilation: javac RabinKarp.java 5 | * Execution: java RabinKarp pat txt 6 | * 7 | * Reads in two strings, the pattern and the input text, and 8 | * searches for the pattern in the input text using the 9 | * Las Vegas version of the Rabin-Karp algorithm. 10 | * 11 | * % java RabinKarp abracadabra abacadabrabracabracadabrabrabracad 12 | * pattern: abracadabra 13 | * text: abacadabrabracabracadabrabrabracad 14 | * match: abracadabra 15 | * 16 | * % java RabinKarp rab abacadabrabracabracadabrabrabracad 17 | * pattern: rab 18 | * text: abacadabrabracabracadabrabrabracad 19 | * match: rab 20 | * 21 | * % java RabinKarp bcara abacadabrabracabracadabrabrabracad 22 | * pattern: bcara 23 | * text: abacadabrabracabracadabrabrabracad 24 | * 25 | * % java RabinKarp rabrabracad abacadabrabracabracadabrabrabracad 26 | * text: abacadabrabracabracadabrabrabracad 27 | * pattern: rabrabracad 28 | * 29 | * % java RabinKarp abacad abacadabrabracabracadabrabrabracad 30 | * text: abacadabrabracabracadabrabrabracad 31 | * pattern: abacad 32 | * 33 | ***************************************************************/ 34 | 35 | import java.math.BigInteger; 36 | import java.util.Random; 37 | 38 | import edu.princeton.cs.introcs.StdOut; 39 | 40 | public class RabinKarp { 41 | private String pat; // the pattern // needed only for Las Vegas 42 | private long patHash; // pattern hash value 43 | private int M; // pattern length 44 | private long Q; // a large prime, small enough to avoid long overflow 45 | private int R; // radix 46 | private long RM; // R^(M-1) % Q 47 | 48 | public RabinKarp(int R, char[] pattern) { 49 | throw new UnsupportedOperationException("Operation not supported yet"); 50 | } 51 | 52 | public RabinKarp(String pat) { 53 | this.pat = pat; // save pattern (needed only for Las Vegas) 54 | R = 256; 55 | M = pat.length(); 56 | Q = longRandomPrime(); 57 | 58 | // precompute R^(M-1) % Q for use in removing leading digit 59 | RM = 1; 60 | for (int i = 1; i <= M-1; i++) 61 | RM = (R * RM) % Q; 62 | patHash = hash(pat, M); 63 | } 64 | 65 | // Compute hash for key[0..M-1]. 66 | private long hash(String key, int M) { 67 | long h = 0; 68 | for (int j = 0; j < M; j++) 69 | h = (R * h + key.charAt(j)) % Q; 70 | return h; 71 | } 72 | 73 | // Las Vegas version: does pat[] match txt[i..i-M+1] ? 74 | private boolean check(String txt, int i) { 75 | for (int j = 0; j < M; j++) 76 | if (pat.charAt(j) != txt.charAt(i + j)) 77 | return false; 78 | return true; 79 | } 80 | 81 | // Monte Carlo version: always return true 82 | private boolean check(int i) { 83 | return true; 84 | } 85 | 86 | // check for exact match 87 | public int search(String txt) { 88 | int N = txt.length(); 89 | if (N < M) return N; 90 | long txtHash = hash(txt, M); 91 | 92 | // check for match at offset 0 93 | if ((patHash == txtHash) && check(txt, 0)) 94 | return 0; 95 | 96 | // check for hash match; if hash match, check for exact match 97 | for (int i = M; i < N; i++) { 98 | // Remove leading digit, add trailing digit, check for match. 99 | txtHash = (txtHash + Q - RM*txt.charAt(i-M) % Q) % Q; 100 | txtHash = (txtHash*R + txt.charAt(i)) % Q; 101 | 102 | // match 103 | int offset = i - M + 1; 104 | if ((patHash == txtHash) && check(txt, offset)) 105 | return offset; 106 | } 107 | 108 | // no match 109 | return N; 110 | } 111 | 112 | 113 | // a random 31-bit prime 114 | private static long longRandomPrime() { 115 | BigInteger prime = BigInteger.probablePrime(31, new Random()); 116 | return prime.longValue(); 117 | } 118 | 119 | // test client 120 | public static void main(String[] args) { 121 | String pat = args[0]; 122 | String txt = args[1]; 123 | char[] pattern = pat.toCharArray(); 124 | char[] text = txt.toCharArray(); 125 | 126 | RabinKarp searcher = new RabinKarp(pat); 127 | int offset = searcher.search(txt); 128 | 129 | // print results 130 | StdOut.println("text: " + txt); 131 | 132 | // from brute force search method 1 133 | StdOut.print("pattern: "); 134 | for (int i = 0; i < offset; i++) 135 | StdOut.print(" "); 136 | StdOut.println(pat); 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/RandomSeq.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdOut; 4 | import edu.princeton.cs.introcs.StdRandom; 5 | 6 | /************************************************************************* 7 | * Compilation: javac RandomSeq.java 8 | * Execution: java RandomSeq N lo hi 9 | * 10 | * Prints N numbers between lo and hi. 11 | * 12 | * % java RandomSeq 5 100.0 200.0 13 | * 123.43 14 | * 153.13 15 | * 144.38 16 | * 155.18 17 | * 104.02 18 | * 19 | *************************************************************************/ 20 | 21 | /** 22 | * The RandomSeq class is a client that prints out a pseudorandom 23 | * sequence of real numbers in a given range. 24 | *

25 | * For additional documentation, see Section 1.1 of 26 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 27 | * 28 | * @author Robert Sedgewick 29 | * @author Kevin Wayne 30 | */ 31 | public class RandomSeq { 32 | 33 | // this class should not be instantiated 34 | private RandomSeq() { } 35 | 36 | 37 | /** 38 | * Reads in two command-line arguments lo and hi and prints N uniformly 39 | * random real numbers in [lo, hi) to standard output. 40 | */ 41 | public static void main(String[] args) { 42 | 43 | // command-line arguments 44 | int N = Integer.parseInt(args[0]); 45 | 46 | // for backward compatibility with Intro to Programming in Java version of RandomSeq 47 | if (args.length == 1) { 48 | // generate and print N numbers between 0.0 and 1.0 49 | for (int i = 0; i < N; i++) { 50 | double x = StdRandom.uniform(); 51 | StdOut.println(x); 52 | } 53 | } 54 | 55 | else if (args.length == 3) { 56 | double lo = Double.parseDouble(args[1]); 57 | double hi = Double.parseDouble(args[2]); 58 | 59 | // generate and print N numbers between lo and hi 60 | for (int i = 0; i < N; i++) { 61 | double x = StdRandom.uniform(lo, hi); 62 | StdOut.printf("%.2f\n", x); 63 | } 64 | } 65 | 66 | else { 67 | throw new IllegalArgumentException("Invalid number of arguments"); 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/ResizingArrayBag.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | /************************************************************************* 4 | * Compilation: javac ResizingArrayBag.java 5 | * Execution: java ResizingArrayBag 6 | * 7 | * Bag implementation with a resizing array. 8 | * 9 | *************************************************************************/ 10 | 11 | import java.util.Iterator; 12 | import java.util.NoSuchElementException; 13 | 14 | import edu.princeton.cs.introcs.StdOut; 15 | 16 | /** 17 | * The ResizingArrayBag class represents a bag (or multiset) of 18 | * generic items. It supports insertion and iterating over the 19 | * items in arbitrary order. 20 | *

21 | * This implementation uses a resizing array. 22 | * See {@link LinkedBag} for a version that uses a singly-linked list. 23 | * The add operation takes constant amortized time; the 24 | * isEmpty, and size operations 25 | * take constant time. Iteration takes time proportional to the number of items. 26 | *

27 | * For additional documentation, see Section 1.3 of 28 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 29 | * 30 | * @author Robert Sedgewick 31 | * @author Kevin Wayne 32 | */ 33 | public class ResizingArrayBag implements Iterable { 34 | private Item[] a; // array of items 35 | private int N = 0; // number of elements on stack 36 | 37 | /** 38 | * Initializes an empty bag. 39 | */ 40 | public ResizingArrayBag() { 41 | a = (Item[]) new Object[2]; 42 | } 43 | 44 | /** 45 | * Is this bag empty? 46 | * @return true if this bag is empty; false otherwise 47 | */ 48 | public boolean isEmpty() { 49 | return N == 0; 50 | } 51 | 52 | /** 53 | * Returns the number of items in this bag. 54 | * @return the number of items in this bag 55 | */ 56 | public int size() { 57 | return N; 58 | } 59 | 60 | // resize the underlying array holding the elements 61 | private void resize(int capacity) { 62 | assert capacity >= N; 63 | Item[] temp = (Item[]) new Object[capacity]; 64 | for (int i = 0; i < N; i++) 65 | temp[i] = a[i]; 66 | a = temp; 67 | } 68 | 69 | /** 70 | * Adds the item to this bag. 71 | * @param item the item to add to this bag 72 | */ 73 | public void add(Item item) { 74 | if (N == a.length) resize(2*a.length); // double size of array if necessary 75 | a[N++] = item; // add item 76 | } 77 | 78 | 79 | /** 80 | * Returns an iterator that iterates over the items in the bag in arbitrary order. 81 | * @return an iterator that iterates over the items in the bag in arbitrary order 82 | */ 83 | public Iterator iterator() { 84 | return new ArrayIterator(); 85 | } 86 | 87 | // an iterator, doesn't implement remove() since it's optional 88 | private class ArrayIterator implements Iterator { 89 | private int i = 0; 90 | public boolean hasNext() { return i < N; } 91 | public void remove() { throw new UnsupportedOperationException(); } 92 | 93 | public Item next() { 94 | if (!hasNext()) throw new NoSuchElementException(); 95 | return a[i++]; 96 | } 97 | } 98 | 99 | /** 100 | * Unit tests the ResizingArrayBag data type. 101 | */ 102 | public static void main(String[] args) { 103 | ResizingArrayBag bag = new ResizingArrayBag(); 104 | bag.add("Hello"); 105 | bag.add("World"); 106 | bag.add("how"); 107 | bag.add("are"); 108 | bag.add("you"); 109 | 110 | for (String s : bag) 111 | StdOut.println(s); 112 | } 113 | 114 | } 115 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/RunLength.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.BinaryStdIn; 4 | import edu.princeton.cs.introcs.BinaryStdOut; 5 | 6 | /************************************************************************* 7 | * Compilation: javac RunLength.java 8 | * Execution: java RunLength - < input.txt (compress) 9 | * Execution: java RunLength + < input.txt (expand) 10 | * Dependencies: BinaryIn.java BinaryOut.java 11 | * 12 | * Compress or expand binary input from standard input using 13 | * run-length encoding. 14 | * 15 | * % java BinaryDump 40 < 4runs.bin 16 | * 0000000000000001111111000000011111111111 17 | * 40 bits 18 | * 19 | * This has runs of 15 0s, 7 1s, 7 0s, and 11 1s. 20 | * 21 | * % java RunLength - < 4runs.bin | java HexDump 22 | * 0f 07 07 0b 23 | * 4 bytes 24 | * 25 | *************************************************************************/ 26 | 27 | public class RunLength { 28 | private static final int R = 256; 29 | private static final int lgR = 8; 30 | 31 | public static void expand() { 32 | boolean b = false; 33 | while (!BinaryStdIn.isEmpty()) { 34 | int run = BinaryStdIn.readInt(lgR); 35 | for (int i = 0; i < run; i++) 36 | BinaryStdOut.write(b); 37 | b = !b; 38 | } 39 | BinaryStdOut.close(); 40 | } 41 | 42 | public static void compress() { 43 | char run = 0; 44 | boolean old = false; 45 | while (!BinaryStdIn.isEmpty()) { 46 | boolean b = BinaryStdIn.readBoolean(); 47 | if (b != old) { 48 | BinaryStdOut.write(run, lgR); 49 | run = 1; 50 | old = !old; 51 | } 52 | else { 53 | if (run == R-1) { 54 | BinaryStdOut.write(run, lgR); 55 | run = 0; 56 | BinaryStdOut.write(run, lgR); 57 | } 58 | run++; 59 | } 60 | } 61 | BinaryStdOut.write(run, lgR); 62 | BinaryStdOut.close(); 63 | } 64 | 65 | 66 | public static void main(String[] args) { 67 | if (args[0].equals("-")) compress(); 68 | else if (args[0].equals("+")) expand(); 69 | else throw new IllegalArgumentException("Illegal command line argument"); 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/SeparateChainingHashST.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdIn; 4 | import edu.princeton.cs.introcs.StdOut; 5 | 6 | /************************************************************************* 7 | * Compilation: javac SeparateChainingHashST.java 8 | * Execution: java SeparateChainingHashST 9 | * 10 | * A symbol table implemented with a separate-chaining hash table. 11 | * 12 | * % java SeparateChainingHashST 13 | * 14 | *************************************************************************/ 15 | 16 | public class SeparateChainingHashST { 17 | private static final int INIT_CAPACITY = 4; 18 | 19 | // largest prime <= 2^i for i = 3 to 31 20 | // not currently used for doubling and shrinking 21 | // private static final int[] PRIMES = { 22 | // 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 23 | // 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 24 | // 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 25 | // 536870909, 1073741789, 2147483647 26 | // }; 27 | 28 | private int N; // number of key-value pairs 29 | private int M; // hash table size 30 | private SequentialSearchST[] st; // array of linked-list symbol tables 31 | 32 | 33 | // create separate chaining hash table 34 | public SeparateChainingHashST() { 35 | this(INIT_CAPACITY); 36 | } 37 | 38 | // create separate chaining hash table with M lists 39 | public SeparateChainingHashST(int M) { 40 | this.M = M; 41 | st = (SequentialSearchST[]) new SequentialSearchST[M]; 42 | for (int i = 0; i < M; i++) 43 | st[i] = new SequentialSearchST(); 44 | } 45 | 46 | // resize the hash table to have the given number of chains b rehashing all of the keys 47 | private void resize(int chains) { 48 | SeparateChainingHashST temp = new SeparateChainingHashST(chains); 49 | for (int i = 0; i < M; i++) { 50 | for (Key key : st[i].keys()) { 51 | temp.put(key, st[i].get(key)); 52 | } 53 | } 54 | this.M = temp.M; 55 | this.N = temp.N; 56 | this.st = temp.st; 57 | } 58 | 59 | // hash value between 0 and M-1 60 | private int hash(Key key) { 61 | return (key.hashCode() & 0x7fffffff) % M; 62 | } 63 | 64 | // return number of key-value pairs in symbol table 65 | public int size() { 66 | return N; 67 | } 68 | 69 | // is the symbol table empty? 70 | public boolean isEmpty() { 71 | return size() == 0; 72 | } 73 | 74 | // is the key in the symbol table? 75 | public boolean contains(Key key) { 76 | return get(key) != null; 77 | } 78 | 79 | // return value associated with key, null if no such key 80 | public Value get(Key key) { 81 | int i = hash(key); 82 | return st[i].get(key); 83 | } 84 | 85 | // insert key-value pair into the table 86 | public void put(Key key, Value val) { 87 | if (val == null) { delete(key); return; } 88 | 89 | // double table size if average length of list >= 10 90 | if (N >= 10*M) resize(2*M); 91 | 92 | int i = hash(key); 93 | if (!st[i].contains(key)) N++; 94 | st[i].put(key, val); 95 | } 96 | 97 | // delete key (and associated value) if key is in the table 98 | public void delete(Key key) { 99 | int i = hash(key); 100 | if (st[i].contains(key)) N--; 101 | st[i].delete(key); 102 | 103 | // halve table size if average length of list <= 2 104 | if (M > INIT_CAPACITY && N <= 2*M) resize(M/2); 105 | } 106 | 107 | // return keys in symbol table as an Iterable 108 | public Iterable keys() { 109 | Queue queue = new Queue(); 110 | for (int i = 0; i < M; i++) { 111 | for (Key key : st[i].keys()) 112 | queue.enqueue(key); 113 | } 114 | return queue; 115 | } 116 | 117 | 118 | /*********************************************************************** 119 | * Unit test client. 120 | ***********************************************************************/ 121 | public static void main(String[] args) { 122 | SeparateChainingHashST st = new SeparateChainingHashST(); 123 | for (int i = 0; !StdIn.isEmpty(); i++) { 124 | String key = StdIn.readString(); 125 | st.put(key, i); 126 | } 127 | 128 | // print keys 129 | for (String s : st.keys()) 130 | StdOut.println(s + " " + st.get(s)); 131 | 132 | } 133 | 134 | } 135 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/Shell.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdIn; 4 | import edu.princeton.cs.introcs.StdOut; 5 | 6 | /************************************************************************* 7 | * Compilation: javac Shell.java 8 | * Execution: java Shell < input.txt 9 | * Dependencies: StdOut.java StdIn.java 10 | * Data files: http://algs4.cs.princeton.edu/21sort/tiny.txt 11 | * http://algs4.cs.princeton.edu/21sort/words3.txt 12 | * 13 | * Sorts a sequence of strings from standard input using shellsort. 14 | * 15 | * Uses increment sequence proposed by Sedgewick and Incerpi. 16 | * The nth element of the sequence is the smallest integer >= 2.5^n 17 | * that is relatively prime to all previous terms in the sequence. 18 | * For example, incs[4] is 41 because 2.5^4 = 39.0625 and 41 is 19 | * the next integer that is relatively prime to 3, 7, and 16. 20 | * 21 | * % more tiny.txt 22 | * S O R T E X A M P L E 23 | * 24 | * % java Shell < tiny.txt 25 | * A E E L M O P R S T X [ one string per line ] 26 | * 27 | * % more words3.txt 28 | * bed bug dad yes zoo ... all bad yet 29 | * 30 | * % java Shell < words3.txt 31 | * all bad bed bug dad ... yes yet zoo [ one string per line ] 32 | * 33 | * 34 | *************************************************************************/ 35 | 36 | /** 37 | * The Shell class provides static methods for sorting an 38 | * array using Shellsort with Knuth's increment sequence (1, 4, 13, 40, ...). 39 | *

40 | * For additional documentation, see Section 2.1 of 41 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 42 | * 43 | * @author Robert Sedgewick 44 | * @author Kevin Wayne 45 | */ 46 | public class Shell { 47 | 48 | // This class should not be instantiated. 49 | private Shell() { } 50 | 51 | /** 52 | * Rearranges the array in ascending order, using the natural order. 53 | * @param a the array to be sorted 54 | */ 55 | public static void sort(Comparable[] a) { 56 | int N = a.length; 57 | 58 | // 3x+1 increment sequence: 1, 4, 13, 40, 121, 364, 1093, ... 59 | int h = 1; 60 | while (h < N/3) h = 3*h + 1; 61 | 62 | while (h >= 1) { 63 | // h-sort the array 64 | for (int i = h; i < N; i++) { 65 | for (int j = i; j >= h && less(a[j], a[j-h]); j -= h) { 66 | exch(a, j, j-h); 67 | } 68 | } 69 | assert isHsorted(a, h); 70 | h /= 3; 71 | } 72 | assert isSorted(a); 73 | } 74 | 75 | 76 | 77 | /*********************************************************************** 78 | * Helper sorting functions 79 | ***********************************************************************/ 80 | 81 | // is v < w ? 82 | private static boolean less(Comparable v, Comparable w) { 83 | return (v.compareTo(w) < 0); 84 | } 85 | 86 | // exchange a[i] and a[j] 87 | private static void exch(Object[] a, int i, int j) { 88 | Object swap = a[i]; 89 | a[i] = a[j]; 90 | a[j] = swap; 91 | } 92 | 93 | 94 | /*********************************************************************** 95 | * Check if array is sorted - useful for debugging 96 | ***********************************************************************/ 97 | private static boolean isSorted(Comparable[] a) { 98 | for (int i = 1; i < a.length; i++) 99 | if (less(a[i], a[i-1])) return false; 100 | return true; 101 | } 102 | 103 | // is the array h-sorted? 104 | private static boolean isHsorted(Comparable[] a, int h) { 105 | for (int i = h; i < a.length; i++) 106 | if (less(a[i], a[i-h])) return false; 107 | return true; 108 | } 109 | 110 | // print array to standard output 111 | private static void show(Comparable[] a) { 112 | for (int i = 0; i < a.length; i++) { 113 | StdOut.println(a[i]); 114 | } 115 | } 116 | 117 | /** 118 | * Reads in a sequence of strings from standard input; Shellsorts them; 119 | * and prints them to standard output in ascending order. 120 | */ 121 | public static void main(String[] args) { 122 | String[] a = StdIn.readAllStrings(); 123 | Shell.sort(a); 124 | show(a); 125 | } 126 | 127 | } 128 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/SparseVector.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdOut; 4 | 5 | /************************************************************************* 6 | * Compilation: javac SparseVector.java 7 | * Execution: java SparseVector 8 | * 9 | * A sparse vector, implementing using a symbol table. 10 | * 11 | * [Not clear we need the instance variable N except for error checking.] 12 | * 13 | *************************************************************************/ 14 | 15 | public class SparseVector { 16 | private int N; // length 17 | private ST st; // the vector, represented by index-value pairs 18 | 19 | // initialize the all 0s vector of length N 20 | public SparseVector(int N) { 21 | this.N = N; 22 | this.st = new ST(); 23 | } 24 | 25 | // put st[i] = value 26 | public void put(int i, double value) { 27 | if (i < 0 || i >= N) throw new IndexOutOfBoundsException("Illegal index"); 28 | if (value == 0.0) st.delete(i); 29 | else st.put(i, value); 30 | } 31 | 32 | // return st[i] 33 | public double get(int i) { 34 | if (i < 0 || i >= N) throw new IndexOutOfBoundsException("Illegal index"); 35 | if (st.contains(i)) return st.get(i); 36 | else return 0.0; 37 | } 38 | 39 | // return the number of nonzero entries 40 | public int nnz() { 41 | return st.size(); 42 | } 43 | 44 | // return the size of the vector 45 | public int size() { 46 | return N; 47 | } 48 | 49 | // return the dot product of this vector with that vector 50 | public double dot(SparseVector that) { 51 | if (this.N != that.N) throw new IllegalArgumentException("Vector lengths disagree"); 52 | double sum = 0.0; 53 | 54 | // iterate over the vector with the fewest nonzeros 55 | if (this.st.size() <= that.st.size()) { 56 | for (int i : this.st.keys()) 57 | if (that.st.contains(i)) sum += this.get(i) * that.get(i); 58 | } 59 | else { 60 | for (int i : that.st.keys()) 61 | if (this.st.contains(i)) sum += this.get(i) * that.get(i); 62 | } 63 | return sum; 64 | } 65 | 66 | 67 | // return the dot product of this vector and that array 68 | public double dot(double[] that) { 69 | double sum = 0.0; 70 | for (int i : st.keys()) 71 | sum += that[i] * this.get(i); 72 | return sum; 73 | } 74 | 75 | 76 | // return the 2-norm 77 | public double norm() { 78 | SparseVector a = this; 79 | return Math.sqrt(a.dot(a)); 80 | } 81 | 82 | // return alpha * this 83 | public SparseVector scale(double alpha) { 84 | SparseVector c = new SparseVector(N); 85 | for (int i : this.st.keys()) c.put(i, alpha * this.get(i)); 86 | return c; 87 | } 88 | 89 | // return this + that 90 | public SparseVector plus(SparseVector that) { 91 | if (this.N != that.N) throw new IllegalArgumentException("Vector lengths disagree"); 92 | SparseVector c = new SparseVector(N); 93 | for (int i : this.st.keys()) c.put(i, this.get(i)); // c = this 94 | for (int i : that.st.keys()) c.put(i, that.get(i) + c.get(i)); // c = c + that 95 | return c; 96 | } 97 | 98 | // return a string representation 99 | @Override 100 | public String toString() { 101 | String s = ""; 102 | for (int i : st.keys()) { 103 | s += "(" + i + ", " + st.get(i) + ") "; 104 | } 105 | return s; 106 | } 107 | 108 | 109 | // test client 110 | public static void main(String[] args) { 111 | SparseVector a = new SparseVector(10); 112 | SparseVector b = new SparseVector(10); 113 | a.put(3, 0.50); 114 | a.put(9, 0.75); 115 | a.put(6, 0.11); 116 | a.put(6, 0.00); 117 | b.put(3, 0.60); 118 | b.put(4, 0.90); 119 | StdOut.println("a = " + a); 120 | StdOut.println("b = " + b); 121 | StdOut.println("a dot b = " + a.dot(b)); 122 | StdOut.println("a + b = " + a.plus(b)); 123 | } 124 | 125 | } 126 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/StaticSETofInts.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | /************************************************************************* 4 | * Compilation: javac StaticSetOfInts.java 5 | * 6 | * Data type to store a set of integers. 7 | * 8 | *************************************************************************/ 9 | 10 | import java.util.Arrays; 11 | 12 | /** 13 | * The StaticSETofInts class represents a set of integers. 14 | * It supports searching for a given integer is in the set. It accomplishes 15 | * this by keeping the set of integers in a sorted array and using 16 | * binary search to find the given integer. 17 | *

18 | * The rank and contains operations take 19 | * logarithmic time in the worst case. 20 | *

21 | * For additional documentation, see Section 1.2 of 22 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 23 | * 24 | * @author Robert Sedgewick 25 | * @author Kevin Wayne 26 | */ 27 | public class StaticSETofInts { 28 | private int[] a; 29 | 30 | /** 31 | * Initializes a set of integers specified by the integer array. 32 | * @param keys the array of integers 33 | * @throws IllegalArgumentException if the array contains duplicate integers 34 | */ 35 | public StaticSETofInts(int[] keys) { 36 | 37 | // defensive copy 38 | a = new int[keys.length]; 39 | for (int i = 0; i < keys.length; i++) 40 | a[i] = keys[i]; 41 | 42 | // sort the integers 43 | Arrays.sort(a); 44 | 45 | // check for duplicates 46 | for (int i = 1; i < a.length; i++) 47 | if (a[i] == a[i-1]) 48 | throw new IllegalArgumentException("Argument arrays contains duplicate keys."); 49 | } 50 | 51 | /** 52 | * Is the key in this set of integers? 53 | * @param key the search key 54 | * @return true if the set of integers contains the key; false otherwise 55 | */ 56 | public boolean contains(int key) { 57 | return rank(key) != -1; 58 | } 59 | 60 | /** 61 | * Returns either the index of the search key in the sorted array 62 | * (if the key is in the set) or -1 (if the key is not in the set). 63 | * @param key the search key 64 | * @return the number of keys in this set less than the key (if the key is in the set) 65 | * or -1 (if the key is not in the set). 66 | */ 67 | public int rank(int key) { 68 | int lo = 0; 69 | int hi = a.length - 1; 70 | while (lo <= hi) { 71 | // Key is in a[lo..hi] or not present. 72 | int mid = lo + (hi - lo) / 2; 73 | if (key < a[mid]) hi = mid - 1; 74 | else if (key > a[mid]) lo = mid + 1; 75 | else return mid; 76 | } 77 | return -1; 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/Stopwatch.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | /************************************************************************* 4 | * Compilation: javac Stopwatch.java 5 | * 6 | * 7 | *************************************************************************/ 8 | 9 | /** 10 | * The Stopwatch data type is for measuring 11 | * the time that elapses between the start and end of a 12 | * programming task (wall-clock time). 13 | * 14 | * See {@link StopwatchCPU} for a version that measures CPU time. 15 | * 16 | * @author Robert Sedgewick 17 | * @author Kevin Wayne 18 | */ 19 | 20 | 21 | public class Stopwatch { 22 | 23 | private final long start; 24 | 25 | /** 26 | * Initialize a stopwatch object. 27 | */ 28 | public Stopwatch() { 29 | start = System.currentTimeMillis(); 30 | } 31 | 32 | 33 | /** 34 | * Returns the elapsed time (in seconds) since this object was created. 35 | */ 36 | public double elapsedTime() { 37 | long now = System.currentTimeMillis(); 38 | return (now - start) / 1000.0; 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/StopwatchCPU.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | /************************************************************************* 4 | * Compilation: javac Stopwatch.java 5 | * 6 | * 7 | *************************************************************************/ 8 | 9 | import java.lang.management.ThreadMXBean; 10 | import java.lang.management.ManagementFactory; 11 | 12 | /** 13 | * The StopwatchCPU data type is for measuring 14 | * the CPU time used during a programming task. 15 | * 16 | * See {@link Stopwatch} for a version that measures wall-clock time 17 | * (the real time that elapses). 18 | * 19 | * @author Josh Hug 20 | * @author Robert Sedgewick 21 | * @author Kevin Wayne 22 | */ 23 | 24 | public class StopwatchCPU { 25 | private final ThreadMXBean threadTimer; 26 | private final long start; 27 | private static final double NANOSECONDS_PER_SECOND = 1000000000; 28 | 29 | /** 30 | * Initialize a stopwatch object. 31 | */ 32 | public StopwatchCPU() { 33 | threadTimer = ManagementFactory.getThreadMXBean(); 34 | start = threadTimer.getCurrentThreadCpuTime(); 35 | } 36 | 37 | /** 38 | * Returns the elapsed CPU time (in seconds) since the object was created. 39 | */ 40 | public double elapsedTime() { 41 | long now = threadTimer.getCurrentThreadCpuTime(); 42 | return (now - start) / NANOSECONDS_PER_SECOND; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/ThreeSum.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.In; 4 | import edu.princeton.cs.introcs.StdOut; 5 | 6 | /************************************************************************* 7 | * Compilation: javac ThreeSum.java 8 | * Execution: java ThreeSum input.txt 9 | * Dependencies: In.java StdOut.java Stopwatch.java 10 | * Data files: http://algs4.cs.princeton.edu/14analysis/1Kints.txt 11 | * http://algs4.cs.princeton.edu/14analysis/2Kints.txt 12 | * http://algs4.cs.princeton.edu/14analysis/4Kints.txt 13 | * http://algs4.cs.princeton.edu/14analysis/8Kints.txt 14 | * http://algs4.cs.princeton.edu/14analysis/16Kints.txt 15 | * http://algs4.cs.princeton.edu/14analysis/32Kints.txt 16 | * http://algs4.cs.princeton.edu/14analysis/1Mints.txt 17 | * 18 | * A program with cubic running time. Read in N integers 19 | * and counts the number of triples that sum to exactly 0 20 | * (ignoring integer overflow). 21 | * 22 | * % java ThreeSum 1Kints.txt 23 | * 70 24 | * 25 | * % java ThreeSum 2Kints.txt 26 | * 528 27 | * 28 | * % java ThreeSum 4Kints.txt 29 | * 4039 30 | * 31 | *************************************************************************/ 32 | 33 | /** 34 | * The ThreeSum class provides static methods for counting 35 | * and printing the number of triples in an array of integers that sum to 0 36 | * (ignoring integer overflow). 37 | *

38 | * This implementation uses a triply nested loop and takes proportional to N^3, 39 | * where N is the number of integers. 40 | *

41 | * For additional documentation, see Section 1.4 of 42 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 43 | * 44 | * @author Robert Sedgewick 45 | * @author Kevin Wayne 46 | */ 47 | public class ThreeSum { 48 | 49 | /** 50 | * Prints to standard output the (i, j, k) with i < j < k such that a[i] + a[j] + a[k] == 0. 51 | * @param a the array of integers 52 | */ 53 | public static void printAll(int[] a) { 54 | int N = a.length; 55 | for (int i = 0; i < N; i++) { 56 | for (int j = i+1; j < N; j++) { 57 | for (int k = j+1; k < N; k++) { 58 | if (a[i] + a[j] + a[k] == 0) { 59 | StdOut.println(a[i] + " " + a[j] + " " + a[k]); 60 | } 61 | } 62 | } 63 | } 64 | } 65 | 66 | /** 67 | * Returns the number of triples (i, j, k) with i < j < k such that a[i] + a[j] + a[k] == 0. 68 | * @param a the array of integers 69 | * @return the number of triples (i, j, k) with i < j < k such that a[i] + a[j] + a[k] == 0 70 | */ 71 | public static int count(int[] a) { 72 | int N = a.length; 73 | int cnt = 0; 74 | for (int i = 0; i < N; i++) { 75 | for (int j = i+1; j < N; j++) { 76 | for (int k = j+1; k < N; k++) { 77 | if (a[i] + a[j] + a[k] == 0) { 78 | cnt++; 79 | } 80 | } 81 | } 82 | } 83 | return cnt; 84 | } 85 | 86 | /** 87 | * Reads in a sequence of integers from a file, specified as a command-line argument; 88 | * counts the number of triples sum to exactly zero; prints out the time to perform 89 | * the computation. 90 | */ 91 | public static void main(String[] args) { 92 | In in = new In(args[0]); 93 | int[] a = in.readAllInts(); 94 | 95 | Stopwatch timer = new Stopwatch(); 96 | int cnt = count(a); 97 | StdOut.println("elapsed time = " + timer.elapsedTime()); 98 | StdOut.println(cnt); 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/ThreeSumFast.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | /************************************************************************* 4 | * Compilation: javac ThreeSumFast.java 5 | * Execution: java ThreeSumFast input.txt 6 | * Dependencies: StdOut.java In.java Stopwatch.java 7 | * Data files: http://algs4.cs.princeton.edu/14analysis/1Kints.txt 8 | * http://algs4.cs.princeton.edu/14analysis/2Kints.txt 9 | * http://algs4.cs.princeton.edu/14analysis/4Kints.txt 10 | * http://algs4.cs.princeton.edu/14analysis/8Kints.txt 11 | * http://algs4.cs.princeton.edu/14analysis/16Kints.txt 12 | * http://algs4.cs.princeton.edu/14analysis/32Kints.txt 13 | * http://algs4.cs.princeton.edu/14analysis/1Mints.txt 14 | * 15 | * A program with N^2 log N running time. Read in N integers 16 | * and counts the number of triples that sum to exactly 0. 17 | * 18 | * Limitations 19 | * ----------- 20 | * - we ignore integer overflow 21 | * - doesn't handle case when input has duplicates 22 | * 23 | * 24 | * % java ThreeSumFast 1Kints.txt 25 | * 70 26 | * 27 | * % java ThreeSumFast 2Kints.txt 28 | * 528 29 | * 30 | * % java ThreeSumFast 4Kints.txt 31 | * 4039 32 | * 33 | * % java ThreeSumFast 8Kints.txt 34 | * 32074 35 | * 36 | * % java ThreeSumFast 16Kints.txt 37 | * 255181 38 | * 39 | * % java ThreeSumFast 32Kints.txt 40 | * 2052358 41 | * 42 | *************************************************************************/ 43 | 44 | import java.util.Arrays; 45 | 46 | import edu.princeton.cs.introcs.In; 47 | import edu.princeton.cs.introcs.StdOut; 48 | 49 | /** 50 | * The ThreeSumFast class provides static methods for counting 51 | * and printing the number of triples in an array of distinct integers that 52 | * sum to 0 (ignoring integer overflow). 53 | *

54 | * This implementation uses sorting and binary search and takes time 55 | * proportional to N^2 log N, where N is the number of integers. 56 | *

57 | * For additional documentation, see Section 1.4 of 58 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 59 | * 60 | * @author Robert Sedgewick 61 | * @author Kevin Wayne 62 | */ 63 | public class ThreeSumFast { 64 | 65 | // returns true if the sorted array a[] contains any duplicated integers 66 | private static boolean containsDuplicates(int[] a) { 67 | for (int i = 1; i < a.length; i++) 68 | if (a[i] == a[i-1]) return true; 69 | return false; 70 | } 71 | 72 | /** 73 | * Prints to standard output the (i, j, k) with i < j < k such that a[i] + a[j] + a[k] == 0. 74 | * @param a the array of integers 75 | * @throws IllegalArgumentException if the array contains duplicate integers 76 | */ 77 | public static void printAll(int[] a) { 78 | int N = a.length; 79 | Arrays.sort(a); 80 | if (containsDuplicates(a)) throw new IllegalArgumentException("array contains duplicate integers"); 81 | for (int i = 0; i < N; i++) { 82 | for (int j = i+1; j < N; j++) { 83 | int k = Arrays.binarySearch(a, -(a[i] + a[j])); 84 | if (k > j) StdOut.println(a[i] + " " + a[j] + " " + a[k]); 85 | } 86 | } 87 | } 88 | 89 | /** 90 | * Returns the number of triples (i, j, k) with i < j < k such that a[i] + a[j] + a[k] == 0. 91 | * @param a the array of integers 92 | * @return the number of triples (i, j, k) with i < j < k such that a[i] + a[j] + a[k] == 0 93 | */ 94 | public static int count(int[] a) { 95 | int N = a.length; 96 | Arrays.sort(a); 97 | if (containsDuplicates(a)) throw new IllegalArgumentException("array contains duplicate integers"); 98 | int cnt = 0; 99 | for (int i = 0; i < N; i++) { 100 | for (int j = i+1; j < N; j++) { 101 | int k = Arrays.binarySearch(a, -(a[i] + a[j])); 102 | if (k > j) cnt++; 103 | } 104 | } 105 | return cnt; 106 | } 107 | 108 | /** 109 | * Reads in a sequence of distinct integers from a file, specified as a command-line argument; 110 | * counts the number of triples sum to exactly zero; prints out the time to perform 111 | * the computation. 112 | */ 113 | public static void main(String[] args) { 114 | In in = new In(args[0]); 115 | int[] a = in.readAllInts(); 116 | int cnt = count(a); 117 | StdOut.println(cnt); 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/TopM.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdIn; 4 | import edu.princeton.cs.introcs.StdOut; 5 | 6 | /************************************************************************* 7 | * Compilation: javac TopM.java 8 | * Execution: java TopM M < input.txt 9 | * Dependencies: MinPQ.java Transaction.java StdIn.java StdOut.java 10 | * Data files: http://algs4.cs.princeton.edu/24pq/tinyBatch.txt 11 | * 12 | * Given an integer M from the command line and an input stream where 13 | * each line contains a String and a long value, this MinPQ client 14 | * prints the M lines whose numbers are the highest. 15 | * 16 | * % java TopM 5 < tinyBatch.txt 17 | * Thompson 2/27/2000 4747.08 18 | * vonNeumann 2/12/1994 4732.35 19 | * vonNeumann 1/11/1999 4409.74 20 | * Hoare 8/18/1992 4381.21 21 | * vonNeumann 3/26/2002 4121.85 22 | * 23 | *************************************************************************/ 24 | 25 | /** 26 | * The TopM class provides a client that reads a sequence of 27 | * transactions from standard input and prints the M largest ones 28 | * to standard output. This implementation uses a {@link MinPQ} of size 29 | * at most M + 1 to identify the M largest transactions 30 | * and a {@link Stack} to output them in the proper order. 31 | *

32 | * For additional documentation, see Section 2.4 33 | * of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 34 | * 35 | * @author Robert Sedgewick 36 | * @author Kevin Wayne 37 | */ 38 | public class TopM { 39 | 40 | // This class should not be instantiated. 41 | private TopM() { } 42 | 43 | /** 44 | * Reads a sequence of transactions from standard input; takes a 45 | * command-line integer M; prints to standard output the M largest 46 | * transactions in descending order. 47 | */ 48 | public static void main(String[] args) { 49 | int M = Integer.parseInt(args[0]); 50 | MinPQ pq = new MinPQ(M+1); 51 | 52 | while (StdIn.hasNextLine()) { 53 | // Create an entry from the next line and put on the PQ. 54 | String line = StdIn.readLine(); 55 | Transaction transaction = new Transaction(line); 56 | pq.insert(transaction); 57 | 58 | // remove minimum if M+1 entries on the PQ 59 | if (pq.size() > M) 60 | pq.delMin(); 61 | } // top M entries are on the PQ 62 | 63 | // print entries on PQ in reverse order 64 | Stack stack = new Stack(); 65 | for (Transaction transaction : pq) 66 | stack.push(transaction); 67 | for (Transaction transaction : stack) 68 | StdOut.println(transaction); 69 | } 70 | } 71 | 72 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/Topological.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.StdOut; 4 | 5 | /************************************************************************* 6 | * Compilation: javac Topoological.java 7 | * Dependencies: Digraph.java DepthFirstOrder.java DirectedCycle.java 8 | * EdgeWeightedDigraph.java EdgeWeightedDirectedCycle.java 9 | * SymbolDigraph.java 10 | * Data files: http://algs4.cs.princeton.edu/42directed/jobs.txt 11 | * 12 | * Compute topological ordering of a DAG or edge-weighted DAG. 13 | * Runs in O(E + V) time. 14 | * 15 | * % java Topological jobs.txt "/" 16 | * Calculus 17 | * Linear Algebra 18 | * Introduction to CS 19 | * Programming Systems 20 | * Algorithms 21 | * Theoretical CS 22 | * Artificial Intelligence 23 | * Machine Learning 24 | * Neural Networks 25 | * Robotics 26 | * Scientific Computing 27 | * Computational Biology 28 | * Databases 29 | * 30 | * 31 | *************************************************************************/ 32 | 33 | /** 34 | * The Topological class represents a data type for 35 | * determining a topological order of a directed acyclic graph (DAG). 36 | * Recall, a digraph has a topological order if and only if it is a DAG. 37 | * The hasOrder operation determines whether the digraph has 38 | * a topological order, and if so, the order operation 39 | * returns one. 40 | *

41 | * This implementation uses depth-first search. 42 | * The constructor takes time proportional to V + E 43 | * (in the worst case), 44 | * where V is the number of vertices and E is the number of edges. 45 | * Afterwards, the hasOrder operation takes constant time; 46 | * the order operation takes time proportional to V. 47 | *

48 | * See {@link DirectedCycle} and {@link EdgeWeightedDirectedCycle} to compute a 49 | * directed cycle if the digraph is not a DAG. 50 | *

51 | * For additional documentation, see Section 4.2 of 52 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 53 | * 54 | * @author Robert Sedgewick 55 | * @author Kevin Wayne 56 | */ 57 | public class Topological { 58 | private Iterable order; // topological order 59 | 60 | /** 61 | * Determines whether the digraph G has a topological order and, if so, 62 | * finds such a topological order. 63 | * @param G the digraph 64 | */ 65 | public Topological(Digraph G) { 66 | DirectedCycle finder = new DirectedCycle(G); 67 | if (!finder.hasCycle()) { 68 | DepthFirstOrder dfs = new DepthFirstOrder(G); 69 | order = dfs.reversePost(); 70 | } 71 | } 72 | 73 | /** 74 | * Determines whether the edge-weighted digraph G has a topological 75 | * order and, if so, finds such an order. 76 | * @param G the edge-weighted digraph 77 | */ 78 | public Topological(EdgeWeightedDigraph G) { 79 | EdgeWeightedDirectedCycle finder = new EdgeWeightedDirectedCycle(G); 80 | if (!finder.hasCycle()) { 81 | DepthFirstOrder dfs = new DepthFirstOrder(G); 82 | order = dfs.reversePost(); 83 | } 84 | } 85 | 86 | /** 87 | * Returns a topological order if the digraph has a topologial order, 88 | * and null otherwise. 89 | * @return a topological order of the vertices (as an interable) if the 90 | * digraph has a topological order (or equivalently, if the digraph is a DAG), 91 | * and null otherwise 92 | */ 93 | public Iterable order() { 94 | return order; 95 | } 96 | 97 | /** 98 | * Does the digraph have a topological order? 99 | * @return true if the digraph has a topological order (or equivalently, 100 | * if the digraph is a DAG), and false otherwise 101 | */ 102 | public boolean hasOrder() { 103 | return order != null; 104 | } 105 | 106 | /** 107 | * Unit tests the Topological data type. 108 | */ 109 | public static void main(String[] args) { 110 | String filename = args[0]; 111 | String delimiter = args[1]; 112 | SymbolDigraph sg = new SymbolDigraph(filename, delimiter); 113 | Topological topological = new Topological(sg.G()); 114 | for (int v : topological.order()) { 115 | StdOut.println(sg.name(v)); 116 | } 117 | } 118 | 119 | } 120 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/TransitiveClosure.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.In; 4 | import edu.princeton.cs.introcs.StdOut; 5 | 6 | /************************************************************************* 7 | * Compilation: javac TransitiveClosure.java 8 | * Execution: java TransitiveClosure filename.txt 9 | * Dependencies: Digraph.java DepthFirstDirectedPaths.java In.java StdOut.java 10 | * Data files: http://algs4.cs.princeton.edu/42directed/tinyDG.txt 11 | * 12 | * Compute transitive closure of a digraph and support 13 | * reachability queries. 14 | * 15 | * Preprocessing time: O(V(E + V)) time. 16 | * Query time: O(1). 17 | * Space: O(V^2). 18 | * 19 | * % java TransitiveClosure tinyDG.txt 20 | * 0 1 2 3 4 5 6 7 8 9 10 11 12 21 | * -------------------------------------------- 22 | * 0: T T T T T T 23 | * 1: T 24 | * 2: T T T T T T 25 | * 3: T T T T T T 26 | * 4: T T T T T T 27 | * 5: T T T T T T 28 | * 6: T T T T T T T T T T T 29 | * 7: T T T T T T T T T T T T T 30 | * 8: T T T T T T T T T T T T T 31 | * 9: T T T T T T T T T T 32 | * 10: T T T T T T T T T T 33 | * 11: T T T T T T T T T T 34 | * 12: T T T T T T T T T T 35 | * 36 | *************************************************************************/ 37 | 38 | /** 39 | * The TransitiveClosure class represents a data type for 40 | * computing the transitive closure of a digraph. 41 | *

42 | * This implementation runs depth-first search from each vertex. 43 | * The constructor takes time proportional to V(V + E) 44 | * (in the worst case) and uses space proportional to V2, 45 | * where V is the number of vertices and E is the number of edges. 46 | *

47 | * For additional documentation, see Section 4.2 of 48 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 49 | * 50 | * @author Robert Sedgewick 51 | * @author Kevin Wayne 52 | */ 53 | public class TransitiveClosure { 54 | private DirectedDFS[] tc; // tc[v] = reachable from v 55 | 56 | /** 57 | * Computes the transitive closure of the digraph G. 58 | * @param G the digraph 59 | */ 60 | public TransitiveClosure(Digraph G) { 61 | tc = new DirectedDFS[G.V()]; 62 | for (int v = 0; v < G.V(); v++) 63 | tc[v] = new DirectedDFS(G, v); 64 | } 65 | 66 | /** 67 | * Is there a directed path from vertex v to vertex w in the digraph? 68 | * @param v the source vertex 69 | * @param w the target vertex 70 | * @return true if there is a directed path from v to w, 71 | * false otherwise 72 | */ 73 | public boolean reachable(int v, int w) { 74 | return tc[v].marked(w); 75 | } 76 | 77 | /** 78 | * Unit tests the TransitiveClosure data type. 79 | */ 80 | public static void main(String[] args) { 81 | In in = new In(args[0]); 82 | Digraph G = new Digraph(in); 83 | 84 | TransitiveClosure tc = new TransitiveClosure(G); 85 | 86 | // print header 87 | StdOut.print(" "); 88 | for (int v = 0; v < G.V(); v++) 89 | StdOut.printf("%3d", v); 90 | StdOut.println(); 91 | StdOut.println("--------------------------------------------"); 92 | 93 | // print transitive closure 94 | for (int v = 0; v < G.V(); v++) { 95 | StdOut.printf("%3d: ", v); 96 | for (int w = 0; w < G.V(); w++) { 97 | if (tc.reachable(v, w)) StdOut.printf(" T"); 98 | else StdOut.printf(" "); 99 | } 100 | StdOut.println(); 101 | } 102 | } 103 | 104 | } 105 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/WhiteFilter.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.In; 4 | import edu.princeton.cs.introcs.StdIn; 5 | import edu.princeton.cs.introcs.StdOut; 6 | 7 | /************************************************************************* 8 | * Compilation: javac WhiteFilter.java 9 | * Execution: java WhiteFilter whitelist.txt < input.txt 10 | * Dependencies: SET In.java StdIn.java StdOut.java 11 | * Data files: http://algs4.cs.princeton.edu/35applications/tinyTale.txt 12 | * http://algs4.cs.princeton.edu/35applications/list.txt 13 | * 14 | * Read in a whitelist of words from a file. Then read in a list of 15 | * words from standard input and print out all those words that 16 | * are in the first file. 17 | * 18 | * % more tinyTale.txt 19 | * it was the best of times it was the worst of times 20 | * it was the age of wisdom it was the age of foolishness 21 | * it was the epoch of belief it was the epoch of incredulity 22 | * it was the season of light it was the season of darkness 23 | * it was the spring of hope it was the winter of despair 24 | * 25 | * % more list.txt 26 | * was it the of 27 | * 28 | * % java WhiteFilter list.txt < tinyTale.txt 29 | * it was the of it was the of 30 | * it was the of it was the of 31 | * it was the of it was the of 32 | * it was the of it was the of 33 | * it was the of it was the of 34 | * 35 | *************************************************************************/ 36 | 37 | public class WhiteFilter { 38 | public static void main(String[] args) { 39 | SET set = new SET(); 40 | 41 | // read in strings and add to set 42 | In in = new In(args[0]); 43 | while (!in.isEmpty()) { 44 | String word = in.readString(); 45 | set.add(word); 46 | } 47 | 48 | // read in string from standard input, printing out all exceptions 49 | while (!StdIn.isEmpty()) { 50 | String word = StdIn.readString(); 51 | if (set.contains(word)) 52 | StdOut.println(word); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algorithms/Whitelist.java: -------------------------------------------------------------------------------- 1 | package edu.princeton.cs.algorithms; 2 | 3 | import edu.princeton.cs.introcs.In; 4 | import edu.princeton.cs.introcs.StdIn; 5 | import edu.princeton.cs.introcs.StdOut; 6 | 7 | /************************************************************************* 8 | * Compilation: javac Whitelist.java 9 | * Execution: java Whitelist whitelist.txt < data.txt 10 | * Dependencies: StaticSetOfInts.java In.java StdOut.java 11 | * 12 | * Data files: http://algs4.cs.princeton.edu/11model/tinyW.txt 13 | * http://algs4.cs.princeton.edu/11model/tinyT.txt 14 | * http://algs4.cs.princeton.edu/11model/largeW.txt 15 | * http://algs4.cs.princeton.edu/11model/largeT.txt 16 | * 17 | * Whitelist filter. 18 | * 19 | * 20 | * % java Whitelist tinyW.txt < tinyT.txt 21 | * 50 22 | * 99 23 | * 13 24 | * 25 | * % java Whitelist largeW.txt < largeT.txt | more 26 | * 499569 27 | * 984875 28 | * 295754 29 | * 207807 30 | * 140925 31 | * 161828 32 | * [367,966 total values] 33 | * 34 | *************************************************************************/ 35 | 36 | /** 37 | * The Whitelist class provides a client for reading in 38 | * a set of integers from a file; reading in a sequence of integers 39 | * from standard input; and printing to standard output those 40 | * integers not in the whitelist. 41 | *

42 | * For additional documentation, see Section 1.2 of 43 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 44 | * 45 | * @author Robert Sedgewick 46 | * @author Kevin Wayne 47 | */ 48 | public class Whitelist { 49 | 50 | /** 51 | * Reads in a sequence of integers from the whitelist file, specified as 52 | * a command-line argument. Reads in integers from standard input and 53 | * prints to standard output those integers that are not in the file. 54 | */ 55 | public static void main(String[] args) { 56 | In in = new In(args[0]); 57 | int[] white = in.readAllInts(); 58 | StaticSETofInts set = new StaticSETofInts(white); 59 | 60 | // Read key, print if not in whitelist. 61 | while (!StdIn.isEmpty()) { 62 | int key = StdIn.readInt(); 63 | if (!set.contains(key)) 64 | StdOut.println(key); 65 | } 66 | } 67 | } 68 | --------------------------------------------------------------------------------