2351b382 by Branden

Initial Commit

1 parent 11b71c47
Showing 222 changed files with 4894 additions and 0 deletions
1 <?xml version="1.0" encoding="UTF-8"?>
2 <classpath>
3 <classpathentry kind="src" path="src"/>
4 <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
5 <classpathentry kind="output" path="bin"/>
6 </classpath>
1 <?xml version="1.0" encoding="UTF-8"?>
2 <projectDescription>
3 <name>Kd-Trees</name>
4 <comment></comment>
5 <projects>
6 </projects>
7 <buildSpec>
8 <buildCommand>
9 <name>org.eclipse.jdt.core.javabuilder</name>
10 <arguments>
11 </arguments>
12 </buildCommand>
13 </buildSpec>
14 <natures>
15 <nature>org.eclipse.jdt.core.javanature</nature>
16 </natures>
17 </projectDescription>
1 0.206107 0.095492
2 0.975528 0.654508
3 0.024472 0.345492
4 0.793893 0.095492
5 0.793893 0.904508
6 0.975528 0.345492
7 0.206107 0.904508
8 0.500000 0.000000
9 0.024472 0.654508
10 0.500000 1.000000
1 0.740877 0.938153
2 0.181288 0.114743
3 0.157726 0.864484
4 0.684062 0.035112
5 0.975528 0.345492
6 0.684062 0.964888
7 0.938153 0.259123
8 0.315938 0.964888
9 0.793893 0.904508
10 0.938153 0.740877
11 0.047586 0.287110
12 0.952414 0.712890
13 0.114743 0.818712
14 0.922164 0.767913
15 0.008856 0.406309
16 0.999013 0.531395
17 0.008856 0.593691
18 0.624345 0.984292
19 0.345492 0.975528
20 0.206107 0.904508
21 0.000000 0.500000
22 0.500000 0.000000
23 0.181288 0.885257
24 0.562667 0.003943
25 0.654508 0.975528
26 0.003943 0.437333
27 0.468605 0.999013
28 0.061847 0.740877
29 0.468605 0.000987
30 0.922164 0.232087
31 0.818712 0.885257
32 0.712890 0.952414
33 0.593691 0.008856
34 0.015708 0.624345
35 0.406309 0.991144
36 0.035112 0.315938
37 0.740877 0.061847
38 0.000987 0.468605
39 0.095492 0.206107
40 0.885257 0.181288
41 0.767913 0.077836
42 0.003943 0.562667
43 0.984292 0.375655
44 0.035112 0.684062
45 0.259123 0.061847
46 0.232087 0.922164
47 0.996057 0.562667
48 0.077836 0.232087
49 0.593691 0.991144
50 0.375655 0.015708
51 0.000987 0.531395
52 0.375655 0.984292
53 0.077836 0.767913
54 0.114743 0.181288
55 0.904508 0.206107
56 0.024472 0.654508
57 0.206107 0.095492
58 0.562667 0.996057
59 0.287110 0.952414
60 0.406309 0.008856
61 0.315938 0.035112
62 0.975528 0.654508
63 0.991144 0.593691
64 0.437333 0.003943
65 0.842274 0.864484
66 0.345492 0.024472
67 0.287110 0.047586
68 0.232087 0.077836
69 0.624345 0.015708
70 0.904508 0.793893
71 0.015708 0.375655
72 0.964888 0.684062
73 0.999013 0.468605
74 0.500000 1.000000
75 0.135516 0.842274
76 0.095492 0.793893
77 0.991144 0.406309
78 0.654508 0.024472
79 0.767913 0.922164
80 0.984292 0.624345
81 0.531395 0.999013
82 0.996057 0.437333
83 0.818712 0.114743
84 0.864484 0.157726
85 0.964888 0.315938
86 1.000000 0.500000
87 0.531395 0.000987
88 0.842274 0.135516
89 0.259123 0.938153
90 0.061847 0.259123
91 0.885257 0.818712
92 0.135516 0.157726
93 0.024472 0.345492
94 0.437333 0.996057
95 0.793893 0.095492
96 0.864484 0.842274
97 0.952414 0.287110
98 0.047586 0.712890
99 0.157726 0.135516
100 0.712890 0.047586
This diff could not be displayed because it is too large.
1 0.206107 0.095492
2 0.975528 0.654508
3 0.024472 0.345492
4 0.793893 0.095492
5 0.793893 0.904508
6 0.975528 0.345492
7 0.206107 0.904508
8 0.500000 0.000000
9 0.024472 0.654508
10 0.500000 1.000000
11 0.761250 0.317125
...\ No newline at end of file ...\ No newline at end of file
1 0.000000 0.500000
2 0.500000 1.000000
3 0.500000 0.000000
4 1.000000 0.500000
1 0.9 0.5
2 0.2 0.5
3 0.3 0.5
4 0.4 0.5
5 0.1 0.5
6 0.6 0.5
7 0.5 0.5
8 0.7 0.5
9
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
1 import java.io.BufferedReader;
2 import java.io.FileReader;
3
4 import edu.princeton.cs.algs4.Point2D;
5 import edu.princeton.cs.algs4.Queue;
6 import edu.princeton.cs.algs4.RectHV;
7 import edu.princeton.cs.algs4.StdDraw;
8
9 public class KdTree {
10
11 private static final boolean vertical = true;
12 private static final boolean horizontal = false;
13 private Node root;
14 private int size;
15
16 private static class Node {
17
18 private Point2D p; // the point
19 private RectHV rect; // the axis-aligned rectangle corresponding to this
20 // node
21 private Node lb; // the left/bottom subtree
22 private Node rt; // the right/top subtree
23
24 public Node(Point2D p, RectHV rect) {
25 this.p = p;
26 this.rect = rect;
27 }
28
29 }
30
31 // construct an empty set of points
32 public KdTree() {
33 root = null;
34 }
35
36 // is the set empty?
37 public boolean isEmpty() {
38 return size() == 0;
39 }
40
41 // number of points in the set
42 public int size() {
43 return size;
44 }
45
46 // add the point to the set (if it is not already in the set)
47 public void insert(Point2D p) {
48 if (p == null)
49 throw new NullPointerException();
50
51 root = insert(root, p, new RectHV(0, 0, 1, 1), vertical);
52 }
53
54 // helper function to recursively insert to the tree
55 private Node insert(Node x, Point2D p, RectHV rect, boolean orientation) {
56
57 // if x is null we've reached the end and can add a new node
58 if (x == null) {
59 this.size++;
60 return new Node(p, rect);
61
62 }
63
64 // if the node's point equals the point passed in
65 // then return that node to avoid duplicates
66 if (x.p.equals(p)) {
67 return x;
68 }
69
70 // determine if a node belongs to the left or right branch of the tree
71 // based off it's orientation. The root node is vertical and the
72 // orientation
73 // alternates between that and horizontal
74 if (orientation == vertical) {
75
76 // if the current node is vertical then the node it branches from
77 // will be horizontal
78 // so the x values are compared to determine which side to add the
79 // new node to
80 double cmp = p.x() - x.p.x();
81
82 if (cmp < 0) {
83 x.lb = insert(x.lb, p, new RectHV(x.rect.xmin(), x.rect.ymin(), x.p.x(), x.rect.ymax()), horizontal);
84 } else {
85 x.rt = insert(x.rt, p, new RectHV(x.p.x(), x.rect.ymin(), x.rect.xmax(), x.rect.ymax()), horizontal);
86 }
87 } else {
88
89 // same as above except the current node is horizontal so the
90 // branches will be vertical
91 // the y values are compared to determine which side to add the new
92 // node to
93 double cmp = p.y() - x.p.y();
94
95 if (cmp < 0) {
96 x.lb = insert(x.lb, p, new RectHV(x.rect.xmin(), x.rect.ymin(), x.rect.xmax(), x.p.y()), vertical);
97 } else {
98 x.rt = insert(x.rt, p, new RectHV(x.rect.xmin(), x.p.y(), x.rect.xmax(), x.rect.ymax()), vertical);
99 }
100
101 }
102
103 return x;
104 }
105
106 // does the set contain point p?
107 public boolean contains(Point2D p) {
108
109 if (p == null)
110 throw new NullPointerException();
111
112 return get(p);
113 }
114
115 // helper function to get a specific point p
116 private boolean get(Point2D p) {
117 return get(root, p, vertical);
118 }
119
120 // helper function to recursively find the node in the tree
121 private boolean get(Node x, Point2D p, boolean orientation) {
122
123 // the point doesn't exist in the tree
124 if (x == null)
125 return false;
126
127 // the point does exist in the tree
128 if (x.p.equals(p)) {
129 return true;
130 }
131
132 // compare points based on the orientation and either their x or y
133 // coordinate
134 // and returns the next node in the tree
135 double cmp;
136 if (orientation == vertical) {
137 cmp = p.x() - x.p.x();
138
139 } else {
140 cmp = p.y() - x.p.y();
141 }
142
143 if (cmp < 0) {
144 return get(x.lb, p, !orientation);
145 } else {
146 return get(x.rt, p, !orientation);
147 }
148
149 }
150
151 // draw all points to standard draw
152 public void draw() {
153 draw(root, vertical);
154
155 }
156
157 // draws red lines for vertical line segments
158 // draws blue lines for horizontal line segments
159 private void draw(Node x, boolean orientation) {
160
161 if (orientation == vertical) {
162 StdDraw.setPenColor(StdDraw.RED);
163 StdDraw.line(x.p.x(), x.rect.ymin(), x.p.x(), x.rect.ymax());
164 } else {
165 StdDraw.setPenColor(StdDraw.BLUE);
166 StdDraw.line(x.rect.xmin(), x.p.y(), x.rect.xmax(), x.p.y());
167 }
168
169 if (x.lb != null) {
170 draw(x.lb, !orientation);
171 }
172
173 if (x.rt != null) {
174 draw(x.rt, !orientation);
175 }
176
177 // draw point last to be on top of line
178 StdDraw.setPenColor(StdDraw.BLACK);
179 x.p.draw();
180 }
181
182 // all points that are inside the rectangle
183 public Iterable<Point2D> range(RectHV rect) {
184 Queue<Point2D> queue = new Queue<>();
185 range(root, rect, queue);
186
187 return queue;
188 }
189
190 // recurse through the tree to find intersecting rectangles of the
191 // nodes in the tree while the node is not null.
192 private void range(Node x, RectHV rect, Queue<Point2D> queue) {
193
194 if (x != null) {
195
196 if (!x.rect.intersects(rect)) {
197 return;
198 }
199
200 if (rect.contains(x.p)) {
201 queue.enqueue(x.p);
202 }
203
204 range(x.lb, rect, queue);
205 range(x.rt, rect, queue);
206 }
207
208 }
209
210 // a nearest neighbor in the set to point p; null if the set is empty
211 public Point2D nearest(Point2D p) {
212 if (p == null)
213 throw new NullPointerException();
214
215 return nearest(root, p, root.p, vertical);
216 }
217
218
219 // garbage please redo
220 private Point2D nearest(Node x, Point2D p, Point2D min, boolean orientation) {
221
222 if (x == null)
223 return min;
224 if (orientation == vertical) {
225 if (p.x() < x.p.x()) {
226 min = nearest(x.rt, p, min, horizontal);
227
228 if (x.lb != null && min.distanceSquaredTo(p) > x.lb.rect.distanceSquaredTo(p)) {
229 min = nearest(x.lb, p, min, horizontal);
230
231 }
232 } else {
233 min = nearest(x.lb, p, min, horizontal);
234
235 if (x.rt != null && min.distanceSquaredTo(p) > x.rt.rect.distanceSquaredTo(p)) {
236 min = nearest(x.rt, p, min, horizontal);
237 }
238
239 }
240
241 } else {
242 if (p.y() < x.p.y()) {
243 min = nearest(x.lb, p, min, vertical);
244
245 if (x.lb != null && min.distanceSquaredTo(p) > x.lb.rect.distanceSquaredTo(p)) {
246 min = nearest(x.lb, p, min, vertical);
247
248 }
249 } else {
250 min = nearest(x.lb, p, min, vertical);
251
252 if (x.rt != null && min.distanceSquaredTo(p) > x.rt.rect.distanceSquaredTo(p)) {
253 min = nearest(x.rt, p, min, vertical);
254 }
255 }
256 }
257
258 return min;
259 }
260
261 // unit testing of the methods (optional)
262 public static void main(String[] args) throws Exception {
263
264 KdTree kdtree = new KdTree();
265
266 /*
267 * System.out.println(kdtree.size());
268 * System.out.println(kdtree.isEmpty()); kdtree.insert(new Point2D(0.2,
269 * 0.4)); kdtree.insert(new Point2D(0.9, 0.6)); kdtree.insert(new
270 * Point2D(0.024, 0.34)); kdtree.insert(new Point2D(0.1, 0.6));
271 * kdtree.insert(new Point2D(0.6, 0.2)); kdtree.insert(new Point2D(0.7,
272 * 0.1)); kdtree.insert(new Point2D(0.6, 0.2)); kdtree.insert(new
273 * Point2D(0.7, 0.1)); kdtree.insert(new Point2D(0.5, 0.5));
274 *
275 * System.out.println(kdtree.isEmpty());
276 * System.out.println(kdtree.contains(new Point2D(0.97, 0.34)));
277 * System.out.println(kdtree.contains(new Point2D(0.5, 0.5)));
278 *
279 * Iterable<Point2D> iterable = kdtree.range(new RectHV(0,0,1,1));
280 *
281 * for(Point2D point : iterable){ System.out.println(point.toString());
282 * }
283 *
284 * kdtree.draw();
285 */
286
287 BufferedReader reader = null;
288 try {
289 reader = new BufferedReader(new FileReader(args[0]));
290 } catch (Exception e) {
291 System.out.println("File not found");
292 }
293
294 String line;
295 while ((line = reader.readLine()) != null) {
296 String[] splitLine = line.trim().split("\\s+");
297
298 double a = Double.parseDouble(splitLine[0]);
299 double b = Double.parseDouble(splitLine[1]);
300 Point2D p = new Point2D(a, b);
301 kdtree.insert(p);
302 }
303
304
305
306 }
307 }
...\ No newline at end of file ...\ No newline at end of file
1 /******************************************************************************
2 * Compilation: javac KdTreeGenerator.java
3 * Execution: java KdTreeGenerator n
4 * Dependencies:
5 *
6 * Creates n random points in the unit square and print to standard output.
7 *
8 * % java KdTreeGenerator 5
9 * 0.195080 0.938777
10 * 0.351415 0.017802
11 * 0.556719 0.841373
12 * 0.183384 0.636701
13 * 0.649952 0.237188
14 *
15 ******************************************************************************/
16
17 import edu.princeton.cs.algs4.StdRandom;
18 import edu.princeton.cs.algs4.StdOut;
19
20 public class KdTreeGenerator {
21
22 public static void main(String[] args) {
23 int n = Integer.parseInt(args[0]);
24 for (int i = 0; i < n; i++) {
25 double x = StdRandom.uniform(0.0, 1.0);
26 double y = StdRandom.uniform(0.0, 1.0);
27 StdOut.printf("%8.6f %8.6f\n", x, y);
28 }
29 }
30 }
1 /******************************************************************************
2 * Compilation: javac KdTreeVisualizer.java
3 * Execution: java KdTreeVisualizer
4 * Dependencies: KdTree.java
5 *
6 * Add the points that the user clicks in the standard draw window
7 * to a kd-tree and draw the resulting kd-tree.
8 *
9 ******************************************************************************/
10
11 import edu.princeton.cs.algs4.Point2D;
12 import edu.princeton.cs.algs4.RectHV;
13 import edu.princeton.cs.algs4.StdDraw;
14 import edu.princeton.cs.algs4.StdOut;
15
16 public class KdTreeVisualizer {
17
18 public static void main(String[] args) {
19 RectHV rect = new RectHV(0.0, 0.0, 1.0, 1.0);
20 StdDraw.enableDoubleBuffering();
21 KdTree kdtree = new KdTree();
22 while (true) {
23 if (StdDraw.mousePressed()) {
24 double x = StdDraw.mouseX();
25 double y = StdDraw.mouseY();
26 StdOut.printf("%8.6f %8.6f\n", x, y);
27 Point2D p = new Point2D(x, y);
28 if (rect.contains(p)) {
29 StdOut.printf("%8.6f %8.6f\n", x, y);
30 kdtree.insert(p);
31 StdDraw.clear();
32 kdtree.draw();
33 StdDraw.show();
34 }
35 }
36 StdDraw.pause(50);
37 }
38
39 }
40 }
1 /******************************************************************************
2 * Compilation: javac NearestNeighborVisualizer.java
3 * Execution: java NearestNeighborVisualizer input.txt
4 * Dependencies: PointSET.java KdTree.java
5 *
6 * Read points from a file (specified as a command-line argument) and
7 * draw to standard draw. Highlight the closest point to the mouse.
8 *
9 * The nearest neighbor according to the brute-force algorithm is drawn
10 * in red; the nearest neighbor using the kd-tree algorithm is drawn in blue.
11 *
12 ******************************************************************************/
13
14 import edu.princeton.cs.algs4.In;
15 import edu.princeton.cs.algs4.Point2D;
16 import edu.princeton.cs.algs4.StdDraw;
17
18 public class NearestNeighborVisualizer {
19
20 public static void main(String[] args) {
21 String filename = args[0];
22 In in = new In(filename);
23
24 StdDraw.enableDoubleBuffering();
25
26 // initialize the two data structures with point from standard input
27 PointSET brute = new PointSET();
28 KdTree kdtree = new KdTree();
29 while (!in.isEmpty()) {
30 double x = in.readDouble();
31 double y = in.readDouble();
32 Point2D p = new Point2D(x, y);
33 kdtree.insert(p);
34 brute.insert(p);
35 }
36
37 while (true) {
38
39 // the location (x, y) of the mouse
40 double x = StdDraw.mouseX();
41 double y = StdDraw.mouseY();
42 Point2D query = new Point2D(x, y);
43
44 // draw all of the points
45 StdDraw.clear();
46 StdDraw.setPenColor(StdDraw.BLACK);
47 StdDraw.setPenRadius(0.01);
48 brute.draw();
49
50 // draw in red the nearest neighbor (using brute-force algorithm)
51 StdDraw.setPenRadius(0.03);
52 StdDraw.setPenColor(StdDraw.RED);
53 brute.nearest(query).draw();
54 StdDraw.setPenRadius(0.02);
55
56 // draw in blue the nearest neighbor (using kd-tree algorithm)
57 StdDraw.setPenColor(StdDraw.BLUE);
58 kdtree.nearest(query).draw();
59 StdDraw.show();
60 StdDraw.pause(40);
61 }
62 }
63 }
1 import java.io.BufferedReader;
2 import java.io.FileReader;
3
4 import edu.princeton.cs.algs4.In;
5 import edu.princeton.cs.algs4.Point2D;
6 import edu.princeton.cs.algs4.RectHV;
7 import edu.princeton.cs.algs4.SET;
8
9 public class PointSET {
10
11 private SET<Point2D> points;
12
13 // construct an empty set of points
14 public PointSET() {
15 this.points = new SET<Point2D>();
16 }
17
18 // is the set empty?
19 public boolean isEmpty() {
20 return points.isEmpty();
21 }
22
23 // number of points in the set
24 public int size() {
25 return points.size();
26 }
27
28 // add the point to the set (if it is not already in the set)
29 public void insert(Point2D p) {
30
31 if(p == null)
32 throw new NullPointerException();
33
34 if (!points.contains(p)) {
35 points.add(p);
36 }
37 }
38
39 // does the set contain point p?
40 public boolean contains(Point2D p) {
41
42 if(p == null)
43 throw new NullPointerException();
44
45 return points.contains(p);
46 }
47
48 // draw all points to standard draw
49 public void draw() {
50 for (Point2D p : points) {
51 p.draw();
52 }
53 }
54
55 // all points that are inside the rectangle
56 public Iterable<Point2D> range(RectHV rect) {
57 SET<Point2D> contains = new SET<Point2D>();
58
59 for (Point2D p : points) {
60 if (rect.contains(p)) {
61 contains.add(p);
62 }
63 }
64
65 return contains;
66 }
67
68 // a nearest neighbor in the set to point p; null if the set is empty
69 public Point2D nearest(Point2D p) {
70
71 Point2D closest = null;
72
73 for (Point2D point : points) {
74
75 if (closest == null || p.distanceTo(point) < p.distanceTo(closest)) {
76 closest = p;
77 }
78
79 }
80
81 return closest;
82 }
83
84 // unit testing of the methods (optional)
85 public static void main(String[] args) throws Exception{
86
87 PointSET set = new PointSET();
88 BufferedReader reader = null;
89 try {
90 reader = new BufferedReader(new FileReader(args[0]));
91 } catch (Exception e) {
92 System.out.println("File not found");
93 }
94
95 String line;
96 while((line = reader.readLine()) != null){
97 String [] splitLine = line.trim().split("\\s+");
98
99 double a = Double.parseDouble(splitLine[0]);
100 double b = Double.parseDouble(splitLine[1]);
101 Point2D p = new Point2D(a,b);
102 set.insert(p);
103 }
104
105 set.draw();
106
107 }
108 }
...\ No newline at end of file ...\ No newline at end of file
1 /******************************************************************************
2 * Compilation: javac RangeSearchVisualizer.java
3 * Execution: java RangeSearchVisualizer input.txt
4 * Dependencies: PointSET.java KdTree.java
5 *
6 * Read points from a file (specified as a command-line arugment) and
7 * draw to standard draw. Also draw all of the points in the rectangle
8 * the user selects by dragging the mouse.
9 *
10 * The range search results using the brute-force algorithm are drawn
11 * in red; the results using the kd-tree algorithms are drawn in blue.
12 *
13 ******************************************************************************/
14
15 import edu.princeton.cs.algs4.In;
16 import edu.princeton.cs.algs4.Point2D;
17 import edu.princeton.cs.algs4.RectHV;
18 import edu.princeton.cs.algs4.StdDraw;
19
20 public class RangeSearchVisualizer {
21
22 public static void main(String[] args) {
23
24 String filename = args[0];
25 In in = new In(filename);
26
27 StdDraw.enableDoubleBuffering();
28
29 // initialize the data structures with N points from standard input
30 PointSET brute = new PointSET();
31 KdTree kdtree = new KdTree();
32 while (!in.isEmpty()) {
33 double x = in.readDouble();
34 double y = in.readDouble();
35 Point2D p = new Point2D(x, y);
36 kdtree.insert(p);
37 brute.insert(p);
38 }
39
40 double x0 = 0.0, y0 = 0.0; // initial endpoint of rectangle
41 double x1 = 0.0, y1 = 0.0; // current location of mouse
42 boolean isDragging = false; // is the user dragging a rectangle
43
44 // draw the points
45 StdDraw.clear();
46 StdDraw.setPenColor(StdDraw.BLACK);
47 StdDraw.setPenRadius(0.01);
48 brute.draw();
49 StdDraw.show();
50
51 while (true) {
52
53 // user starts to drag a rectangle
54 if (StdDraw.mousePressed() && !isDragging) {
55 x0 = StdDraw.mouseX();
56 y0 = StdDraw.mouseY();
57 isDragging = true;
58 continue;
59 }
60
61 // user is dragging a rectangle
62 else if (StdDraw.mousePressed() && isDragging) {
63 x1 = StdDraw.mouseX();
64 y1 = StdDraw.mouseY();
65 continue;
66 }
67
68 // mouse no longer pressed
69 else if (!StdDraw.mousePressed() && isDragging) {
70 isDragging = false;
71 }
72
73
74 RectHV rect = new RectHV(Math.min(x0, x1), Math.min(y0, y1),
75 Math.max(x0, x1), Math.max(y0, y1));
76 // draw the points
77 StdDraw.clear();
78 StdDraw.setPenColor(StdDraw.BLACK);
79 StdDraw.setPenRadius(0.01);
80 brute.draw();
81
82 // draw the rectangle
83 StdDraw.setPenColor(StdDraw.BLACK);
84 StdDraw.setPenRadius();
85 rect.draw();
86
87 // draw the range search results for brute-force data structure in red
88 StdDraw.setPenRadius(0.03);
89 StdDraw.setPenColor(StdDraw.RED);
90 for (Point2D p : brute.range(rect))
91 p.draw();
92
93 // draw the range search results for kd-tree in blue
94 StdDraw.setPenRadius(.02);
95 StdDraw.setPenColor(StdDraw.BLUE);
96 for (Point2D p : kdtree.range(rect))
97 p.draw();
98
99 StdDraw.show();
100 StdDraw.pause(40);
101 }
102 }
103 }
1 /******************************************************************************
2 * Compilation: javac Accumulator.java
3 * Execution: java Accumulator < input.txt
4 * Dependencies: StdOut.java StdIn.java
5 *
6 * Mutable data type that calculates the mean, sample standard
7 * deviation, and sample variance of a stream of real numbers
8 * use a stable, one-pass algorithm.
9 *
10 ******************************************************************************/
11
12 package edu.princeton.cs.algs4;
13
14
15 /**
16 * The {@code Accumulator} class is a data type for computing the running
17 * mean, sample standard deviation, and sample variance of a stream of real
18 * numbers. It provides an example of a mutable data type and a streaming
19 * algorithm.
20 * <p>
21 * This implementation uses a one-pass algorithm that is less susceptible
22 * to floating-point roundoff error than the more straightforward
23 * implementation based on saving the sum of the squares of the numbers.
24 * This technique is due to
25 * <a href = "https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm">B. P. Welford</a>.
26 * Each operation takes constant time in the worst case.
27 * The amount of memory is constant - the data values are not stored.
28 * <p>
29 * For additional documentation,
30 * see <a href="http://algs4.cs.princeton.edu/12oop">Section 1.2</a> of
31 * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
32 *
33 * @author Robert Sedgewick
34 * @author Kevin Wayne
35 */
36 public class Accumulator {
37 private int n = 0; // number of data values
38 private double sum = 0.0; // sample variance * (n-1)
39 private double mu = 0.0; // sample mean
40
41 /**
42 * Initializes an accumulator.
43 */
44 public Accumulator() {
45 }
46
47 /**
48 * Adds the specified data value to the accumulator.
49 * @param x the data value
50 */
51 public void addDataValue(double x) {
52 n++;
53 double delta = x - mu;
54 mu += delta / n;
55 sum += (double) (n - 1) / n * delta * delta;
56 }
57
58 /**
59 * Returns the mean of the data values.
60 * @return the mean of the data values
61 */
62 public double mean() {
63 return mu;
64 }
65
66 /**
67 * Returns the sample variance of the data values.
68 * @return the sample variance of the data values
69 */
70 public double var() {
71 return sum / (n - 1);
72 }
73
74 /**
75 * Returns the sample standard deviation of the data values.
76 * @return the sample standard deviation of the data values
77 */
78 public double stddev() {
79 return Math.sqrt(this.var());
80 }
81
82 /**
83 * Returns the number of data values.
84 * @return the number of data values
85 */
86 public int count() {
87 return n;
88 }
89
90 /**
91 * Unit tests the {@code Accumulator} data type.
92 * Reads in a stream of real number from standard input;
93 * adds them to the accumulator; and prints the mean,
94 * sample standard deviation, and sample variance to standard
95 * output.
96 *
97 * @param args the command-line arguments
98 */
99 public static void main(String[] args) {
100 Accumulator stats = new Accumulator();
101 while (!StdIn.isEmpty()) {
102 double x = StdIn.readDouble();
103 stats.addDataValue(x);
104 }
105
106 StdOut.printf("n = %d\n", stats.count());
107 StdOut.printf("mean = %.5f\n", stats.mean());
108 StdOut.printf("stddev = %.5f\n", stats.stddev());
109 StdOut.printf("var = %.5f\n", stats.var());
110 }
111 }
112
113 /******************************************************************************
114 * Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
115 *
116 * This file is part of algs4.jar, which accompanies the textbook
117 *
118 * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
119 * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
120 * http://algs4.cs.princeton.edu
121 *
122 *
123 * algs4.jar is free software: you can redistribute it and/or modify
124 * it under the terms of the GNU General Public License as published by
125 * the Free Software Foundation, either version 3 of the License, or
126 * (at your option) any later version.
127 *
128 * algs4.jar is distributed in the hope that it will be useful,
129 * but WITHOUT ANY WARRANTY; without even the implied warranty of
130 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
131 * GNU General Public License for more details.
132 *
133 * You should have received a copy of the GNU General Public License
134 * along with algs4.jar. If not, see http://www.gnu.org/licenses.
135 ******************************************************************************/
1 /******************************************************************************
2 * Compilation: javac AcyclicLP.java
3 * Execution: java AcyclicP V E
4 * Dependencies: EdgeWeightedDigraph.java DirectedEdge.java Topological.java
5 * Data files: http://algs4.cs.princeton.edu/44sp/tinyEWDAG.txt
6 *
7 * Computes longeset paths in an edge-weighted acyclic digraph.
8 *
9 * Remark: should probably check that graph is a DAG before running
10 *
11 * % java AcyclicLP tinyEWDAG.txt 5
12 * 5 to 0 (2.44) 5->1 0.32 1->3 0.29 3->6 0.52 6->4 0.93 4->0 0.38
13 * 5 to 1 (0.32) 5->1 0.32
14 * 5 to 2 (2.77) 5->1 0.32 1->3 0.29 3->6 0.52 6->4 0.93 4->7 0.37 7->2 0.34
15 * 5 to 3 (0.61) 5->1 0.32 1->3 0.29
16 * 5 to 4 (2.06) 5->1 0.32 1->3 0.29 3->6 0.52 6->4 0.93
17 * 5 to 5 (0.00)
18 * 5 to 6 (1.13) 5->1 0.32 1->3 0.29 3->6 0.52
19 * 5 to 7 (2.43) 5->1 0.32 1->3 0.29 3->6 0.52 6->4 0.93 4->7 0.37
20 *
21 ******************************************************************************/
22
23 package edu.princeton.cs.algs4;
24
25 /**
26 * The {@code AcyclicLP} class represents a data type for solving the
27 * single-source longest paths problem in edge-weighted directed
28 * acyclic graphs (DAGs). The edge weights can be positive, negative, or zero.
29 * <p>
30 * This implementation uses a topological-sort based algorithm.
31 * The constructor takes time proportional to <em>V</em> + <em>E</em>,
32 * where <em>V</em> is the number of vertices and <em>E</em> is the number of edges.
33 * Afterwards, the {@code distTo()} and {@code hasPathTo()} methods take
34 * constant time and the {@code pathTo()} method takes time proportional to the
35 * number of edges in the longest path returned.
36 * <p>
37 * For additional documentation,
38 * see <a href="http://algs4.cs.princeton.edu/44sp">Section 4.4</a> of
39 * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
40 *
41 * @author Robert Sedgewick
42 * @author Kevin Wayne
43 */
44 public class AcyclicLP {
45 private double[] distTo; // distTo[v] = distance of longest s->v path
46 private DirectedEdge[] edgeTo; // edgeTo[v] = last edge on longest s->v path
47
48 /**
49 * Computes a longest paths tree from {@code s} to every other vertex in
50 * the directed acyclic graph {@code G}.
51 * @param G the acyclic digraph
52 * @param s the source vertex
53 * @throws IllegalArgumentException if the digraph is not acyclic
54 * @throws IllegalArgumentException unless {@code 0 <= s < V}
55 */
56 public AcyclicLP(EdgeWeightedDigraph G, int s) {
57 distTo = new double[G.V()];
58 edgeTo = new DirectedEdge[G.V()];
59
60 validateVertex(s);
61
62 for (int v = 0; v < G.V(); v++)
63 distTo[v] = Double.NEGATIVE_INFINITY;
64 distTo[s] = 0.0;
65
66 // relax vertices in toplogical order
67 Topological topological = new Topological(G);
68 if (!topological.hasOrder())
69 throw new IllegalArgumentException("Digraph is not acyclic.");
70 for (int v : topological.order()) {
71 for (DirectedEdge e : G.adj(v))
72 relax(e);
73 }
74 }
75
76 // relax edge e, but update if you find a *longer* path
77 private void relax(DirectedEdge e) {
78 int v = e.from(), w = e.to();
79 if (distTo[w] < distTo[v] + e.weight()) {
80 distTo[w] = distTo[v] + e.weight();
81 edgeTo[w] = e;
82 }
83 }
84
85 /**
86 * Returns the length of a longest path from the source vertex {@code s} to vertex {@code v}.
87 * @param v the destination vertex
88 * @return the length of a longest path from the source vertex {@code s} to vertex {@code v};
89 * {@code Double.NEGATIVE_INFINITY} if no such path
90 * @throws IllegalArgumentException unless {@code 0 <= v < V}
91 */
92 public double distTo(int v) {
93 validateVertex(v);
94 return distTo[v];
95 }
96
97 /**
98 * Is there a path from the source vertex {@code s} to vertex {@code v}?
99 * @param v the destination vertex
100 * @return {@code true} if there is a path from the source vertex
101 * {@code s} to vertex {@code v}, and {@code false} otherwise
102 * @throws IllegalArgumentException unless {@code 0 <= v < V}
103 */
104 public boolean hasPathTo(int v) {
105 validateVertex(v);
106 return distTo[v] > Double.NEGATIVE_INFINITY;
107 }
108
109 /**
110 * Returns a longest path from the source vertex {@code s} to vertex {@code v}.
111 * @param v the destination vertex
112 * @return a longest path from the source vertex {@code s} to vertex {@code v}
113 * as an iterable of edges, and {@code null} if no such path
114 * @throws IllegalArgumentException unless {@code 0 <= v < V}
115 */
116 public Iterable<DirectedEdge> pathTo(int v) {
117 validateVertex(v);
118 if (!hasPathTo(v)) return null;
119 Stack<DirectedEdge> path = new Stack<DirectedEdge>();
120 for (DirectedEdge e = edgeTo[v]; e != null; e = edgeTo[e.from()]) {
121 path.push(e);
122 }
123 return path;
124 }
125
126 // throw an IllegalArgumentException unless {@code 0 <= v < V}
127 private void validateVertex(int v) {
128 int V = distTo.length;
129 if (v < 0 || v >= V)
130 throw new IllegalArgumentException("vertex " + v + " is not between 0 and " + (V-1));
131 }
132
133 /**
134 * Unit tests the {@code AcyclicLP} data type.
135 *
136 * @param args the command-line arguments
137 */
138 public static void main(String[] args) {
139 In in = new In(args[0]);
140 int s = Integer.parseInt(args[1]);
141 EdgeWeightedDigraph G = new EdgeWeightedDigraph(in);
142
143 AcyclicLP lp = new AcyclicLP(G, s);
144
145 for (int v = 0; v < G.V(); v++) {
146 if (lp.hasPathTo(v)) {
147 StdOut.printf("%d to %d (%.2f) ", s, v, lp.distTo(v));
148 for (DirectedEdge e : lp.pathTo(v)) {
149 StdOut.print(e + " ");
150 }
151 StdOut.println();
152 }
153 else {
154 StdOut.printf("%d to %d no path\n", s, v);
155 }
156 }
157 }
158 }
159
160 /******************************************************************************
161 * Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
162 *
163 * This file is part of algs4.jar, which accompanies the textbook
164 *
165 * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
166 * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
167 * http://algs4.cs.princeton.edu
168 *
169 *
170 * algs4.jar is free software: you can redistribute it and/or modify
171 * it under the terms of the GNU General Public License as published by
172 * the Free Software Foundation, either version 3 of the License, or
173 * (at your option) any later version.
174 *
175 * algs4.jar is distributed in the hope that it will be useful,
176 * but WITHOUT ANY WARRANTY; without even the implied warranty of
177 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
178 * GNU General Public License for more details.
179 *
180 * You should have received a copy of the GNU General Public License
181 * along with algs4.jar. If not, see http://www.gnu.org/licenses.
182 ******************************************************************************/
1 /******************************************************************************
2 * Compilation: javac AcyclicSP.java
3 * Execution: java AcyclicSP V E
4 * Dependencies: EdgeWeightedDigraph.java DirectedEdge.java Topological.java
5 * Data files: http://algs4.cs.princeton.edu/44sp/tinyEWDAG.txt
6 *
7 * Computes shortest paths in an edge-weighted acyclic digraph.
8 *
9 * % java AcyclicSP tinyEWDAG.txt 5
10 * 5 to 0 (0.73) 5->4 0.35 4->0 0.38
11 * 5 to 1 (0.32) 5->1 0.32
12 * 5 to 2 (0.62) 5->7 0.28 7->2 0.34
13 * 5 to 3 (0.61) 5->1 0.32 1->3 0.29
14 * 5 to 4 (0.35) 5->4 0.35
15 * 5 to 5 (0.00)
16 * 5 to 6 (1.13) 5->1 0.32 1->3 0.29 3->6 0.52
17 * 5 to 7 (0.28) 5->7 0.28
18 *
19 ******************************************************************************/
20
21 package edu.princeton.cs.algs4;
22
23 /**
24 * The {@code AcyclicSP} class represents a data type for solving the
25 * single-source shortest paths problem in edge-weighted directed acyclic
26 * graphs (DAGs). The edge weights can be positive, negative, or zero.
27 * <p>
28 * This implementation uses a topological-sort based algorithm.
29 * The constructor takes time proportional to <em>V</em> + <em>E</em>,
30 * where <em>V</em> is the number of vertices and <em>E</em> is the number of edges.
31 * Afterwards, the {@code distTo()} and {@code hasPathTo()} methods take
32 * constant time and the {@code pathTo()} method takes time proportional to the
33 * number of edges in the shortest path returned.
34 * <p>
35 * For additional documentation,
36 * see <a href="http://algs4.cs.princeton.edu/44sp">Section 4.4</a> of
37 * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
38 *
39 * @author Robert Sedgewick
40 * @author Kevin Wayne
41 */
42 public class AcyclicSP {
43 private double[] distTo; // distTo[v] = distance of shortest s->v path
44 private DirectedEdge[] edgeTo; // edgeTo[v] = last edge on shortest s->v path
45
46
47 /**
48 * Computes a shortest paths tree from {@code s} to every other vertex in
49 * the directed acyclic graph {@code G}.
50 * @param G the acyclic digraph
51 * @param s the source vertex
52 * @throws IllegalArgumentException if the digraph is not acyclic
53 * @throws IllegalArgumentException unless {@code 0 <= s < V}
54 */
55 public AcyclicSP(EdgeWeightedDigraph G, int s) {
56 distTo = new double[G.V()];
57 edgeTo = new DirectedEdge[G.V()];
58
59 validateVertex(s);
60
61 for (int v = 0; v < G.V(); v++)
62 distTo[v] = Double.POSITIVE_INFINITY;
63 distTo[s] = 0.0;
64
65 // visit vertices in toplogical order
66 Topological topological = new Topological(G);
67 if (!topological.hasOrder())
68 throw new IllegalArgumentException("Digraph is not acyclic.");
69 for (int v : topological.order()) {
70 for (DirectedEdge e : G.adj(v))
71 relax(e);
72 }
73 }
74
75 // relax edge e
76 private void relax(DirectedEdge e) {
77 int v = e.from(), w = e.to();
78 if (distTo[w] > distTo[v] + e.weight()) {
79 distTo[w] = distTo[v] + e.weight();
80 edgeTo[w] = e;
81 }
82 }
83
84 /**
85 * Returns the length of a shortest path from the source vertex {@code s} to vertex {@code v}.
86 * @param v the destination vertex
87 * @return the length of a shortest path from the source vertex {@code s} to vertex {@code v};
88 * {@code Double.POSITIVE_INFINITY} if no such path
89 * @throws IllegalArgumentException unless {@code 0 <= v < V}
90 */
91 public double distTo(int v) {
92 validateVertex(v);
93 return distTo[v];
94 }
95
96 /**
97 * Is there a path from the source vertex {@code s} to vertex {@code v}?
98 * @param v the destination vertex
99 * @return {@code true} if there is a path from the source vertex
100 * {@code s} to vertex {@code v}, and {@code false} otherwise
101 * @throws IllegalArgumentException unless {@code 0 <= v < V}
102 */
103 public boolean hasPathTo(int v) {
104 validateVertex(v);
105 return distTo[v] < Double.POSITIVE_INFINITY;
106 }
107
108 /**
109 * Returns a shortest path from the source vertex {@code s} to vertex {@code v}.
110 * @param v the destination vertex
111 * @return a shortest path from the source vertex {@code s} to vertex {@code v}
112 * as an iterable of edges, and {@code null} if no such path
113 * @throws IllegalArgumentException unless {@code 0 <= v < V}
114 */
115 public Iterable<DirectedEdge> pathTo(int v) {
116 validateVertex(v);
117 if (!hasPathTo(v)) return null;
118 Stack<DirectedEdge> path = new Stack<DirectedEdge>();
119 for (DirectedEdge e = edgeTo[v]; e != null; e = edgeTo[e.from()]) {
120 path.push(e);
121 }
122 return path;
123 }
124
125 // throw an IllegalArgumentException unless {@code 0 <= v < V}
126 private void validateVertex(int v) {
127 int V = distTo.length;
128 if (v < 0 || v >= V)
129 throw new IllegalArgumentException("vertex " + v + " is not between 0 and " + (V-1));
130 }
131
132 /**
133 * Unit tests the {@code AcyclicSP} data type.
134 *
135 * @param args the command-line arguments
136 */
137 public static void main(String[] args) {
138 In in = new In(args[0]);
139 int s = Integer.parseInt(args[1]);
140 EdgeWeightedDigraph G = new EdgeWeightedDigraph(in);
141
142 // find shortest path from s to each other vertex in DAG
143 AcyclicSP sp = new AcyclicSP(G, s);
144 for (int v = 0; v < G.V(); v++) {
145 if (sp.hasPathTo(v)) {
146 StdOut.printf("%d to %d (%.2f) ", s, v, sp.distTo(v));
147 for (DirectedEdge e : sp.pathTo(v)) {
148 StdOut.print(e + " ");
149 }
150 StdOut.println();
151 }
152 else {
153 StdOut.printf("%d to %d no path\n", s, v);
154 }
155 }
156 }
157 }
158
159 /******************************************************************************
160 * Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
161 *
162 * This file is part of algs4.jar, which accompanies the textbook
163 *
164 * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
165 * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
166 * http://algs4.cs.princeton.edu
167 *
168 *
169 * algs4.jar is free software: you can redistribute it and/or modify
170 * it under the terms of the GNU General Public License as published by
171 * the Free Software Foundation, either version 3 of the License, or
172 * (at your option) any later version.
173 *
174 * algs4.jar is distributed in the hope that it will be useful,
175 * but WITHOUT ANY WARRANTY; without even the implied warranty of
176 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
177 * GNU General Public License for more details.
178 *
179 * You should have received a copy of the GNU General Public License
180 * along with algs4.jar. If not, see http://www.gnu.org/licenses.
181 ******************************************************************************/
1 /******************************************************************************
2 * Compilation: javac AdjMatrixEdgeWeightedDigraph.java
3 * Execution: java AdjMatrixEdgeWeightedDigraph V E
4 * Dependencies: StdOut.java
5 *
6 * An edge-weighted digraph, implemented using an adjacency matrix.
7 * Parallel edges are disallowed; self-loops are allowed.
8 *
9 ******************************************************************************/
10
11 package edu.princeton.cs.algs4;
12
13 import java.util.Iterator;
14 import java.util.NoSuchElementException;
15
16 /**
17 * The {@code AdjMatrixEdgeWeightedDigraph} class represents a edge-weighted
18 * digraph of vertices named 0 through <em>V</em> - 1, where each
19 * directed edge is of type {@link DirectedEdge} and has a real-valued weight.
20 * It supports the following two primary operations: add a directed edge
21 * to the digraph and iterate over all of edges incident from a given vertex.
22 * It also provides
23 * methods for returning the number of vertices <em>V</em> and the number
24 * of edges <em>E</em>. Parallel edges are disallowed; self-loops are permitted.
25 * <p>
26 * This implementation uses an adjacency-matrix representation.
27 * All operations take constant time (in the worst case) except
28 * iterating over the edges incident from a given vertex, which takes
29 * time proportional to <em>V</em>.
30 * <p>
31 * For additional documentation,
32 * see <a href="http://algs4.cs.princeton.edu/44sp">Section 4.4</a> of
33 * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
34 *
35 * @author Robert Sedgewick
36 * @author Kevin Wayne
37 */
38 public class AdjMatrixEdgeWeightedDigraph {
39 private static final String NEWLINE = System.getProperty("line.separator");
40
41 private final int V;
42 private int E;
43 private DirectedEdge[][] adj;
44
45 /**
46 * Initializes an empty edge-weighted digraph with {@code V} vertices and 0 edges.
47 * @param V the number of vertices
48 * @throws IllegalArgumentException if {@code V < 0}
49 */
50 public AdjMatrixEdgeWeightedDigraph(int V) {
51 if (V < 0) throw new IllegalArgumentException("number of vertices must be nonnegative");
52 this.V = V;
53 this.E = 0;
54 this.adj = new DirectedEdge[V][V];
55 }
56
57 /**
58 * Initializes a random edge-weighted digraph with {@code V} vertices and <em>E</em> edges.
59 * @param V the number of vertices
60 * @param E the number of edges
61 * @throws IllegalArgumentException if {@code V < 0}
62 * @throws IllegalArgumentException if {@code E < 0}
63 */
64 public AdjMatrixEdgeWeightedDigraph(int V, int E) {
65 this(V);
66 if (E < 0) throw new IllegalArgumentException("number of edges must be nonnegative");
67 if (E > V*V) throw new IllegalArgumentException("too many edges");
68
69 // can be inefficient
70 while (this.E != E) {
71 int v = StdRandom.uniform(V);
72 int w = StdRandom.uniform(V);
73 double weight = Math.round(100 * StdRandom.uniform()) / 100.0;
74 addEdge(new DirectedEdge(v, w, weight));
75 }
76 }
77
78 /**
79 * Returns the number of vertices in the edge-weighted digraph.
80 * @return the number of vertices in the edge-weighted digraph
81 */
82 public int V() {
83 return V;
84 }
85
86 /**
87 * Returns the number of edges in the edge-weighted digraph.
88 * @return the number of edges in the edge-weighted digraph
89 */
90 public int E() {
91 return E;
92 }
93
94 /**
95 * Adds the directed edge {@code e} to the edge-weighted digraph (if there
96 * is not already an edge with the same endpoints).
97 * @param e the edge
98 */
99 public void addEdge(DirectedEdge e) {
100 int v = e.from();
101 int w = e.to();
102 validateVertex(v);
103 validateVertex(w);
104 if (adj[v][w] == null) {
105 E++;
106 adj[v][w] = e;
107 }
108 }
109
110 /**
111 * Returns the directed edges incident from vertex {@code v}.
112 * @param v the vertex
113 * @return the directed edges incident from vertex {@code v} as an Iterable
114 * @throws IllegalArgumentException unless {@code 0 <= v < V}
115 */
116 public Iterable<DirectedEdge> adj(int v) {
117 validateVertex(v);
118 return new AdjIterator(v);
119 }
120
121 // support iteration over graph vertices
122 private class AdjIterator implements Iterator<DirectedEdge>, Iterable<DirectedEdge> {
123 private int v;
124 private int w = 0;
125
126 public AdjIterator(int v) {
127 this.v = v;
128 }
129
130 public Iterator<DirectedEdge> iterator() {
131 return this;
132 }
133
134 public boolean hasNext() {
135 while (w < V) {
136 if (adj[v][w] != null) return true;
137 w++;
138 }
139 return false;
140 }
141
142 public DirectedEdge next() {
143 if (!hasNext()) {
144 throw new NoSuchElementException();
145 }
146 return adj[v][w++];
147 }
148
149 public void remove() {
150 throw new UnsupportedOperationException();
151 }
152 }
153
154 /**
155 * Returns a string representation of the edge-weighted digraph. This method takes
156 * time proportional to <em>V</em><sup>2</sup>.
157 * @return the number of vertices <em>V</em>, followed by the number of edges <em>E</em>,
158 * followed by the <em>V</em> adjacency lists of edges
159 */
160 public String toString() {
161 StringBuilder s = new StringBuilder();
162 s.append(V + " " + E + NEWLINE);
163 for (int v = 0; v < V; v++) {
164 s.append(v + ": ");
165 for (DirectedEdge e : adj(v)) {
166 s.append(e + " ");
167 }
168 s.append(NEWLINE);
169 }
170 return s.toString();
171 }
172
173 // throw an IllegalArgumentException unless {@code 0 <= v < V}
174 private void validateVertex(int v) {
175 if (v < 0 || v >= V)
176 throw new IllegalArgumentException("vertex " + v + " is not between 0 and " + (V-1));
177 }
178
179
180 /**
181 * Unit tests the {@code AdjMatrixEdgeWeightedDigraph} data type.
182 *
183 * @param args the command-line arguments
184 */
185 public static void main(String[] args) {
186 int V = Integer.parseInt(args[0]);
187 int E = Integer.parseInt(args[1]);
188 AdjMatrixEdgeWeightedDigraph G = new AdjMatrixEdgeWeightedDigraph(V, E);
189 StdOut.println(G);
190 }
191
192 }
193
194 /******************************************************************************
195 * Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
196 *
197 * This file is part of algs4.jar, which accompanies the textbook
198 *
199 * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
200 * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
201 * http://algs4.cs.princeton.edu
202 *
203 *
204 * algs4.jar is free software: you can redistribute it and/or modify
205 * it under the terms of the GNU General Public License as published by
206 * the Free Software Foundation, either version 3 of the License, or
207 * (at your option) any later version.
208 *
209 * algs4.jar is distributed in the hope that it will be useful,
210 * but WITHOUT ANY WARRANTY; without even the implied warranty of
211 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
212 * GNU General Public License for more details.
213 *
214 * You should have received a copy of the GNU General Public License
215 * along with algs4.jar. If not, see http://www.gnu.org/licenses.
216 ******************************************************************************/
1 /******************************************************************************
2 * Compilation: javac Alphabet.java
3 * Execution: java Alphabet
4 * Dependencies: StdOut.java
5 *
6 * A data type for alphabets, for use with string-processing code
7 * that must convert between an alphabet of size R and the integers
8 * 0 through R-1.
9 *
10 * Warning: supports only the basic multilingual plane (BMP), i.e,
11 * Unicode characters between U+0000 and U+FFFF.
12 *
13 ******************************************************************************/
14
15 package edu.princeton.cs.algs4;
16
17 public class Alphabet {
18
19 /**
20 * The binary alphabet { 0, 1 }.
21 */
22 public static final Alphabet BINARY = new Alphabet("01");
23
24 /**
25 * The octal alphabet { 0, 1, 2, 3, 4, 5, 6, 7 }.
26 */
27 public static final Alphabet OCTAL = new Alphabet("01234567");
28
29 /**
30 * The decimal alphabet { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }.
31 */
32 public static final Alphabet DECIMAL = new Alphabet("0123456789");
33
34 /**
35 * The hexadecimal alphabet { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F }.
36 */
37 public static final Alphabet HEXADECIMAL = new Alphabet("0123456789ABCDEF");
38
39 /**
40 * The DNA alphabet { A, C, T, G }.
41 */
42 public static final Alphabet DNA = new Alphabet("ACGT");
43
44 /**
45 * The lowercase alphabet { a, b, c, ..., z }.
46 */
47 public static final Alphabet LOWERCASE = new Alphabet("abcdefghijklmnopqrstuvwxyz");
48
49 /**
50 * The uppercase alphabet { A, B, C, ..., Z }.
51 */
52
53 public static final Alphabet UPPERCASE = new Alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
54
55 /**
56 * The protein alphabet { A, C, D, E, F, G, H, I, K, L, M, N, P, Q, R, S, T, V, W, Y }.
57 */
58 public static final Alphabet PROTEIN = new Alphabet("ACDEFGHIKLMNPQRSTVWY");
59
60 /**
61 * The base-64 alphabet (64 characters).
62 */
63 public static final Alphabet BASE64 = new Alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
64
65 /**
66 * The ASCII alphabet (0-127).
67 */
68 public static final Alphabet ASCII = new Alphabet(128);
69
70 /**
71 * The extended ASCII alphabet (0-255).
72 */
73 public static final Alphabet EXTENDED_ASCII = new Alphabet(256);
74
75 /**
76 * The Unicode 16 alphabet (0-65,535).
77 */
78 public static final Alphabet UNICODE16 = new Alphabet(65536);
79
80
81 private char[] alphabet; // the characters in the alphabet
82 private int[] inverse; // indices
83 private final int R; // the radix of the alphabet
84
85 /**
86 * Initializes a new alphabet from the given set of characters.
87 *
88 * @param alpha the set of characters
89 */
90 public Alphabet(String alpha) {
91
92 // check that alphabet contains no duplicate chars
93 boolean[] unicode = new boolean[Character.MAX_VALUE];
94 for (int i = 0; i < alpha.length(); i++) {
95 char c = alpha.charAt(i);
96 if (unicode[c])
97 throw new IllegalArgumentException("Illegal alphabet: repeated character = '" + c + "'");
98 unicode[c] = true;
99 }
100
101 alphabet = alpha.toCharArray();
102 R = alpha.length();
103 inverse = new int[Character.MAX_VALUE];
104 for (int i = 0; i < inverse.length; i++)
105 inverse[i] = -1;
106
107 // can't use char since R can be as big as 65,536
108 for (int c = 0; c < R; c++)
109 inverse[alphabet[c]] = c;
110 }
111
112 /**
113 * Initializes a new alphabet using characters 0 through R-1.
114 *
115 * @param radix the number of characters in the alphabet (the radix R)
116 */
117 private Alphabet(int radix) {
118 this.R = radix;
119 alphabet = new char[R];
120 inverse = new int[R];
121
122 // can't use char since R can be as big as 65,536
123 for (int i = 0; i < R; i++)
124 alphabet[i] = (char) i;
125 for (int i = 0; i < R; i++)
126 inverse[i] = i;
127 }
128
129 /**
130 * Initializes a new alphabet using characters 0 through 255.
131 */
132 public Alphabet() {
133 this(256);
134 }
135
136 /**
137 * Returns true if the argument is a character in this alphabet.
138 *
139 * @param c the character
140 * @return {@code true} if {@code c} is a character in this alphabet;
141 * {@code false} otherwise
142 */
143 public boolean contains(char c) {
144 return inverse[c] != -1;
145 }
146
147 /**
148 * Returns the number of characters in this alphabet (the radix).
149 *
150 * @return the number of characters in this alphabet
151 * @deprecated Replaced by {@link #radix()}.
152 */
153 @Deprecated
154 public int R() {
155 return R;
156 }
157
158 /**
159 * Returns the number of characters in this alphabet (the radix).
160 *
161 * @return the number of characters in this alphabet
162 */
163 public int radix() {
164 return R;
165 }
166
167 /**
168 * Returns the binary logarithm of the number of characters in this alphabet.
169 *
170 * @return the binary logarithm (rounded up) of the number of characters in this alphabet
171 */
172 public int lgR() {
173 int lgR = 0;
174 for (int t = R-1; t >= 1; t /= 2)
175 lgR++;
176 return lgR;
177 }
178
179 /**
180 * Returns the index corresponding to the argument character.
181 *
182 * @param c the character
183 * @return the index corresponding to the character {@code c}
184 * @throws IllegalArgumentException unless {@code c} is a character in this alphabet
185 */
186 public int toIndex(char c) {
187 if (c >= inverse.length || inverse[c] == -1) {
188 throw new IllegalArgumentException("Character " + c + " not in alphabet");
189 }
190 return inverse[c];
191 }
192
193 /**
194 * Returns the indices corresponding to the argument characters.
195 *
196 * @param s the characters
197 * @return the indices corresponding to the characters {@code s}
198 * @throws IllegalArgumentException unless every character in {@code s}
199 * is a character in this alphabet
200 */
201 public int[] toIndices(String s) {
202 char[] source = s.toCharArray();
203 int[] target = new int[s.length()];
204 for (int i = 0; i < source.length; i++)
205 target[i] = toIndex(source[i]);
206 return target;
207 }
208
209 /**
210 * Returns the character corresponding to the argument index.
211 *
212 * @param index the index
213 * @return the character corresponding to the index {@code index}
214 * @throws IllegalArgumentException unless {@code 0 <= index < R}
215 */
216 public char toChar(int index) {
217 if (index < 0 || index >= R) {
218 throw new IndexOutOfBoundsException("Alphabet index out of bounds");
219 }
220 return alphabet[index];
221 }
222
223 /**
224 * Returns the characters corresponding to the argument indices.
225 *
226 * @param indices the indices
227 * @return the characters corresponding to the indices {@code indices}
228 * @throws IllegalArgumentException unless {@code 0 < indices[i] < R}
229 * for every {@code i}
230 */
231 public String toChars(int[] indices) {
232 StringBuilder s = new StringBuilder(indices.length);
233 for (int i = 0; i < indices.length; i++)
234 s.append(toChar(indices[i]));
235 return s.toString();
236 }
237
238 /**
239 * Unit tests the {@code Alphabet} data type.
240 *
241 * @param args the command-line arguments
242 */
243 public static void main(String[] args) {
244 int[] encoded1 = Alphabet.BASE64.toIndices("NowIsTheTimeForAllGoodMen");
245 String decoded1 = Alphabet.BASE64.toChars(encoded1);
246 StdOut.println(decoded1);
247
248 int[] encoded2 = Alphabet.DNA.toIndices("AACGAACGGTTTACCCCG");
249 String decoded2 = Alphabet.DNA.toChars(encoded2);
250 StdOut.println(decoded2);
251
252 int[] encoded3 = Alphabet.DECIMAL.toIndices("01234567890123456789");
253 String decoded3 = Alphabet.DECIMAL.toChars(encoded3);
254 StdOut.println(decoded3);
255 }
256 }
257
258 /******************************************************************************
259 * Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
260 *
261 * This file is part of algs4.jar, which accompanies the textbook
262 *
263 * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
264 * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
265 * http://algs4.cs.princeton.edu
266 *
267 *
268 * algs4.jar is free software: you can redistribute it and/or modify
269 * it under the terms of the GNU General Public License as published by
270 * the Free Software Foundation, either version 3 of the License, or
271 * (at your option) any later version.
272 *
273 * algs4.jar is distributed in the hope that it will be useful,
274 * but WITHOUT ANY WARRANTY; without even the implied warranty of
275 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
276 * GNU General Public License for more details.
277 *
278 * You should have received a copy of the GNU General Public License
279 * along with algs4.jar. If not, see http://www.gnu.org/licenses.
280 ******************************************************************************/
1 /******************************************************************************
2 * Compilation: javac Arbitrage.java
3 * Execution: java Arbitrage < input.txt
4 * Dependencies: EdgeWeightedDigraph.java DirectedEdge.java
5 * BellmanFordSP.java
6 * Data file: http://algs4.cs.princeton.edu/44sp/rates.txt
7 *
8 * Arbitrage detection.
9 *
10 * % more rates.txt
11 * 5
12 * USD 1 0.741 0.657 1.061 1.005
13 * EUR 1.349 1 0.888 1.433 1.366
14 * GBP 1.521 1.126 1 1.614 1.538
15 * CHF 0.942 0.698 0.619 1 0.953
16 * CAD 0.995 0.732 0.650 1.049 1
17 *
18 * % java Arbitrage < rates.txt
19 * 1000.00000 USD = 741.00000 EUR
20 * 741.00000 EUR = 1012.20600 CAD
21 * 1012.20600 CAD = 1007.14497 USD
22 *
23 ******************************************************************************/
24
25 package edu.princeton.cs.algs4;
26
27 /**
28 * The {@code Arbitrage} class provides a client that finds an arbitrage
29 * opportunity in a currency exchange table by constructing a
30 * complete-digraph representation of the exchange table and then finding
31 * a negative cycle in the digraph.
32 * <p>
33 * This implementation uses the Bellman-Ford algorithm to find a
34 * negative cycle in the complete digraph.
35 * The running time is proportional to <em>V</em><sup>3</sup> in the
36 * worst case, where <em>V</em> is the number of currencies.
37 * <p>
38 * For additional documentation,
39 * see <a href="http://algs4.cs.princeton.edu/44sp">Section 4.4</a> of
40 * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
41 *
42 * @author Robert Sedgewick
43 * @author Kevin Wayne
44 */
45 public class Arbitrage {
46
47 // this class cannot be instantiated
48 private Arbitrage() { }
49
50 /**
51 * Reads the currency exchange table from standard input and
52 * prints an arbitrage opportunity to standard output (if one exists).
53 *
54 * @param args the command-line arguments
55 */
56 public static void main(String[] args) {
57
58 // V currencies
59 int V = StdIn.readInt();
60 String[] name = new String[V];
61
62 // create complete network
63 EdgeWeightedDigraph G = new EdgeWeightedDigraph(V);
64 for (int v = 0; v < V; v++) {
65 name[v] = StdIn.readString();
66 for (int w = 0; w < V; w++) {
67 double rate = StdIn.readDouble();
68 DirectedEdge e = new DirectedEdge(v, w, -Math.log(rate));
69 G.addEdge(e);
70 }
71 }
72
73 // find negative cycle
74 BellmanFordSP spt = new BellmanFordSP(G, 0);
75 if (spt.hasNegativeCycle()) {
76 double stake = 1000.0;
77 for (DirectedEdge e : spt.negativeCycle()) {
78 StdOut.printf("%10.5f %s ", stake, name[e.from()]);
79 stake *= Math.exp(-e.weight());
80 StdOut.printf("= %10.5f %s\n", stake, name[e.to()]);
81 }
82 }
83 else {
84 StdOut.println("No arbitrage opportunity");
85 }
86 }
87
88 }
89
90 /******************************************************************************
91 * Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
92 *
93 * This file is part of algs4.jar, which accompanies the textbook
94 *
95 * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
96 * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
97 * http://algs4.cs.princeton.edu
98 *
99 *
100 * algs4.jar is free software: you can redistribute it and/or modify
101 * it under the terms of the GNU General Public License as published by
102 * the Free Software Foundation, either version 3 of the License, or
103 * (at your option) any later version.
104 *
105 * algs4.jar is distributed in the hope that it will be useful,
106 * but WITHOUT ANY WARRANTY; without even the implied warranty of
107 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
108 * GNU General Public License for more details.
109 *
110 * You should have received a copy of the GNU General Public License
111 * along with algs4.jar. If not, see http://www.gnu.org/licenses.
112 ******************************************************************************/
1 /******************************************************************************
2 * Compilation: javac Average.java
3 * Execution: java Average < data.txt
4 * Dependencies: StdIn.java StdOut.java
5 *
6 * Reads in a sequence of real numbers, and computes their average.
7 *
8 * % java Average
9 * 10.0 5.0 6.0
10 * 3.0 7.0 32.0
11 * [Ctrl-d]
12 * Average is 10.5
13 *
14 * Note [Ctrl-d] signifies the end of file on Unix.
15 * On windows use [Ctrl-z].
16 *
17 ******************************************************************************/
18
19 package edu.princeton.cs.algs4;
20
21 /**
22 * The {@code Average} class provides a client for reading in a sequence
23 * of real numbers and printing out their average.
24 * <p>
25 * For additional documentation, see <a href="http://algs4.cs.princeton.edu/11model">Section 1.1</a> of
26 * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
27 *
28 * @author Robert Sedgewick
29 * @author Kevin Wayne
30 */
31 public class Average {
32
33 // this class should not be instantiated
34 private Average() { }
35
36 /**
37 * Reads in a sequence of real numbers from standard input and prints
38 * out their average to standard output.
39 *
40 * @param args the command-line arguments
41 */
42 public static void main(String[] args) {
43 int count = 0; // number input values
44 double sum = 0.0; // sum of input values
45
46 // read data and compute statistics
47 while (!StdIn.isEmpty()) {
48 double value = StdIn.readDouble();
49 sum += value;
50 count++;
51 }
52
53 // compute the average
54 double average = sum / count;
55
56 // print results
57 StdOut.println("Average is " + average);
58 }
59 }
60
61 /******************************************************************************
62 * Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
63 *
64 * This file is part of algs4.jar, which accompanies the textbook
65 *
66 * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
67 * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
68 * http://algs4.cs.princeton.edu
69 *
70 *
71 * algs4.jar is free software: you can redistribute it and/or modify
72 * it under the terms of the GNU General Public License as published by
73 * the Free Software Foundation, either version 3 of the License, or
74 * (at your option) any later version.
75 *
76 * algs4.jar is distributed in the hope that it will be useful,
77 * but WITHOUT ANY WARRANTY; without even the implied warranty of
78 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
79 * GNU General Public License for more details.
80 *
81 * You should have received a copy of the GNU General Public License
82 * along with algs4.jar. If not, see http://www.gnu.org/licenses.
83 ******************************************************************************/
1 /******************************************************************************
2 * Compilation: javac Bag.java
3 * Execution: java Bag < input.txt
4 * Dependencies: StdIn.java StdOut.java
5 *
6 * A generic bag or multiset, implemented using a singly-linked list.
7 *
8 * % more tobe.txt
9 * to be or not to - be - - that - - - is
10 *
11 * % java Bag < tobe.txt
12 * size of bag = 14
13 * is
14 * -
15 * -
16 * -
17 * that
18 * -
19 * -
20 * be
21 * -
22 * to
23 * not
24 * or
25 * be
26 * to
27 *
28 ******************************************************************************/
29
30 package edu.princeton.cs.algs4;
31
32 import java.util.Iterator;
33 import java.util.NoSuchElementException;
34
35 /**
36 * The {@code Bag} class represents a bag (or multiset) of
37 * generic items. It supports insertion and iterating over the
38 * items in arbitrary order.
39 * <p>
40 * This implementation uses a singly-linked list with a static nested class Node.
41 * See {@link LinkedBag} for the version from the
42 * textbook that uses a non-static nested class.
43 * The <em>add</em>, <em>isEmpty</em>, and <em>size</em> operations
44 * take constant time. Iteration takes time proportional to the number of items.
45 * <p>
46 * For additional documentation, see <a href="http://algs4.cs.princeton.edu/13stacks">Section 1.3</a> of
47 * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
48 *
49 * @author Robert Sedgewick
50 * @author Kevin Wayne
51 *
52 * @param <Item> the generic type of an item in this bag
53 */
54 public class Bag<Item> implements Iterable<Item> {
55 private Node<Item> first; // beginning of bag
56 private int n; // number of elements in bag
57
58 // helper linked list class
59 private static class Node<Item> {
60 private Item item;
61 private Node<Item> next;
62 }
63
64 /**
65 * Initializes an empty bag.
66 */
67 public Bag() {
68 first = null;
69 n = 0;
70 }
71
72 /**
73 * Returns true if this bag is empty.
74 *
75 * @return {@code true} if this bag is empty;
76 * {@code false} otherwise
77 */
78 public boolean isEmpty() {
79 return first == null;
80 }
81
82 /**
83 * Returns the number of items in this bag.
84 *
85 * @return the number of items in this bag
86 */
87 public int size() {
88 return n;
89 }
90
91 /**
92 * Adds the item to this bag.
93 *
94 * @param item the item to add to this bag
95 */
96 public void add(Item item) {
97 Node<Item> oldfirst = first;
98 first = new Node<Item>();
99 first.item = item;
100 first.next = oldfirst;
101 n++;
102 }
103
104
105 /**
106 * Returns an iterator that iterates over the items in this bag in arbitrary order.
107 *
108 * @return an iterator that iterates over the items in this bag in arbitrary order
109 */
110 public Iterator<Item> iterator() {
111 return new ListIterator<Item>(first);
112 }
113
114 // an iterator, doesn't implement remove() since it's optional
115 private class ListIterator<Item> implements Iterator<Item> {
116 private Node<Item> current;
117
118 public ListIterator(Node<Item> first) {
119 current = first;
120 }
121
122 public boolean hasNext() { return current != null; }
123 public void remove() { throw new UnsupportedOperationException(); }
124
125 public Item next() {
126 if (!hasNext()) throw new NoSuchElementException();
127 Item item = current.item;
128 current = current.next;
129 return item;
130 }
131 }
132
133 /**
134 * Unit tests the {@code Bag} data type.
135 *
136 * @param args the command-line arguments
137 */
138 public static void main(String[] args) {
139 Bag<String> bag = new Bag<String>();
140 while (!StdIn.isEmpty()) {
141 String item = StdIn.readString();
142 bag.add(item);
143 }
144
145 StdOut.println("size of bag = " + bag.size());
146 for (String s : bag) {
147 StdOut.println(s);
148 }
149 }
150
151 }
152
153 /******************************************************************************
154 * Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
155 *
156 * This file is part of algs4.jar, which accompanies the textbook
157 *
158 * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
159 * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
160 * http://algs4.cs.princeton.edu
161 *
162 *
163 * algs4.jar is free software: you can redistribute it and/or modify
164 * it under the terms of the GNU General Public License as published by
165 * the Free Software Foundation, either version 3 of the License, or
166 * (at your option) any later version.
167 *
168 * algs4.jar is distributed in the hope that it will be useful,
169 * but WITHOUT ANY WARRANTY; without even the implied warranty of
170 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
171 * GNU General Public License for more details.
172 *
173 * You should have received a copy of the GNU General Public License
174 * along with algs4.jar. If not, see http://www.gnu.org/licenses.
175 ******************************************************************************/
1 /******************************************************************************
2 * Compilation: javac BinaryDump.java
3 * Execution: java BinaryDump N < file
4 * Dependencies: BinaryStdIn.java
5 * Data file: http://introcs.cs.princeton.edu/stdlib/abra.txt
6 *
7 * Reads in a binary file and writes out the bits, N per line.
8 *
9 * % more abra.txt
10 * ABRACADABRA!
11 *
12 * % java BinaryDump 16 < abra.txt
13 * 0100000101000010
14 * 0101001001000001
15 * 0100001101000001
16 * 0100010001000001
17 * 0100001001010010
18 * 0100000100100001
19 * 96 bits
20 *
21 ******************************************************************************/
22
23 package edu.princeton.cs.algs4;
24
25 /**
26 * The {@code BinaryDump} class provides a client for displaying the contents
27 * of a binary file in binary.
28 * <p>
29 * For more full-featured versions, see the Unix utilities
30 * {@code od} (octal dump) and {@code hexdump} (hexadecimal dump).
31 * <p>
32 * For additional documentation,
33 * see <a href="http://algs4.cs.princeton.edu/55compress">Section 5.5</a> of
34 * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
35 * <p>
36 * See also {@link HexDump} and {@link PictureDump}.
37 *
38 * @author Robert Sedgewick
39 * @author Kevin Wayne
40 */
41 public class BinaryDump {
42
43 // Do not instantiate.
44 private BinaryDump() { }
45
46 /**
47 * Reads in a sequence of bytes from standard input and writes
48 * them to standard output in binary, k bits per line,
49 * where k is given as a command-line integer (defaults
50 * to 16 if no integer is specified); also writes the number
51 * of bits.
52 *
53 * @param args the command-line arguments
54 */
55 public static void main(String[] args) {
56 int bitsPerLine = 16;
57 if (args.length == 1) {
58 bitsPerLine = Integer.parseInt(args[0]);
59 }
60
61 int count;
62 for (count = 0; !BinaryStdIn.isEmpty(); count++) {
63 if (bitsPerLine == 0) {
64 BinaryStdIn.readBoolean();
65 continue;
66 }
67 else if (count != 0 && count % bitsPerLine == 0) StdOut.println();
68 if (BinaryStdIn.readBoolean()) StdOut.print(1);
69 else StdOut.print(0);
70 }
71 if (bitsPerLine != 0) StdOut.println();
72 StdOut.println(count + " bits");
73 }
74 }
75
76 /******************************************************************************
77 * Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
78 *
79 * This file is part of algs4.jar, which accompanies the textbook
80 *
81 * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
82 * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
83 * http://algs4.cs.princeton.edu
84 *
85 *
86 * algs4.jar is free software: you can redistribute it and/or modify
87 * it under the terms of the GNU General Public License as published by
88 * the Free Software Foundation, either version 3 of the License, or
89 * (at your option) any later version.
90 *
91 * algs4.jar is distributed in the hope that it will be useful,
92 * but WITHOUT ANY WARRANTY; without even the implied warranty of
93 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
94 * GNU General Public License for more details.
95 *
96 * You should have received a copy of the GNU General Public License
97 * along with algs4.jar. If not, see http://www.gnu.org/licenses.
98 ******************************************************************************/
1 /******************************************************************************
2 * Compilation: javac BinaryInsertion.java
3 * Execution: java BinaryInsertion < input.txt
4 * Dependencies: StdOut.java StdIn.java
5 * Data files: http://algs4.cs.princeton.edu/21sort/tiny.txt
6 * http://algs4.cs.princeton.edu/21sort/words3.txt
7 *
8 * Sorts a sequence of strings from standard input using
9 * binary insertion sort with half exchanges.
10 *
11 * % more tiny.txt
12 * S O R T E X A M P L E
13 *
14 * % java BinaryInsertion < tiny.txt
15 * A E E L M O P R S T X [ one string per line ]
16 *
17 * % more words3.txt
18 * bed bug dad yes zoo ... all bad yet
19 *
20 * % java BinaryInsertion < words3.txt
21 * all bad bed bug dad ... yes yet zoo [ one string per line ]
22 *
23 ******************************************************************************/
24
25 package edu.princeton.cs.algs4;
26
27 /**
28 * The {@code BinaryInsertion} class provides a static method for sorting an
29 * array using an optimized binary insertion sort with half exchanges.
30 * <p>
31 * This implementation makes ~ n lg n compares for any array of length n.
32 * However, in the worst case, the running time is quadratic because the
33 * number of array accesses can be proportional to n^2 (e.g, if the array
34 * is reverse sorted). As such, it is not suitable for sorting large
35 * arrays (unless the number of inversions is small).
36 * <p>
37 * The sorting algorithm is stable and uses O(1) extra memory.
38 * <p>
39 * For additional documentation, see <a href="http://algs4.cs.princeton.edu/21elementary">Section 2.1</a> of
40 * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
41 *
42 * @author Ivan Pesin
43 * @author Robert Sedgewick
44 * @author Kevin Wayne
45 */
46 public class BinaryInsertion {
47
48 // This class should not be instantiated.
49 private BinaryInsertion() { }
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 for (int i = 1; i < n; i++) {
58
59 // binary search to determine index j at which to insert a[i]
60 Comparable v = a[i];
61 int lo = 0, hi = i;
62 while (lo < hi) {
63 int mid = lo + (hi - lo) / 2;
64 if (less(v, a[mid])) hi = mid;
65 else lo = mid + 1;
66 }
67
68 // insetion sort with "half exchanges"
69 // (insert a[i] at index j and shift a[j], ..., a[i-1] to right)
70 for (int j = i; j > lo; --j)
71 a[j] = a[j-1];
72 a[lo] = v;
73 }
74 assert isSorted(a);
75 }
76
77
78
79 /***************************************************************************
80 * Helper sorting function.
81 ***************************************************************************/
82
83 // is v < w ?
84 private static boolean less(Comparable v, Comparable w) {
85 return v.compareTo(w) < 0;
86 }
87
88 /***************************************************************************
89 * Check if array is sorted - useful for debugging.
90 ***************************************************************************/
91 private static boolean isSorted(Comparable[] a) {
92 return isSorted(a, 0, a.length - 1);
93 }
94
95 // is the array sorted from a[lo] to a[hi]
96 private static boolean isSorted(Comparable[] a, int lo, int hi) {
97 for (int i = lo+1; i <= hi; i++)
98 if (less(a[i], a[i-1])) return false;
99 return true;
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; insertion sorts them;
111 * and prints them to standard output in ascending order.
112 *
113 * @param args the command-line arguments
114 */
115 public static void main(String[] args) {
116 String[] a = StdIn.readAllStrings();
117 BinaryInsertion.sort(a);
118 show(a);
119 }
120 }
121
122 /******************************************************************************
123 * Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
124 *
125 * This file is part of algs4.jar, which accompanies the textbook
126 *
127 * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
128 * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
129 * http://algs4.cs.princeton.edu
130 *
131 *
132 * algs4.jar is free software: you can redistribute it and/or modify
133 * it under the terms of the GNU General Public License as published by
134 * the Free Software Foundation, either version 3 of the License, or
135 * (at your option) any later version.
136 *
137 * algs4.jar is distributed in the hope that it will be useful,
138 * but WITHOUT ANY WARRANTY; without even the implied warranty of
139 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
140 * GNU General Public License for more details.
141 *
142 * You should have received a copy of the GNU General Public License
143 * along with algs4.jar. If not, see http://www.gnu.org/licenses.
144 ******************************************************************************/
1 /******************************************************************************
2 * Compilation: javac BinarySearch.java
3 * Execution: java BinarySearch whitelist.txt < input.txt
4 * Dependencies: In.java StdIn.java StdOut.java
5 * Data files: http://algs4.cs.princeton.edu/11model/tinyW.txt
6 * http://algs4.cs.princeton.edu/11model/tinyT.txt
7 * http://algs4.cs.princeton.edu/11model/largeW.txt
8 * http://algs4.cs.princeton.edu/11model/largeT.txt
9 *
10 * % java BinarySearch tinyW.txt < tinyT.txt
11 * 50
12 * 99
13 * 13
14 *
15 * % java BinarySearch largeW.txt < largeT.txt | more
16 * 499569
17 * 984875
18 * 295754
19 * 207807
20 * 140925
21 * 161828
22 * [367,966 total values]
23 *
24 ******************************************************************************/
25
26 package edu.princeton.cs.algs4;
27
28 import java.util.Arrays;
29
30 /**
31 * The {@code BinarySearch} class provides a static method for binary
32 * searching for an integer in a sorted array of integers.
33 * <p>
34 * The <em>indexOf</em> operations takes logarithmic time in the worst case.
35 * <p>
36 * For additional documentation, see <a href="http://algs4.cs.princeton.edu/11model">Section 1.1</a> of
37 * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
38 *
39 * @author Robert Sedgewick
40 * @author Kevin Wayne
41 */
42 public class BinarySearch {
43
44 /**
45 * This class should not be instantiated.
46 */
47 private BinarySearch() { }
48
49 /**
50 * Returns the index of the specified key in the specified array.
51 *
52 * @param a the array of integers, must be sorted in ascending order
53 * @param key the search key
54 * @return index of key in array {@code a} if present; {@code -1} otherwise
55 */
56 public static int indexOf(int[] a, int key) {
57 int lo = 0;
58 int hi = a.length - 1;
59 while (lo <= hi) {
60 // Key is in a[lo..hi] or not present.
61 int mid = lo + (hi - lo) / 2;
62 if (key < a[mid]) hi = mid - 1;
63 else if (key > a[mid]) lo = mid + 1;
64 else return mid;
65 }
66 return -1;
67 }
68
69 /**
70 * Returns the index of the specified key in the specified array.
71 * This function is poorly named because it does not give the <em>rank</em>
72 * if the array has duplicate keys or if the key is not in the array.
73 *
74 * @param key the search key
75 * @param a the array of integers, must be sorted in ascending order
76 * @return index of key in array {@code a} if present; {@code -1} otherwise
77 * @deprecated Replaced by {@link #indexOf(int[], int)}.
78 */
79 @Deprecated
80 public static int rank(int key, int[] a) {
81 return indexOf(a, key);
82 }
83
84 /**
85 * Reads in a sequence of integers from the whitelist file, specified as
86 * a command-line argument; reads in integers from standard input;
87 * prints to standard output those integers that do <em>not</em> appear in the file.
88 *
89 * @param args the command-line arguments
90 */
91 public static void main(String[] args) {
92
93 // read the integers from a file
94 In in = new In(args[0]);
95 int[] whitelist = in.readAllInts();
96
97 // sort the array
98 Arrays.sort(whitelist);
99
100 // read integer key from standard input; print if not in whitelist
101 while (!StdIn.isEmpty()) {
102 int key = StdIn.readInt();
103 if (BinarySearch.indexOf(whitelist, key) == -1)
104 StdOut.println(key);
105 }
106 }
107 }
108
109 /******************************************************************************
110 * Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
111 *
112 * This file is part of algs4.jar, which accompanies the textbook
113 *
114 * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
115 * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
116 * http://algs4.cs.princeton.edu
117 *
118 *
119 * algs4.jar is free software: you can redistribute it and/or modify
120 * it under the terms of the GNU General Public License as published by
121 * the Free Software Foundation, either version 3 of the License, or
122 * (at your option) any later version.
123 *
124 * algs4.jar is distributed in the hope that it will be useful,
125 * but WITHOUT ANY WARRANTY; without even the implied warranty of
126 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
127 * GNU General Public License for more details.
128 *
129 * You should have received a copy of the GNU General Public License
130 * along with algs4.jar. If not, see http://www.gnu.org/licenses.
131 ******************************************************************************/
1 /******************************************************************************
2 * Compilation: javac BinaryStdOut.java
3 * Execution: java BinaryStdOut
4 * Dependencies: none
5 *
6 * Write binary data to standard output, either one 1-bit boolean,
7 * one 8-bit char, one 32-bit int, one 64-bit double, one 32-bit float,
8 * or one 64-bit long at a time.
9 *
10 * The bytes written are not aligned.
11 *
12 ******************************************************************************/
13
14 package edu.princeton.cs.algs4;
15
16 import java.io.BufferedOutputStream;
17 import java.io.IOException;
18
19 /**
20 * <i>Binary standard output</i>. This class provides methods for converting
21 * primtive type variables ({@code boolean}, {@code byte}, {@code char},
22 * {@code int}, {@code long}, {@code float}, and {@code double})
23 * to sequences of bits and writing them to standard output.
24 * Uses big-endian (most-significant byte first).
25 * <p>
26 * The client must {@code flush()} the output stream when finished writing bits.
27 * <p>
28 * The client should not intermixing calls to {@code BinaryStdOut} with calls
29 * to {@code StdOut} or {@code System.out}; otherwise unexpected behavior
30 * will result.
31 *
32 * @author Robert Sedgewick
33 * @author Kevin Wayne
34 */
35 public final class BinaryStdOut {
36 private static BufferedOutputStream out = new BufferedOutputStream(System.out);
37
38 private static int buffer; // 8-bit buffer of bits to write out
39 private static int n; // number of bits remaining in buffer
40
41 // don't instantiate
42 private BinaryStdOut() { }
43
44 /**
45 * Write the specified bit to standard output.
46 */
47 private static void writeBit(boolean bit) {
48 // add bit to buffer
49 buffer <<= 1;
50 if (bit) buffer |= 1;
51
52 // if buffer is full (8 bits), write out as a single byte
53 n++;
54 if (n == 8) clearBuffer();
55 }
56
57 /**
58 * Write the 8-bit byte to standard output.
59 */
60 private static void writeByte(int x) {
61 assert x >= 0 && x < 256;
62
63 // optimized if byte-aligned
64 if (n == 0) {
65 try {
66 out.write(x);
67 }
68 catch (IOException e) {
69 e.printStackTrace();
70 }
71 return;
72 }
73
74 // otherwise write one bit at a time
75 for (int i = 0; i < 8; i++) {
76 boolean bit = ((x >>> (8 - i - 1)) & 1) == 1;
77 writeBit(bit);
78 }
79 }
80
81 // write out any remaining bits in buffer to standard output, padding with 0s
82 private static void clearBuffer() {
83 if (n == 0) return;
84 if (n > 0) buffer <<= (8 - n);
85 try {
86 out.write(buffer);
87 }
88 catch (IOException e) {
89 e.printStackTrace();
90 }
91 n = 0;
92 buffer = 0;
93 }
94
95 /**
96 * Flush standard output, padding 0s if number of bits written so far
97 * is not a multiple of 8.
98 */
99 public static void flush() {
100 clearBuffer();
101 try {
102 out.flush();
103 }
104 catch (IOException e) {
105 e.printStackTrace();
106 }
107 }
108
109 /**
110 * Flush and close standard output. Once standard output is closed, you can no
111 * longer write bits to it.
112 */
113 public static void close() {
114 flush();
115 try {
116 out.close();
117 }
118 catch (IOException e) {
119 e.printStackTrace();
120 }
121 }
122
123
124 /**
125 * Write the specified bit to standard output.
126 * @param x the {@code boolean} to write.
127 */
128 public static void write(boolean x) {
129 writeBit(x);
130 }
131
132 /**
133 * Write the 8-bit byte to standard output.
134 * @param x the {@code byte} to write.
135 */
136 public static void write(byte x) {
137 writeByte(x & 0xff);
138 }
139
140 /**
141 * Write the 32-bit int to standard output.
142 * @param x the {@code int} to write.
143 */
144 public static void write(int x) {
145 writeByte((x >>> 24) & 0xff);
146 writeByte((x >>> 16) & 0xff);
147 writeByte((x >>> 8) & 0xff);
148 writeByte((x >>> 0) & 0xff);
149 }
150
151 /**
152 * Write the r-bit int to standard output.
153 * @param x the {@code int} to write.
154 * @param r the number of relevant bits in the char.
155 * @throws IllegalArgumentException if {@code r} is not between 1 and 32.
156 * @throws IllegalArgumentException if {@code x} is not between 0 and 2<sup>r</sup> - 1.
157 */
158 public static void write(int x, int r) {
159 if (r == 32) {
160 write(x);
161 return;
162 }
163 if (r < 1 || r > 32) throw new IllegalArgumentException("Illegal value for r = " + r);
164 if (x < 0 || x >= (1 << r)) throw new IllegalArgumentException("Illegal " + r + "-bit char = " + x);
165 for (int i = 0; i < r; i++) {
166 boolean bit = ((x >>> (r - i - 1)) & 1) == 1;
167 writeBit(bit);
168 }
169 }
170
171
172
173
174
175 /**
176 * Write the 64-bit double to standard output.
177 * @param x the {@code double} to write.
178 */
179 public static void write(double x) {
180 write(Double.doubleToRawLongBits(x));
181 }
182
183 /**
184 * Write the 64-bit long to standard output.
185 * @param x the {@code long} to write.
186 */
187 public static void write(long x) {
188 writeByte((int) ((x >>> 56) & 0xff));
189 writeByte((int) ((x >>> 48) & 0xff));
190 writeByte((int) ((x >>> 40) & 0xff));
191 writeByte((int) ((x >>> 32) & 0xff));
192 writeByte((int) ((x >>> 24) & 0xff));
193 writeByte((int) ((x >>> 16) & 0xff));
194 writeByte((int) ((x >>> 8) & 0xff));
195 writeByte((int) ((x >>> 0) & 0xff));
196 }
197
198 /**
199 * Write the 32-bit float to standard output.
200 * @param x the {@code float} to write.
201 */
202 public static void write(float x) {
203 write(Float.floatToRawIntBits(x));
204 }
205
206 /**
207 * Write the 16-bit int to standard output.
208 * @param x the {@code short} to write.
209 */
210 public static void write(short x) {
211 writeByte((x >>> 8) & 0xff);
212 writeByte((x >>> 0) & 0xff);
213 }
214
215 /**
216 * Write the 8-bit char to standard output.
217 * @param x the {@code char} to write.
218 * @throws IllegalArgumentException if {@code x} is not betwen 0 and 255.
219 */
220 public static void write(char x) {
221 if (x < 0 || x >= 256) throw new IllegalArgumentException("Illegal 8-bit char = " + x);
222 writeByte(x);
223 }
224
225 /**
226 * Write the r-bit char to standard output.
227 * @param x the {@code char} to write.
228 * @param r the number of relevant bits in the char.
229 * @throws IllegalArgumentException if {@code r} is not between 1 and 16.
230 * @throws IllegalArgumentException if {@code x} is not between 0 and 2<sup>r</sup> - 1.
231 */
232 public static void write(char x, int r) {
233 if (r == 8) {
234 write(x);
235 return;
236 }
237 if (r < 1 || r > 16) throw new IllegalArgumentException("Illegal value for r = " + r);
238 if (x >= (1 << r)) throw new IllegalArgumentException("Illegal " + r + "-bit char = " + x);
239 for (int i = 0; i < r; i++) {
240 boolean bit = ((x >>> (r - i - 1)) & 1) == 1;
241 writeBit(bit);
242 }
243 }
244
245 /**
246 * Write the string of 8-bit characters to standard output.
247 * @param s the {@code String} to write.
248 * @throws IllegalArgumentException if any character in the string is not
249 * between 0 and 255.
250 */
251 public static void write(String s) {
252 for (int i = 0; i < s.length(); i++)
253 write(s.charAt(i));
254 }
255
256 /**
257 * Write the String of r-bit characters to standard output.
258 * @param s the {@code String} to write.
259 * @param r the number of relevants bits in each character.
260 * @throws IllegalArgumentException if r is not between 1 and 16.
261 * @throws IllegalArgumentException if any character in the string is not
262 * between 0 and 2<sup>r</sup> - 1.
263 */
264 public static void write(String s, int r) {
265 for (int i = 0; i < s.length(); i++)
266 write(s.charAt(i), r);
267 }
268
269 /**
270 * Test client.
271 *
272 * @param args the command-line arguments
273 */
274 public static void main(String[] args) {
275 int m = Integer.parseInt(args[0]);
276
277 // write n integers to binary standard output
278 for (int i = 0; i < m; i++) {
279 BinaryStdOut.write(i);
280 }
281 BinaryStdOut.flush();
282 }
283
284 }
285
286 /******************************************************************************
287 * Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
288 *
289 * This file is part of algs4.jar, which accompanies the textbook
290 *
291 * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
292 * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
293 * http://algs4.cs.princeton.edu
294 *
295 *
296 * algs4.jar is free software: you can redistribute it and/or modify
297 * it under the terms of the GNU General Public License as published by
298 * the Free Software Foundation, either version 3 of the License, or
299 * (at your option) any later version.
300 *
301 * algs4.jar is distributed in the hope that it will be useful,
302 * but WITHOUT ANY WARRANTY; without even the implied warranty of
303 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 * GNU General Public License for more details.
305 *
306 * You should have received a copy of the GNU General Public License
307 * along with algs4.jar. If not, see http://www.gnu.org/licenses.
308 ******************************************************************************/
1 /******************************************************************************
2 * Compilation: javac BinomialMinPQ.java
3 * Execution:
4 *
5 * A binomial heap.
6 *
7 ******************************************************************************/
8
9 package edu.princeton.cs.algs4;
10
11 import java.util.Iterator;
12 import java.util.Comparator;
13 import java.util.NoSuchElementException;
14
15 /**
16 * The BinomialMinPQ class represents a priority queue of generic keys.
17 * It supports the usual insert and delete-the-minimum operations,
18 * along with the merging of two heaps together.
19 * It also supports methods for peeking at the minimum key,
20 * testing if the priority queue is empty, and iterating through
21 * the keys.
22 * It is possible to build the priority queue using a Comparator.
23 * If not, the natural order relation between the keys will be used.
24 *
25 * This implementation uses a binomial heap.
26 * The insert, delete-the-minimum, union, min-key
27 * and size operations take logarithmic time.
28 * The is-empty and constructor operations take constant time.
29 *
30 * @author Tristan Claverie
31 */
32 public class BinomialMinPQ<Key> implements Iterable<Key> {
33 private Node head; //head of the list of roots
34 private final Comparator<Key> comp; //Comparator over the keys
35
36 //Represents a Node of a Binomial Tree
37 private class Node {
38 Key key; //Key contained by the Node
39 int order; //The order of the Binomial Tree rooted by this Node
40 Node child, sibling; //child and sibling of this Node
41 }
42
43 /**
44 * Initializes an empty priority queue
45 * Worst case is O(1)
46 */
47 public BinomialMinPQ() {
48 comp = new MyComparator();
49 }
50
51 /**
52 * Initializes an empty priority queue using the given Comparator
53 * Worst case is O(1)
54 * @param C a comparator over the keys
55 */
56 public BinomialMinPQ(Comparator<Key> C) {
57 comp = C;
58 }
59
60 /**
61 * Initializes a priority queue with given keys
62 * Worst case is O(n*log(n))
63 * @param a an array of keys
64 */
65 public BinomialMinPQ(Key[] a) {
66 comp = new MyComparator();
67 for (Key k : a) insert(k);
68 }
69
70 /**
71 * Initializes a priority queue with given keys using the given Comparator
72 * Worst case is O(n*log(n))
73 * @param C a comparator over the keys
74 * @param a an array of keys
75 */
76 public BinomialMinPQ(Comparator<Key> C, Key[] a) {
77 comp = C;
78 for (Key k : a) insert(k);
79 }
80
81 /**
82 * Whether the priority queue is empty
83 * Worst case is O(1)
84 * @return true if the priority queue is empty, false if not
85 */
86 public boolean isEmpty() {
87 return head == null;
88 }
89
90 /**
91 * Number of elements currently on the priority queue
92 * Worst case is O(log(n))
93 * @throws java.lang.ArithmeticException if there are more than 2^63-1 elements in the queue
94 * @return the number of elements on the priority queue
95 */
96 public int size() {
97 int result = 0, tmp;
98 for (Node node = head; node != null; node = node.sibling) {
99 if (node.order > 30) { throw new ArithmeticException("The number of elements cannot be evaluated, but the priority queue is still valid."); }
100 tmp = 1 << node.order;
101 result |= tmp;
102 }
103 return result;
104 }
105
106 /**
107 * Puts a Key in the heap
108 * Worst case is O(log(n))
109 * @param key a Key
110 */
111 public void insert(Key key) {
112 Node x = new Node();
113 x.key = key;
114 x.order = 0;
115 BinomialMinPQ<Key> H = new BinomialMinPQ<Key>(); //The Comparator oh the H heap is not used
116 H.head = x;
117 this.head = this.union(H).head;
118 }
119
120 /**
121 * Get the minimum key currently in the queue
122 * Worst case is O(log(n))
123 * @throws java.util.NoSuchElementException if the priority queue is empty
124 * @return the minimum key currently in the priority queue
125 */
126 public Key minKey() {
127 if (isEmpty()) throw new NoSuchElementException("Priority queue is empty");
128 Node min = head;
129 Node current = head;
130 while (current.sibling != null) {
131 min = (greater(min.key, current.sibling.key)) ? current : min;
132 current = current.sibling;
133 }
134 return min.key;
135 }
136
137 /**
138 * Deletes the minimum key
139 * Worst case is O(log(n))
140 * @throws java.util.NoSuchElementException if the priority queue is empty
141 * @return the minimum key
142 */
143 public Key delMin() {
144 if(isEmpty()) throw new NoSuchElementException("Priority queue is empty");
145 Node min = eraseMin();
146 Node x = (min.child == null) ? min : min.child;
147 if (min.child != null) {
148 min.child = null;
149 Node prevx = null, nextx = x.sibling;
150 while (nextx != null) {
151 x.sibling = prevx;
152 prevx = x;
153 x = nextx;nextx = nextx.sibling;
154 }
155 x.sibling = prevx;
156 BinomialMinPQ<Key> H = new BinomialMinPQ<Key>();
157 H.head = x;
158 head = union(H).head;
159 }
160 return min.key;
161 }
162
163 /**
164 * Merges two Binomial heaps together
165 * This operation is destructive
166 * Worst case is O(log(n))
167 * @param heap a Binomial Heap to be merged with the current heap
168 * @throws java.lang.IllegalArgumentException if the heap in parameter is null
169 * @return the union of two heaps
170 */
171 public BinomialMinPQ<Key> union(BinomialMinPQ<Key> heap) {
172 if (heap == null) throw new IllegalArgumentException("Cannot merge a Binomial Heap with null");
173 this.head = merge(new Node(), this.head, heap.head).sibling;
174 Node x = this.head;
175 Node prevx = null, nextx = x.sibling;
176 while (nextx != null) {
177 if (x.order < nextx.order ||
178 (nextx.sibling != null && nextx.sibling.order == x.order)) {
179 prevx = x; x = nextx;
180 } else if (greater(nextx.key, x.key)) {
181 x.sibling = nextx.sibling;
182 link(nextx, x);
183 } else {
184 if (prevx == null) { this.head = nextx; }
185 else { prevx.sibling = nextx; }
186 link(x, nextx);
187 x = nextx;
188 }
189 nextx = x.sibling;
190 }
191 return this;
192 }
193
194 /*************************************************
195 * General helper functions
196 ************************************************/
197
198 //Compares two keys
199 private boolean greater(Key n, Key m) {
200 if (n == null) return false;
201 if (m == null) return true;
202 return comp.compare(n, m) > 0;
203 }
204
205 //Assuming root1 holds a greater key than root2, root2 becomes the new root
206 private void link(Node root1, Node root2) {
207 root1.sibling = root2.child;
208 root2.child = root1;
209 root2.order++;
210 }
211
212 //Deletes and return the node containing the minimum key
213 private Node eraseMin() {
214 Node min = head;
215 Node previous = null;
216 Node current = head;
217 while (current.sibling != null) {
218 if (greater(min.key, current.sibling.key)) {
219 previous = current;
220 min = current.sibling;
221 }
222 current = current.sibling;
223 }
224 previous.sibling = min.sibling;
225 if (min == head) head = min.sibling;
226 return min;
227 }
228
229 /**************************************************
230 * Functions for inserting a key in the heap
231 *************************************************/
232
233 //Merges two root lists into one, there can be up to 2 Binomial Trees of same order
234 private Node merge(Node h, Node x, Node y) {
235 if (x == null && y == null) return h;
236 else if (x == null) h.sibling = merge(y, null, y.sibling);
237 else if (y == null) h.sibling = merge(x, x.sibling, null);
238 else if (x.order < y.order) h.sibling = merge(x, x.sibling, y);
239 else h.sibling = merge(y, x, y.sibling);
240 return h;
241 }
242
243 /******************************************************************
244 * Iterator
245 *****************************************************************/
246
247 /**
248 * Gets an Iterator over the keys in the priority queue in ascending order
249 * The Iterator does not implement the remove() method
250 * iterator() : Worst case is O(n)
251 * next() : Worst case is O(log(n))
252 * hasNext() : Worst case is O(1)
253 * @return an Iterator over the keys in the priority queue in ascending order
254 */
255 public Iterator<Key> iterator() {
256 return new MyIterator();
257 }
258
259 private class MyIterator implements Iterator<Key> {
260 BinomialMinPQ<Key> data;
261
262 //Constructor clones recursively the elements in the queue
263 //It takes linear time
264 public MyIterator() {
265 data = new BinomialMinPQ<Key>(comp);
266 data.head = clone(head, false, false, null);
267 }
268
269 private Node clone(Node x, boolean isParent, boolean isChild, Node parent) {
270 if (x == null) return null;
271 Node node = new Node();
272 node.key = x.key;
273 node.sibling = clone(x.sibling, false, false, parent);
274 node.child = clone(x.child, false, true, node);
275 return node;
276 }
277
278 public boolean hasNext() {
279 return !data.isEmpty();
280 }
281
282 public Key next() {
283 if (!hasNext()) throw new NoSuchElementException();
284 return data.delMin();
285 }
286
287 public void remove() {
288 throw new UnsupportedOperationException();
289 }
290 }
291
292 /***************************
293 * Comparator
294 **************************/
295
296 //default Comparator
297 private class MyComparator implements Comparator<Key> {
298 @Override
299 public int compare(Key key1, Key key2) {
300 return ((Comparable<Key>) key1).compareTo(key2);
301 }
302 }
303
304 }
305
306 /******************************************************************************
307 * Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
308 *
309 * This file is part of algs4.jar, which accompanies the textbook
310 *
311 * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
312 * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
313 * http://algs4.cs.princeton.edu
314 *
315 *
316 * algs4.jar is free software: you can redistribute it and/or modify
317 * it under the terms of the GNU General Public License as published by
318 * the Free Software Foundation, either version 3 of the License, or
319 * (at your option) any later version.
320 *
321 * algs4.jar is distributed in the hope that it will be useful,
322 * but WITHOUT ANY WARRANTY; without even the implied warranty of
323 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
324 * GNU General Public License for more details.
325 *
326 * You should have received a copy of the GNU General Public License
327 * along with algs4.jar. If not, see http://www.gnu.org/licenses.
328 ******************************************************************************/
1 /******************************************************************************
2 * Compilation: javac Bipartite.java
3 * Execution: java Bipartite V E F
4 * Dependencies: Graph.java
5 * Data files: http://algs4.cs.princeton.edu/41graph/tinyG.txt
6 * http://algs4.cs.princeton.edu/41graph/mediumG.txt
7 * http://algs4.cs.princeton.edu/41graph/largeG.txt
8 *
9 * Given a graph, find either (i) a bipartition or (ii) an odd-length cycle.
10 * Runs in O(E + V) time.
11 *
12 *
13 ******************************************************************************/
14
15 package edu.princeton.cs.algs4;
16
17
18 /**
19 * The {@code Bipartite} class represents a data type for
20 * determining whether an undirected graph is bipartite or whether
21 * it has an odd-length cycle.
22 * The <em>isBipartite</em> operation determines whether the graph is
23 * bipartite. If so, the <em>color</em> operation determines a
24 * bipartition; if not, the <em>oddCycle</em> operation determines a
25 * cycle with an odd number of edges.
26 * <p>
27 * This implementation uses depth-first search.
28 * The constructor takes time proportional to <em>V</em> + <em>E</em>
29 * (in the worst case),
30 * where <em>V</em> is the number of vertices and <em>E</em> is the number of edges.
31 * Afterwards, the <em>isBipartite</em> and <em>color</em> operations
32 * take constant time; the <em>oddCycle</em> operation takes time proportional
33 * to the length of the cycle.
34 * See {@link BipartiteX} for a nonrecursive version that uses breadth-first
35 * search.
36 * <p>
37 * For additional documentation, see <a href="http://algs4.cs.princeton.edu/41graph">Section 4.1</a>
38 * of <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
39 *
40 * @author Robert Sedgewick
41 * @author Kevin Wayne
42 */
43 public class Bipartite {
44 private boolean isBipartite; // is the graph bipartite?
45 private boolean[] color; // color[v] gives vertices on one side of bipartition
46 private boolean[] marked; // marked[v] = true if v has been visited in DFS
47 private int[] edgeTo; // edgeTo[v] = last edge on path to v
48 private Stack<Integer> cycle; // odd-length cycle
49
50 /**
51 * Determines whether an undirected graph is bipartite and finds either a
52 * bipartition or an odd-length cycle.
53 *
54 * @param G the graph
55 */
56 public Bipartite(Graph G) {
57 isBipartite = true;
58 color = new boolean[G.V()];
59 marked = new boolean[G.V()];
60 edgeTo = new int[G.V()];
61
62 for (int v = 0; v < G.V(); v++) {
63 if (!marked[v]) {
64 dfs(G, v);
65 }
66 }
67 assert check(G);
68 }
69
70 private void dfs(Graph G, int v) {
71 marked[v] = true;
72 for (int w : G.adj(v)) {
73
74 // short circuit if odd-length cycle found
75 if (cycle != null) return;
76
77 // found uncolored vertex, so recur
78 if (!marked[w]) {
79 edgeTo[w] = v;
80 color[w] = !color[v];
81 dfs(G, w);
82 }
83
84 // if v-w create an odd-length cycle, find it
85 else if (color[w] == color[v]) {
86 isBipartite = false;
87 cycle = new Stack<Integer>();
88 cycle.push(w); // don't need this unless you want to include start vertex twice
89 for (int x = v; x != w; x = edgeTo[x]) {
90 cycle.push(x);
91 }
92 cycle.push(w);
93 }
94 }
95 }
96
97 /**
98 * Returns true if the graph is bipartite.
99 *
100 * @return {@code true} if the graph is bipartite; {@code false} otherwise
101 */
102 public boolean isBipartite() {
103 return isBipartite;
104 }
105
106 /**
107 * Returns the side of the bipartite that vertex {@code v} is on.
108 *
109 * @param v the vertex
110 * @return the side of the bipartition that vertex {@code v} is on; two vertices
111 * are in the same side of the bipartition if and only if they have the
112 * same color
113 * @throws IllegalArgumentException unless {@code 0 <= v < V}
114 * @throws UnsupportedOperationException if this method is called when the graph
115 * is not bipartite
116 */
117 public boolean color(int v) {
118 validateVertex(v);
119 if (!isBipartite)
120 throw new UnsupportedOperationException("graph is not bipartite");
121 return color[v];
122 }
123
124 /**
125 * Returns an odd-length cycle if the graph is not bipartite, and
126 * {@code null} otherwise.
127 *
128 * @return an odd-length cycle if the graph is not bipartite
129 * (and hence has an odd-length cycle), and {@code null}
130 * otherwise
131 */
132 public Iterable<Integer> oddCycle() {
133 return cycle;
134 }
135
136 private boolean check(Graph G) {
137 // graph is bipartite
138 if (isBipartite) {
139 for (int v = 0; v < G.V(); v++) {
140 for (int w : G.adj(v)) {
141 if (color[v] == color[w]) {
142 System.err.printf("edge %d-%d with %d and %d in same side of bipartition\n", v, w, v, w);
143 return false;
144 }
145 }
146 }
147 }
148
149 // graph has an odd-length cycle
150 else {
151 // verify cycle
152 int first = -1, last = -1;
153 for (int v : oddCycle()) {
154 if (first == -1) first = v;
155 last = v;
156 }
157 if (first != last) {
158 System.err.printf("cycle begins with %d and ends with %d\n", first, last);
159 return false;
160 }
161 }
162
163 return true;
164 }
165
166 // throw an IllegalArgumentException unless {@code 0 <= v < V}
167 private void validateVertex(int v) {
168 int V = marked.length;
169 if (v < 0 || v >= V)
170 throw new IllegalArgumentException("vertex " + v + " is not between 0 and " + (V-1));
171 }
172
173 /**
174 * Unit tests the {@code Bipartite} data type.
175 *
176 * @param args the command-line arguments
177 */
178 public static void main(String[] args) {
179 int V1 = Integer.parseInt(args[0]);
180 int V2 = Integer.parseInt(args[1]);
181 int E = Integer.parseInt(args[2]);
182 int F = Integer.parseInt(args[3]);
183
184 // create random bipartite graph with V1 vertices on left side,
185 // V2 vertices on right side, and E edges; then add F random edges
186 Graph G = GraphGenerator.bipartite(V1, V2, E);
187 for (int i = 0; i < F; i++) {
188 int v = StdRandom.uniform(V1 + V2);
189 int w = StdRandom.uniform(V1 + V2);
190 G.addEdge(v, w);
191 }
192
193 StdOut.println(G);
194
195
196 Bipartite b = new Bipartite(G);
197 if (b.isBipartite()) {
198 StdOut.println("Graph is bipartite");
199 for (int v = 0; v < G.V(); v++) {
200 StdOut.println(v + ": " + b.color(v));
201 }
202 }
203 else {
204 StdOut.print("Graph has an odd-length cycle: ");
205 for (int x : b.oddCycle()) {
206 StdOut.print(x + " ");
207 }
208 StdOut.println();
209 }
210 }
211
212
213 }
214
215 /******************************************************************************
216 * Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
217 *
218 * This file is part of algs4.jar, which accompanies the textbook
219 *
220 * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
221 * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
222 * http://algs4.cs.princeton.edu
223 *
224 *
225 * algs4.jar is free software: you can redistribute it and/or modify
226 * it under the terms of the GNU General Public License as published by
227 * the Free Software Foundation, either version 3 of the License, or
228 * (at your option) any later version.
229 *
230 * algs4.jar is distributed in the hope that it will be useful,
231 * but WITHOUT ANY WARRANTY; without even the implied warranty of
232 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
233 * GNU General Public License for more details.
234 *
235 * You should have received a copy of the GNU General Public License
236 * along with algs4.jar. If not, see http://www.gnu.org/licenses.
237 ******************************************************************************/
1 /******************************************************************************
2 * Compilation: javac BipartiteX.java
3 * Execution: java Bipartite V E F
4 * Dependencies: Graph.java
5 *
6 * Given a graph, find either (i) a bipartition or (ii) an odd-length cycle.
7 * Runs in O(E + V) time.
8 *
9 *
10 ******************************************************************************/
11
12 package edu.princeton.cs.algs4;
13
14
15 /**
16 * The {@code BipartiteX} class represents a data type for
17 * determining whether an undirected graph is bipartite or whether
18 * it has an odd-length cycle.
19 * The <em>isBipartite</em> operation determines whether the graph is
20 * bipartite. If so, the <em>color</em> operation determines a
21 * bipartition; if not, the <em>oddCycle</em> operation determines a
22 * cycle with an odd number of edges.
23 * <p>
24 * This implementation uses breadth-first search and is nonrecursive.
25 * The constructor takes time proportional to <em>V</em> + <em>E</em>
26 * (in the worst case),
27 * where <em>V</em> is the number of vertices and <em>E</em> is the number of edges.
28 * Afterwards, the <em>isBipartite</em> and <em>color</em> operations
29 * take constant time; the <em>oddCycle</em> operation takes time proportional
30 * to the length of the cycle.
31 * See {@link Bipartite} for a recursive version that uses depth-first search.
32 * <p>
33 * For additional documentation,
34 * see <a href="http://algs4.cs.princeton.edu/41graph">Section 4.1</a>
35 * of <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
36 *
37 * @author Robert Sedgewick
38 * @author Kevin Wayne
39 */
40 public class BipartiteX {
41 private static final boolean WHITE = false;
42 private static final boolean BLACK = true;
43
44 private boolean isBipartite; // is the graph bipartite?
45 private boolean[] color; // color[v] gives vertices on one side of bipartition
46 private boolean[] marked; // marked[v] = true if v has been visited in DFS
47 private int[] edgeTo; // edgeTo[v] = last edge on path to v
48 private Queue<Integer> cycle; // odd-length cycle
49
50 /**
51 * Determines whether an undirected graph is bipartite and finds either a
52 * bipartition or an odd-length cycle.
53 *
54 * @param G the graph
55 */
56 public BipartiteX(Graph G) {
57 isBipartite = true;
58 color = new boolean[G.V()];
59 marked = new boolean[G.V()];
60 edgeTo = new int[G.V()];
61
62 for (int v = 0; v < G.V() && isBipartite; v++) {
63 if (!marked[v]) {
64 bfs(G, v);
65 }
66 }
67 assert check(G);
68 }
69
70 private void bfs(Graph G, int s) {
71 Queue<Integer> q = new Queue<Integer>();
72 color[s] = WHITE;
73 marked[s] = true;
74 q.enqueue(s);
75
76 while (!q.isEmpty()) {
77 int v = q.dequeue();
78 for (int w : G.adj(v)) {
79 if (!marked[w]) {
80 marked[w] = true;
81 edgeTo[w] = v;
82 color[w] = !color[v];
83 q.enqueue(w);
84 }
85 else if (color[w] == color[v]) {
86 isBipartite = false;
87
88 // to form odd cycle, consider s-v path and s-w path
89 // and let x be closest node to v and w common to two paths
90 // then (w-x path) + (x-v path) + (edge v-w) is an odd-length cycle
91 // Note: distTo[v] == distTo[w];
92 cycle = new Queue<Integer>();
93 Stack<Integer> stack = new Stack<Integer>();
94 int x = v, y = w;
95 while (x != y) {
96 stack.push(x);
97 cycle.enqueue(y);
98 x = edgeTo[x];
99 y = edgeTo[y];
100 }
101 stack.push(x);
102 while (!stack.isEmpty())
103 cycle.enqueue(stack.pop());
104 cycle.enqueue(w);
105 return;
106 }
107 }
108 }
109 }
110
111 /**
112 * Returns true if the graph is bipartite.
113 *
114 * @return {@code true} if the graph is bipartite; {@code false} otherwise
115 */
116 public boolean isBipartite() {
117 return isBipartite;
118 }
119
120 /**
121 * Returns the side of the bipartite that vertex {@code v} is on.
122 *
123 * @param v the vertex
124 * @return the side of the bipartition that vertex {@code v} is on; two vertices
125 * are in the same side of the bipartition if and only if they have the
126 * same color
127 * @throws IllegalArgumentException unless {@code 0 <= v < V}
128 * @throws UnsupportedOperationException if this method is called when the graph
129 * is not bipartite
130 */
131 public boolean color(int v) {
132 validateVertex(v);
133 if (!isBipartite)
134 throw new UnsupportedOperationException("Graph is not bipartite");
135 return color[v];
136 }
137
138
139 /**
140 * Returns an odd-length cycle if the graph is not bipartite, and
141 * {@code null} otherwise.
142 *
143 * @return an odd-length cycle if the graph is not bipartite
144 * (and hence has an odd-length cycle), and {@code null}
145 * otherwise
146 */
147 public Iterable<Integer> oddCycle() {
148 return cycle;
149 }
150
151 private boolean check(Graph G) {
152 // graph is bipartite
153 if (isBipartite) {
154 for (int v = 0; v < G.V(); v++) {
155 for (int w : G.adj(v)) {
156 if (color[v] == color[w]) {
157 System.err.printf("edge %d-%d with %d and %d in same side of bipartition\n", v, w, v, w);
158 return false;
159 }
160 }
161 }
162 }
163
164 // graph has an odd-length cycle
165 else {
166 // verify cycle
167 int first = -1, last = -1;
168 for (int v : oddCycle()) {
169 if (first == -1) first = v;
170 last = v;
171 }
172 if (first != last) {
173 System.err.printf("cycle begins with %d and ends with %d\n", first, last);
174 return false;
175 }
176 }
177 return true;
178 }
179
180 // throw an IllegalArgumentException unless {@code 0 <= v < V}
181 private void validateVertex(int v) {
182 int V = marked.length;
183 if (v < 0 || v >= V)
184 throw new IllegalArgumentException("vertex " + v + " is not between 0 and " + (V-1));
185 }
186
187 /**
188 * Unit tests the {@code BipartiteX} data type.
189 *
190 * @param args the command-line arguments
191 */
192 public static void main(String[] args) {
193 int V1 = Integer.parseInt(args[0]);
194 int V2 = Integer.parseInt(args[1]);
195 int E = Integer.parseInt(args[2]);
196 int F = Integer.parseInt(args[3]);
197
198 // create random bipartite graph with V1 vertices on left side,
199 // V2 vertices on right side, and E edges; then add F random edges
200 Graph G = GraphGenerator.bipartite(V1, V2, E);
201 for (int i = 0; i < F; i++) {
202 int v = StdRandom.uniform(V1 + V2);
203 int w = StdRandom.uniform(V1 + V2);
204 G.addEdge(v, w);
205 }
206
207 StdOut.println(G);
208
209
210 BipartiteX b = new BipartiteX(G);
211 if (b.isBipartite()) {
212 StdOut.println("Graph is bipartite");
213 for (int v = 0; v < G.V(); v++) {
214 StdOut.println(v + ": " + b.color(v));
215 }
216 }
217 else {
218 StdOut.print("Graph has an odd-length cycle: ");
219 for (int x : b.oddCycle()) {
220 StdOut.print(x + " ");
221 }
222 StdOut.println();
223 }
224 }
225
226
227 }
228
229 /******************************************************************************
230 * Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
231 *
232 * This file is part of algs4.jar, which accompanies the textbook
233 *
234 * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
235 * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
236 * http://algs4.cs.princeton.edu
237 *
238 *
239 * algs4.jar is free software: you can redistribute it and/or modify
240 * it under the terms of the GNU General Public License as published by
241 * the Free Software Foundation, either version 3 of the License, or
242 * (at your option) any later version.
243 *
244 * algs4.jar is distributed in the hope that it will be useful,
245 * but WITHOUT ANY WARRANTY; without even the implied warranty of
246 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
247 * GNU General Public License for more details.
248 *
249 * You should have received a copy of the GNU General Public License
250 * along with algs4.jar. If not, see http://www.gnu.org/licenses.
251 ******************************************************************************/
1 /******************************************************************************
2 * Compilation: javac BlackFilter.java
3 * Execution: java BlackFilter blacklist.txt < input.txt
4 * Dependencies: SET In.java StdIn.java StdOut.java
5 * Data files: http://algs4.cs.princeton.edu/35applications/tinyTale.txt
6 * http://algs4.cs.princeton.edu/35applications/list.txt
7 *
8 * Read in a blacklist of words from a file. Then read in a list of
9 * words from standard input and print out all those words that
10 * are not in the first file.
11 *
12 * % more tinyTale.txt
13 * it was the best of times it was the worst of times
14 * it was the age of wisdom it was the age of foolishness
15 * it was the epoch of belief it was the epoch of incredulity
16 * it was the season of light it was the season of darkness
17 * it was the spring of hope it was the winter of despair
18 *
19 * % more list.txt
20 * was it the of
21 *
22 * % java BlackFilter list.txt < tinyTale.txt
23 * best times worst times
24 * age wisdom age foolishness
25 * epoch belief epoch incredulity
26 * season light season darkness
27 * spring hope winter despair
28 *
29 ******************************************************************************/
30
31 package edu.princeton.cs.algs4;
32
33 /**
34 * The {@code BlackFilter} class provides a client for reading in a <em>blacklist</em>
35 * of words from a file; then, reading in a sequence of words from standard input,
36 * printing out each word that <em>does not</em> appear in the file.
37 * It is useful as a test client for various symbol table implementations.
38 * <p>
39 * For additional documentation, see <a href="http://algs4.cs.princeton.edu/35applications">Section 3.5</a> of
40 * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
41 *
42 * @author Robert Sedgewick
43 * @author Kevin Wayne
44 */
45 public class BlackFilter {
46
47 // Do not instantiate.
48 private BlackFilter() { }
49
50 public static void main(String[] args) {
51 SET<String> set = new SET<String>();
52
53 // read in strings and add to set
54 In in = new In(args[0]);
55 while (!in.isEmpty()) {
56 String word = in.readString();
57 set.add(word);
58 }
59
60 // read in string from standard input, printing out all exceptions
61 while (!StdIn.isEmpty()) {
62 String word = StdIn.readString();
63 if (!set.contains(word))
64 StdOut.println(word);
65 }
66 }
67 }
68
69 /******************************************************************************
70 * Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
71 *
72 * This file is part of algs4.jar, which accompanies the textbook
73 *
74 * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
75 * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
76 * http://algs4.cs.princeton.edu
77 *
78 *
79 * algs4.jar is free software: you can redistribute it and/or modify
80 * it under the terms of the GNU General Public License as published by
81 * the Free Software Foundation, either version 3 of the License, or
82 * (at your option) any later version.
83 *
84 * algs4.jar is distributed in the hope that it will be useful,
85 * but WITHOUT ANY WARRANTY; without even the implied warranty of
86 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
87 * GNU General Public License for more details.
88 *
89 * You should have received a copy of the GNU General Public License
90 * along with algs4.jar. If not, see http://www.gnu.org/licenses.
91 ******************************************************************************/
1 /******************************************************************************
2 * Compilation: javac BoruvkaMST.java
3 * Execution: java BoruvkaMST filename.txt
4 * Dependencies: EdgeWeightedGraph.java Edge.java Bag.java
5 * UF.java In.java StdOut.java
6 * Data files: http://algs4.cs.princeton.edu/43mst/tinyEWG.txt
7 * http://algs4.cs.princeton.edu/43mst/mediumEWG.txt
8 * http://algs4.cs.princeton.edu/43mst/largeEWG.txt
9 *
10 * Compute a minimum spanning forest using Boruvka's algorithm.
11 *
12 * % java BoruvkaMST tinyEWG.txt
13 * 0-2 0.26000
14 * 6-2 0.40000
15 * 5-7 0.28000
16 * 4-5 0.35000
17 * 2-3 0.17000
18 * 1-7 0.19000
19 * 0-7 0.16000
20 * 1.81000
21 *
22 ******************************************************************************/
23
24 package edu.princeton.cs.algs4;
25
26 /**
27 * The {@code BoruvkaMST} class represents a data type for computing a
28 * <em>minimum spanning tree</em> in an edge-weighted graph.
29 * The edge weights can be positive, zero, or negative and need not
30 * be distinct. If the graph is not connected, it computes a <em>minimum
31 * spanning forest</em>, which is the union of minimum spanning trees
32 * in each connected component. The {@code weight()} method returns the
33 * weight of a minimum spanning tree and the {@code edges()} method
34 * returns its edges.
35 * <p>
36 * This implementation uses <em>Boruvka's algorithm</em> and the union-find
37 * data type.
38 * The constructor takes time proportional to <em>E</em> log <em>V</em>
39 * and extra space (not including the graph) proportional to <em>V</em>,
40 * where <em>V</em> is the number of vertices and <em>E</em> is the number of edges.
41 * Afterwards, the {@code weight()} method takes constant time
42 * and the {@code edges()} method takes time proportional to <em>V</em>.
43 * <p>
44 * For additional documentation,
45 * see <a href="http://algs4.cs.princeton.edu/43mst">Section 4.3</a> of
46 * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
47 * For alternate implementations, see {@link LazyPrimMST}, {@link PrimMST},
48 * and {@link KruskalMST}.
49 *
50 * @author Robert Sedgewick
51 * @author Kevin Wayne
52 */
53 public class BoruvkaMST {
54 private static final double FLOATING_POINT_EPSILON = 1E-12;
55
56 private Bag<Edge> mst = new Bag<Edge>(); // edges in MST
57 private double weight; // weight of MST
58
59 /**
60 * Compute a minimum spanning tree (or forest) of an edge-weighted graph.
61 * @param G the edge-weighted graph
62 */
63 public BoruvkaMST(EdgeWeightedGraph G) {
64 UF uf = new UF(G.V());
65
66 // repeat at most log V times or until we have V-1 edges
67 for (int t = 1; t < G.V() && mst.size() < G.V() - 1; t = t + t) {
68
69 // foreach tree in forest, find closest edge
70 // if edge weights are equal, ties are broken in favor of first edge in G.edges()
71 Edge[] closest = new Edge[G.V()];
72 for (Edge e : G.edges()) {
73 int v = e.either(), w = e.other(v);
74 int i = uf.find(v), j = uf.find(w);
75 if (i == j) continue; // same tree
76 if (closest[i] == null || less(e, closest[i])) closest[i] = e;
77 if (closest[j] == null || less(e, closest[j])) closest[j] = e;
78 }
79
80 // add newly discovered edges to MST
81 for (int i = 0; i < G.V(); i++) {
82 Edge e = closest[i];
83 if (e != null) {
84 int v = e.either(), w = e.other(v);
85 // don't add the same edge twice
86 if (!uf.connected(v, w)) {
87 mst.add(e);
88 weight += e.weight();
89 uf.union(v, w);
90 }
91 }
92 }
93 }
94
95 // check optimality conditions
96 assert check(G);
97 }
98
99 /**
100 * Returns the edges in a minimum spanning tree (or forest).
101 * @return the edges in a minimum spanning tree (or forest) as
102 * an iterable of edges
103 */
104 public Iterable<Edge> edges() {
105 return mst;
106 }
107
108
109 /**
110 * Returns the sum of the edge weights in a minimum spanning tree (or forest).
111 * @return the sum of the edge weights in a minimum spanning tree (or forest)
112 */
113 public double weight() {
114 return weight;
115 }
116
117 // is the weight of edge e strictly less than that of edge f?
118 private static boolean less(Edge e, Edge f) {
119 return e.weight() < f.weight();
120 }
121
122 // check optimality conditions (takes time proportional to E V lg* V)
123 private boolean check(EdgeWeightedGraph G) {
124
125 // check weight
126 double totalWeight = 0.0;
127 for (Edge e : edges()) {
128 totalWeight += e.weight();
129 }
130 if (Math.abs(totalWeight - weight()) > FLOATING_POINT_EPSILON) {
131 System.err.printf("Weight of edges does not equal weight(): %f vs. %f\n", totalWeight, weight());
132 return false;
133 }
134
135 // check that it is acyclic
136 UF uf = new UF(G.V());
137 for (Edge e : edges()) {
138 int v = e.either(), w = e.other(v);
139 if (uf.connected(v, w)) {
140 System.err.println("Not a forest");
141 return false;
142 }
143 uf.union(v, w);
144 }
145
146 // check that it is a spanning forest
147 for (Edge e : G.edges()) {
148 int v = e.either(), w = e.other(v);
149 if (!uf.connected(v, w)) {
150 System.err.println("Not a spanning forest");
151 return false;
152 }
153 }
154
155 // check that it is a minimal spanning forest (cut optimality conditions)
156 for (Edge e : edges()) {
157
158 // all edges in MST except e
159 uf = new UF(G.V());
160 for (Edge f : mst) {
161 int x = f.either(), y = f.other(x);
162 if (f != e) uf.union(x, y);
163 }
164
165 // check that e is min weight edge in crossing cut
166 for (Edge f : G.edges()) {
167 int x = f.either(), y = f.other(x);
168 if (!uf.connected(x, y)) {
169 if (f.weight() < e.weight()) {
170 System.err.println("Edge " + f + " violates cut optimality conditions");
171 return false;
172 }
173 }
174 }
175
176 }
177
178 return true;
179 }
180
181 /**
182 * Unit tests the {@code BoruvkaMST} data type.
183 *
184 * @param args the command-line arguments
185 */
186 public static void main(String[] args) {
187 In in = new In(args[0]);
188 EdgeWeightedGraph G = new EdgeWeightedGraph(in);
189 BoruvkaMST mst = new BoruvkaMST(G);
190 for (Edge e : mst.edges()) {
191 StdOut.println(e);
192 }
193 StdOut.printf("%.5f\n", mst.weight());
194 }
195
196 }
197
198 /******************************************************************************
199 * Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
200 *
201 * This file is part of algs4.jar, which accompanies the textbook
202 *
203 * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
204 * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
205 * http://algs4.cs.princeton.edu
206 *
207 *
208 * algs4.jar is free software: you can redistribute it and/or modify
209 * it under the terms of the GNU General Public License as published by
210 * the Free Software Foundation, either version 3 of the License, or
211 * (at your option) any later version.
212 *
213 * algs4.jar is distributed in the hope that it will be useful,
214 * but WITHOUT ANY WARRANTY; without even the implied warranty of
215 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
216 * GNU General Public License for more details.
217 *
218 * You should have received a copy of the GNU General Public License
219 * along with algs4.jar. If not, see http://www.gnu.org/licenses.
220 ******************************************************************************/
1 /******************************************************************************
2 * Compilation: javac BoyerMoore.java
3 * Execution: java BoyerMoore pattern text
4 * Dependencies: StdOut.java
5 *
6 * Reads in two strings, the pattern and the input text, and
7 * searches for the pattern in the input text using the
8 * bad-character rule part of the Boyer-Moore algorithm.
9 * (does not implement the strong good suffix rule)
10 *
11 * % java BoyerMoore abracadabra abacadabrabracabracadabrabrabracad
12 * text: abacadabrabracabracadabrabrabracad
13 * pattern: abracadabra
14 *
15 * % java BoyerMoore rab abacadabrabracabracadabrabrabracad
16 * text: abacadabrabracabracadabrabrabracad
17 * pattern: rab
18 *
19 * % java BoyerMoore bcara abacadabrabracabracadabrabrabracad
20 * text: abacadabrabracabracadabrabrabracad
21 * pattern: bcara
22 *
23 * % java BoyerMoore rabrabracad abacadabrabracabracadabrabrabracad
24 * text: abacadabrabracabracadabrabrabracad
25 * pattern: rabrabracad
26 *
27 * % java BoyerMoore abacad abacadabrabracabracadabrabrabracad
28 * text: abacadabrabracabracadabrabrabracad
29 * pattern: abacad
30 *
31 ******************************************************************************/
32
33 package edu.princeton.cs.algs4;
34
35 /**
36 * The {@code BoyerMoore} class finds the first occurrence of a pattern string
37 * in a text string.
38 * <p>
39 * This implementation uses the Boyer-Moore algorithm (with the bad-character
40 * rule, but not the strong good suffix rule).
41 * <p>
42 * For additional documentation,
43 * see <a href="http://algs4.cs.princeton.edu/53substring">Section 5.3</a> of
44 * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
45 */
46 public class BoyerMoore {
47 private final int R; // the radix
48 private int[] right; // the bad-character skip array
49
50 private char[] pattern; // store the pattern as a character array
51 private String pat; // or as a string
52
53 /**
54 * Preprocesses the pattern string.
55 *
56 * @param pat the pattern string
57 */
58 public BoyerMoore(String pat) {
59 this.R = 256;
60 this.pat = pat;
61
62 // position of rightmost occurrence of c in the pattern
63 right = new int[R];
64 for (int c = 0; c < R; c++)
65 right[c] = -1;
66 for (int j = 0; j < pat.length(); j++)
67 right[pat.charAt(j)] = j;
68 }
69
70 /**
71 * Preprocesses the pattern string.
72 *
73 * @param pattern the pattern string
74 * @param R the alphabet size
75 */
76 public BoyerMoore(char[] pattern, int R) {
77 this.R = R;
78 this.pattern = new char[pattern.length];
79 for (int j = 0; j < pattern.length; j++)
80 this.pattern[j] = pattern[j];
81
82 // position of rightmost occurrence of c in the pattern
83 right = new int[R];
84 for (int c = 0; c < R; c++)
85 right[c] = -1;
86 for (int j = 0; j < pattern.length; j++)
87 right[pattern[j]] = j;
88 }
89
90 /**
91 * Returns the index of the first occurrrence of the pattern string
92 * in the text string.
93 *
94 * @param txt the text string
95 * @return the index of the first occurrence of the pattern string
96 * in the text string; n if no such match
97 */
98 public int search(String txt) {
99 int m = pat.length();
100 int n = txt.length();
101 int skip;
102 for (int i = 0; i <= n - m; i += skip) {
103 skip = 0;
104 for (int j = m-1; j >= 0; j--) {
105 if (pat.charAt(j) != txt.charAt(i+j)) {
106 skip = Math.max(1, j - right[txt.charAt(i+j)]);
107 break;
108 }
109 }
110 if (skip == 0) return i; // found
111 }
112 return n; // not found
113 }
114
115
116 /**
117 * Returns the index of the first occurrrence of the pattern string
118 * in the text string.
119 *
120 * @param text the text string
121 * @return the index of the first occurrence of the pattern string
122 * in the text string; n if no such match
123 */
124 public int search(char[] text) {
125 int m = pattern.length;
126 int n = text.length;
127 int skip;
128 for (int i = 0; i <= n - m; i += skip) {
129 skip = 0;
130 for (int j = m-1; j >= 0; j--) {
131 if (pattern[j] != text[i+j]) {
132 skip = Math.max(1, j - right[text[i+j]]);
133 break;
134 }
135 }
136 if (skip == 0) return i; // found
137 }
138 return n; // not found
139 }
140
141
142 /**
143 * Takes a pattern string and an input string as command-line arguments;
144 * searches for the pattern string in the text string; and prints
145 * the first occurrence of the pattern string in the text string.
146 *
147 * @param args the command-line arguments
148 */
149 public static void main(String[] args) {
150 String pat = args[0];
151 String txt = args[1];
152 char[] pattern = pat.toCharArray();
153 char[] text = txt.toCharArray();
154
155 BoyerMoore boyermoore1 = new BoyerMoore(pat);
156 BoyerMoore boyermoore2 = new BoyerMoore(pattern, 256);
157 int offset1 = boyermoore1.search(txt);
158 int offset2 = boyermoore2.search(text);
159
160 // print results
161 StdOut.println("text: " + txt);
162
163 StdOut.print("pattern: ");
164 for (int i = 0; i < offset1; i++)
165 StdOut.print(" ");
166 StdOut.println(pat);
167
168 StdOut.print("pattern: ");
169 for (int i = 0; i < offset2; i++)
170 StdOut.print(" ");
171 StdOut.println(pat);
172 }
173 }
174
175
176 /******************************************************************************
177 * Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
178 *
179 * This file is part of algs4.jar, which accompanies the textbook
180 *
181 * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
182 * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
183 * http://algs4.cs.princeton.edu
184 *
185 *
186 * algs4.jar is free software: you can redistribute it and/or modify
187 * it under the terms of the GNU General Public License as published by
188 * the Free Software Foundation, either version 3 of the License, or
189 * (at your option) any later version.
190 *
191 * algs4.jar is distributed in the hope that it will be useful,
192 * but WITHOUT ANY WARRANTY; without even the implied warranty of
193 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
194 * GNU General Public License for more details.
195 *
196 * You should have received a copy of the GNU General Public License
197 * along with algs4.jar. If not, see http://www.gnu.org/licenses.
198 ******************************************************************************/
1 /******************************************************************************
2 * Compilation: javac BreadthFirstDirectedPaths.java
3 * Execution: java BreadthFirstDirectedPaths digraph.txt s
4 * Dependencies: Digraph.java Queue.java Stack.java
5 * Data files: http://algs4.cs.princeton.edu/42digraph/tinyDG.txt
6 * http://algs4.cs.princeton.edu/42digraph/mediumDG.txt
7 * http://algs4.cs.princeton.edu/42digraph/largeDG.txt
8 *
9 * Run breadth-first search on a digraph.
10 * Runs in O(E + V) time.
11 *
12 * % java BreadthFirstDirectedPaths tinyDG.txt 3
13 * 3 to 0 (2): 3->2->0
14 * 3 to 1 (3): 3->2->0->1
15 * 3 to 2 (1): 3->2
16 * 3 to 3 (0): 3
17 * 3 to 4 (2): 3->5->4
18 * 3 to 5 (1): 3->5
19 * 3 to 6 (-): not connected
20 * 3 to 7 (-): not connected
21 * 3 to 8 (-): not connected
22 * 3 to 9 (-): not connected
23 * 3 to 10 (-): not connected
24 * 3 to 11 (-): not connected
25 * 3 to 12 (-): not connected
26 *
27 ******************************************************************************/
28
29 package edu.princeton.cs.algs4;
30
31 /**
32 * The {@code BreadthDirectedFirstPaths} class represents a data type for finding
33 * shortest paths (number of edges) from a source vertex <em>s</em>
34 * (or set of source vertices) to every other vertex in the digraph.
35 * <p>
36 * This implementation uses breadth-first search.
37 * The constructor takes time proportional to <em>V</em> + <em>E</em>,
38 * where <em>V</em> is the number of vertices and <em>E</em> is the number of edges.
39 * It uses extra space (not including the digraph) proportional to <em>V</em>.
40 * <p>
41 * For additional documentation,
42 * see <a href="http://algs4.cs.princeton.edu/42digraph">Section 4.2</a> of
43 * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
44 *
45 * @author Robert Sedgewick
46 * @author Kevin Wayne
47 */
48 public class BreadthFirstDirectedPaths {
49 private static final int INFINITY = Integer.MAX_VALUE;
50 private boolean[] marked; // marked[v] = is there an s->v path?
51 private int[] edgeTo; // edgeTo[v] = last edge on shortest s->v path
52 private int[] distTo; // distTo[v] = length of shortest s->v path
53
54 /**
55 * Computes the shortest path from {@code s} and every other vertex in graph {@code G}.
56 * @param G the digraph
57 * @param s the source vertex
58 * @throws IllegalArgumentException unless {@code 0 <= v < V}
59 */
60 public BreadthFirstDirectedPaths(Digraph G, int s) {
61 marked = new boolean[G.V()];
62 distTo = new int[G.V()];
63 edgeTo = new int[G.V()];
64 for (int v = 0; v < G.V(); v++)
65 distTo[v] = INFINITY;
66 validateVertex(s);
67 bfs(G, s);
68 }
69
70 /**
71 * Computes the shortest path from any one of the source vertices in {@code sources}
72 * to every other vertex in graph {@code G}.
73 * @param G the digraph
74 * @param sources the source vertices
75 * @throws IllegalArgumentException unless each vertex {@code v} in
76 * {@code sources} satisfies {@code 0 <= v < V}
77 */
78 public BreadthFirstDirectedPaths(Digraph G, Iterable<Integer> sources) {
79 marked = new boolean[G.V()];
80 distTo = new int[G.V()];
81 edgeTo = new int[G.V()];
82 for (int v = 0; v < G.V(); v++)
83 distTo[v] = INFINITY;
84 validateVertices(sources);
85 bfs(G, sources);
86 }
87
88 // BFS from single source
89 private void bfs(Digraph G, int s) {
90 Queue<Integer> q = new Queue<Integer>();
91 marked[s] = true;
92 distTo[s] = 0;
93 q.enqueue(s);
94 while (!q.isEmpty()) {
95 int v = q.dequeue();
96 for (int w : G.adj(v)) {
97 if (!marked[w]) {
98 edgeTo[w] = v;
99 distTo[w] = distTo[v] + 1;
100 marked[w] = true;
101 q.enqueue(w);
102 }
103 }
104 }
105 }
106
107 // BFS from multiple sources
108 private void bfs(Digraph G, Iterable<Integer> sources) {
109 Queue<Integer> q = new Queue<Integer>();
110 for (int s : sources) {
111 marked[s] = true;
112 distTo[s] = 0;
113 q.enqueue(s);
114 }
115 while (!q.isEmpty()) {
116 int v = q.dequeue();
117 for (int w : G.adj(v)) {
118 if (!marked[w]) {
119 edgeTo[w] = v;
120 distTo[w] = distTo[v] + 1;
121 marked[w] = true;
122 q.enqueue(w);
123 }
124 }
125 }
126 }
127
128 /**
129 * Is there a directed path from the source {@code s} (or sources) to vertex {@code v}?
130 * @param v the vertex
131 * @return {@code true} if there is a directed path, {@code false} otherwise
132 * @throws IllegalArgumentException unless {@code 0 <= v < V}
133 */
134 public boolean hasPathTo(int v) {
135 validateVertex(v);
136 return marked[v];
137 }
138
139 /**
140 * Returns the number of edges in a shortest path from the source {@code s}
141 * (or sources) to vertex {@code v}?
142 * @param v the vertex
143 * @return the number of edges in a shortest path
144 * @throws IllegalArgumentException unless {@code 0 <= v < V}
145 */
146 public int distTo(int v) {
147 validateVertex(v);
148 return distTo[v];
149 }
150
151 /**
152 * Returns a shortest path from {@code s} (or sources) to {@code v}, or
153 * {@code null} if no such path.
154 * @param v the vertex
155 * @return the sequence of vertices on a shortest path, as an Iterable
156 * @throws IllegalArgumentException unless {@code 0 <= v < V}
157 */
158 public Iterable<Integer> pathTo(int v) {
159 validateVertex(v);
160
161 if (!hasPathTo(v)) return null;
162 Stack<Integer> path = new Stack<Integer>();
163 int x;
164 for (x = v; distTo[x] != 0; x = edgeTo[x])
165 path.push(x);
166 path.push(x);
167 return path;
168 }
169
170 // throw an IllegalArgumentException unless {@code 0 <= v < V}
171 private void validateVertex(int v) {
172 int V = marked.length;
173 if (v < 0 || v >= V)
174 throw new IllegalArgumentException("vertex " + v + " is not between 0 and " + (V-1));
175 }
176
177 // throw an IllegalArgumentException unless {@code 0 <= v < V}
178 private void validateVertices(Iterable<Integer> vertices) {
179 if (vertices == null) {
180 throw new IllegalArgumentException("argument is null");
181 }
182 int V = marked.length;
183 for (int v : vertices) {
184 if (v < 0 || v >= V) {
185 throw new IllegalArgumentException("vertex " + v + " is not between 0 and " + (V-1));
186 }
187 }
188 }
189
190
191 /**
192 * Unit tests the {@code BreadthFirstDirectedPaths} data type.
193 *
194 * @param args the command-line arguments
195 */
196 public static void main(String[] args) {
197 In in = new In(args[0]);
198 Digraph G = new Digraph(in);
199 // StdOut.println(G);
200
201 int s = Integer.parseInt(args[1]);
202 BreadthFirstDirectedPaths bfs = new BreadthFirstDirectedPaths(G, s);
203
204 for (int v = 0; v < G.V(); v++) {
205 if (bfs.hasPathTo(v)) {
206 StdOut.printf("%d to %d (%d): ", s, v, bfs.distTo(v));
207 for (int x : bfs.pathTo(v)) {
208 if (x == s) StdOut.print(x);
209 else StdOut.print("->" + x);
210 }
211 StdOut.println();
212 }
213
214 else {
215 StdOut.printf("%d to %d (-): not connected\n", s, v);
216 }
217
218 }
219 }
220
221
222 }
223
224 /******************************************************************************
225 * Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
226 *
227 * This file is part of algs4.jar, which accompanies the textbook
228 *
229 * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
230 * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
231 * http://algs4.cs.princeton.edu
232 *
233 *
234 * algs4.jar is free software: you can redistribute it and/or modify
235 * it under the terms of the GNU General Public License as published by
236 * the Free Software Foundation, either version 3 of the License, or
237 * (at your option) any later version.
238 *
239 * algs4.jar is distributed in the hope that it will be useful,
240 * but WITHOUT ANY WARRANTY; without even the implied warranty of
241 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
242 * GNU General Public License for more details.
243 *
244 * You should have received a copy of the GNU General Public License
245 * along with algs4.jar. If not, see http://www.gnu.org/licenses.
246 ******************************************************************************/
1 /******************************************************************************
2 * Compilation: javac CC.java
3 * Execution: java CC filename.txt
4 * Dependencies: Graph.java StdOut.java Queue.java
5 * Data files: http://algs4.cs.princeton.edu/41graph/tinyG.txt
6 * http://algs4.cs.princeton.edu/41graph/mediumG.txt
7 * http://algs4.cs.princeton.edu/41graph/largeG.txt
8 *
9 * Compute connected components using depth first search.
10 * Runs in O(E + V) time.
11 *
12 * % java CC tinyG.txt
13 * 3 components
14 * 0 1 2 3 4 5 6
15 * 7 8
16 * 9 10 11 12
17 *
18 * % java CC mediumG.txt
19 * 1 components
20 * 0 1 2 3 4 5 6 7 8 9 10 ...
21 *
22 * % java -Xss50m CC largeG.txt
23 * 1 components
24 * 0 1 2 3 4 5 6 7 8 9 10 ...
25 *
26 * Note: This implementation uses a recursive DFS. To avoid needing
27 * a potentially very large stack size, replace with a non-recurisve
28 * DFS ala NonrecursiveDFS.java.
29 *
30 ******************************************************************************/
31
32 package edu.princeton.cs.algs4;
33
34 /**
35 * The {@code CC} class represents a data type for
36 * determining the connected components in an undirected graph.
37 * The <em>id</em> operation determines in which connected component
38 * a given vertex lies; the <em>connected</em> operation
39 * determines whether two vertices are in the same connected component;
40 * the <em>count</em> operation determines the number of connected
41 * components; and the <em>size</em> operation determines the number
42 * of vertices in the connect component containing a given vertex.
43
44 * The <em>component identifier</em> of a connected component is one of the
45 * vertices in the connected component: two vertices have the same component
46 * identifier if and only if they are in the same connected component.
47
48 * <p>
49 * This implementation uses depth-first search.
50 * The constructor takes time proportional to <em>V</em> + <em>E</em>
51 * (in the worst case),
52 * where <em>V</em> is the number of vertices and <em>E</em> is the number of edges.
53 * Afterwards, the <em>id</em>, <em>count</em>, <em>connected</em>,
54 * and <em>size</em> operations take constant time.
55 * <p>
56 * For additional documentation, see <a href="http://algs4.cs.princeton.edu/41graph">Section 4.1</a>
57 * of <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
58 *
59 * @author Robert Sedgewick
60 * @author Kevin Wayne
61 */
62 public class CC {
63 private boolean[] marked; // marked[v] = has vertex v been marked?
64 private int[] id; // id[v] = id of connected component containing v
65 private int[] size; // size[id] = number of vertices in given component
66 private int count; // number of connected components
67
68 /**
69 * Computes the connected components of the undirected graph {@code G}.
70 *
71 * @param G the undirected graph
72 */
73 public CC(Graph G) {
74 marked = new boolean[G.V()];
75 id = new int[G.V()];
76 size = new int[G.V()];
77 for (int v = 0; v < G.V(); v++) {
78 if (!marked[v]) {
79 dfs(G, v);
80 count++;
81 }
82 }
83 }
84
85 /**
86 * Computes the connected components of the edge-weighted graph {@code G}.
87 *
88 * @param G the edge-weighted graph
89 */
90 public CC(EdgeWeightedGraph G) {
91 marked = new boolean[G.V()];
92 id = new int[G.V()];
93 size = new int[G.V()];
94 for (int v = 0; v < G.V(); v++) {
95 if (!marked[v]) {
96 dfs(G, v);
97 count++;
98 }
99 }
100 }
101
102 // depth-first search for a Graph
103 private void dfs(Graph G, int v) {
104 marked[v] = true;
105 id[v] = count;
106 size[count]++;
107 for (int w : G.adj(v)) {
108 if (!marked[w]) {
109 dfs(G, w);
110 }
111 }
112 }
113
114 // depth-first search for an EdgeWeightedGraph
115 private void dfs(EdgeWeightedGraph G, int v) {
116 marked[v] = true;
117 id[v] = count;
118 size[count]++;
119 for (Edge e : G.adj(v)) {
120 int w = e.other(v);
121 if (!marked[w]) {
122 dfs(G, w);
123 }
124 }
125 }
126
127
128 /**
129 * Returns the component id of the connected component containing vertex {@code v}.
130 *
131 * @param v the vertex
132 * @return the component id of the connected component containing vertex {@code v}
133 * @throws IllegalArgumentException unless {@code 0 <= v < V}
134 */
135 public int id(int v) {
136 validateVertex(v);
137 return id[v];
138 }
139
140 /**
141 * Returns the number of vertices in the connected component containing vertex {@code v}.
142 *
143 * @param v the vertex
144 * @return the number of vertices in the connected component containing vertex {@code v}
145 * @throws IllegalArgumentException unless {@code 0 <= v < V}
146 */
147 public int size(int v) {
148 validateVertex(v);
149 return size[id[v]];
150 }
151
152 /**
153 * Returns the number of connected components in the graph {@code G}.
154 *
155 * @return the number of connected components in the graph {@code G}
156 */
157 public int count() {
158 return count;
159 }
160
161 /**
162 * Returns true if vertices {@code v} and {@code w} are in the same
163 * connected component.
164 *
165 * @param v one vertex
166 * @param w the other vertex
167 * @return {@code true} if vertices {@code v} and {@code w} are in the same
168 * connected component; {@code false} otherwise
169 * @throws IllegalArgumentException unless {@code 0 <= v < V}
170 * @throws IllegalArgumentException unless {@code 0 <= w < V}
171 */
172 public boolean connected(int v, int w) {
173 validateVertex(v);
174 validateVertex(w);
175 return id(v) == id(w);
176 }
177
178 /**
179 * Returns true if vertices {@code v} and {@code w} are in the same
180 * connected component.
181 *
182 * @param v one vertex
183 * @param w the other vertex
184 * @return {@code true} if vertices {@code v} and {@code w} are in the same
185 * connected component; {@code false} otherwise
186 * @throws IllegalArgumentException unless {@code 0 <= v < V}
187 * @throws IllegalArgumentException unless {@code 0 <= w < V}
188 * @deprecated Replaced by {@link #connected(int, int)}.
189 */
190 @Deprecated
191 public boolean areConnected(int v, int w) {
192 validateVertex(v);
193 validateVertex(w);
194 return id(v) == id(w);
195 }
196
197 // throw an IllegalArgumentException unless {@code 0 <= v < V}
198 private void validateVertex(int v) {
199 int V = marked.length;
200 if (v < 0 || v >= V)
201 throw new IllegalArgumentException("vertex " + v + " is not between 0 and " + (V-1));
202 }
203
204 /**
205 * Unit tests the {@code CC} data type.
206 *
207 * @param args the command-line arguments
208 */
209 public static void main(String[] args) {
210 In in = new In(args[0]);
211 Graph G = new Graph(in);
212 CC cc = new CC(G);
213
214 // number of connected components
215 int m = cc.count();
216 StdOut.println(m + " components");
217
218 // compute list of vertices in each connected component
219 Queue<Integer>[] components = (Queue<Integer>[]) new Queue[m];
220 for (int i = 0; i < m; i++) {
221 components[i] = new Queue<Integer>();
222 }
223 for (int v = 0; v < G.V(); v++) {
224 components[cc.id(v)].enqueue(v);
225 }
226
227 // print results
228 for (int i = 0; i < m; i++) {
229 for (int v : components[i]) {
230 StdOut.print(v + " ");
231 }
232 StdOut.println();
233 }
234 }
235 }
236
237 /******************************************************************************
238 * Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
239 *
240 * This file is part of algs4.jar, which accompanies the textbook
241 *
242 * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
243 * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
244 * http://algs4.cs.princeton.edu
245 *
246 *
247 * algs4.jar is free software: you can redistribute it and/or modify
248 * it under the terms of the GNU General Public License as published by
249 * the Free Software Foundation, either version 3 of the License, or
250 * (at your option) any later version.
251 *
252 * algs4.jar is distributed in the hope that it will be useful,
253 * but WITHOUT ANY WARRANTY; without even the implied warranty of
254 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
255 * GNU General Public License for more details.
256 *
257 * You should have received a copy of the GNU General Public License
258 * along with algs4.jar. If not, see http://www.gnu.org/licenses.
259 ******************************************************************************/
1 /******************************************************************************
2 * Compilation: javac CPM.java
3 * Execution: java CPM < input.txt
4 * Dependencies: EdgeWeightedDigraph.java AcyclicDigraphLP.java StdOut.java
5 * Data files: http://algs4.cs.princeton.edu/44sp/jobsPC.txt
6 *
7 * Critical path method.
8 *
9 * % java CPM < jobsPC.txt
10 * job start finish
11 * --------------------
12 * 0 0.0 41.0
13 * 1 41.0 92.0
14 * 2 123.0 173.0
15 * 3 91.0 127.0
16 * 4 70.0 108.0
17 * 5 0.0 45.0
18 * 6 70.0 91.0
19 * 7 41.0 73.0
20 * 8 91.0 123.0
21 * 9 41.0 70.0
22 * Finish time: 173.0
23 *
24 ******************************************************************************/
25
26 package edu.princeton.cs.algs4;
27
28 /**
29 * The {@code CPM} class provides a client that solves the
30 * parallel precedence-constrained job scheduling problem
31 * via the <em>critical path method</em>. It reduces the problem
32 * to the longest-paths problem in edge-weighted DAGs.
33 * It builds an edge-weighted digraph (which must be a DAG)
34 * from the job-scheduling problem specification,
35 * finds the longest-paths tree, and computes the longest-paths
36 * lengths (which are precisely the start times for each job).
37 * <p>
38 * This implementation uses {@link AcyclicLP} to find a longest
39 * path in a DAG.
40 * The running time is proportional to <em>V</em> + <em>E</em>,
41 * where <em>V</em> is the number of jobs and <em>E</em> is the
42 * number of precedence constraints.
43 * <p>
44 * For additional documentation,
45 * see <a href="http://algs4.cs.princeton.edu/44sp">Section 4.4</a> of
46 * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
47 *
48 * @author Robert Sedgewick
49 * @author Kevin Wayne
50 */
51 public class CPM {
52
53 // this class cannot be instantiated
54 private CPM() { }
55
56 /**
57 * Reads the precedence constraints from standard input
58 * and prints a feasible schedule to standard output.
59 *
60 * @param args the command-line arguments
61 */
62 public static void main(String[] args) {
63
64 // number of jobs
65 int n = StdIn.readInt();
66
67 // source and sink
68 int source = 2*n;
69 int sink = 2*n + 1;
70
71 // build network
72 EdgeWeightedDigraph G = new EdgeWeightedDigraph(2*n + 2);
73 for (int i = 0; i < n; i++) {
74 double duration = StdIn.readDouble();
75 G.addEdge(new DirectedEdge(source, i, 0.0));
76 G.addEdge(new DirectedEdge(i+n, sink, 0.0));
77 G.addEdge(new DirectedEdge(i, i+n, duration));
78
79 // precedence constraints
80 int m = StdIn.readInt();
81 for (int j = 0; j < m; j++) {
82 int precedent = StdIn.readInt();
83 G.addEdge(new DirectedEdge(n+i, precedent, 0.0));
84 }
85 }
86
87 // compute longest path
88 AcyclicLP lp = new AcyclicLP(G, source);
89
90 // print results
91 StdOut.println(" job start finish");
92 StdOut.println("--------------------");
93 for (int i = 0; i < n; i++) {
94 StdOut.printf("%4d %7.1f %7.1f\n", i, lp.distTo(i), lp.distTo(i+n));
95 }
96 StdOut.printf("Finish time: %7.1f\n", lp.distTo(sink));
97 }
98
99 }
100
101 /******************************************************************************
102 * Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
103 *
104 * This file is part of algs4.jar, which accompanies the textbook
105 *
106 * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
107 * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
108 * http://algs4.cs.princeton.edu
109 *
110 *
111 * algs4.jar is free software: you can redistribute it and/or modify
112 * it under the terms of the GNU General Public License as published by
113 * the Free Software Foundation, either version 3 of the License, or
114 * (at your option) any later version.
115 *
116 * algs4.jar is distributed in the hope that it will be useful,
117 * but WITHOUT ANY WARRANTY; without even the implied warranty of
118 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
119 * GNU General Public License for more details.
120 *
121 * You should have received a copy of the GNU General Public License
122 * along with algs4.jar. If not, see http://www.gnu.org/licenses.
123 ******************************************************************************/
1 /******************************************************************************
2 * Compilation: javac Cat.java
3 * Execution: java Cat input0.txt input1.txt ... output.txt
4 * Dependencies: In.java Out.java
5 * Data files: http://algs4.cs.princeton.edu/11model/in1.txt
6 * http://algs4.cs.princeton.edu/11model/in2.txt
7 *
8 * Reads in text files specified as the first command-line
9 * arguments, concatenates them, and writes the result to
10 * filename specified as the last command-line arguments.
11 *
12 * % more in1.txt
13 * This is
14 *
15 * % more in2.txt
16 * a tiny
17 * test.
18 *
19 * % java Cat in1.txt in2.txt out.txt
20 *
21 * % more out.txt
22 * This is
23 * a tiny
24 * test.
25 *
26 ******************************************************************************/
27
28 package edu.princeton.cs.algs4;
29
30 /**
31 * The {@code Cat} class provides a client for concatenating the results
32 * of several text files.
33 * <p>
34 * For additional documentation, see <a href="http://algs4.cs.princeton.edu/11model">Section 1.1</a> of
35 * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
36 *
37 * @author Robert Sedgewick
38 * @author Kevin Wayne
39 */
40 public class Cat {
41
42 // this class should not be instantiated
43 private Cat() { }
44
45 /**
46 * Reads in a sequence of text files specified as the first command-line
47 * arguments, concatenates them, and writes the results to the file
48 * specified as the last command-line argument.
49 *
50 * @param args the command-line arguments
51 */
52 public static void main(String[] args) {
53 Out out = new Out(args[args.length - 1]);
54 for (int i = 0; i < args.length - 1; i++) {
55 In in = new In(args[i]);
56 String s = in.readAll();
57 out.println(s);
58 in.close();
59 }
60 out.close();
61 }
62
63 }
64
65 /******************************************************************************
66 * Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
67 *
68 * This file is part of algs4.jar, which accompanies the textbook
69 *
70 * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
71 * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
72 * http://algs4.cs.princeton.edu
73 *
74 *
75 * algs4.jar is free software: you can redistribute it and/or modify
76 * it under the terms of the GNU General Public License as published by
77 * the Free Software Foundation, either version 3 of the License, or
78 * (at your option) any later version.
79 *
80 * algs4.jar is distributed in the hope that it will be useful,
81 * but WITHOUT ANY WARRANTY; without even the implied warranty of
82 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
83 * GNU General Public License for more details.
84 *
85 * You should have received a copy of the GNU General Public License
86 * along with algs4.jar. If not, see http://www.gnu.org/licenses.
87 ******************************************************************************/
No preview for this file type
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.