├── .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 |
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 | *
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
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
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
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
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
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 ≤ s ≤ V - 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
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
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
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
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
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
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
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
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
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
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
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
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
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 |
--------------------------------------------------------------------------------
Interval2D
includes methods for checking whether
22 | * a two-dimensional interval contains a point and determining whether
23 | * two two-dimensional intervals intersect.
24 | *