├── .gitignore ├── Assignment1 ├── Percolation.java └── PercolationStats.java ├── Assignment2 ├── Deque.java ├── RandomizedQueue.java └── Subset.java ├── Assignment3 ├── Brute.java ├── Fast.java ├── Fast2.java ├── Point.java ├── input6.txt └── input8.txt ├── Assignment4 ├── Board.java ├── Solver.java ├── puzzle-unsolvable3x3.txt └── puzzle04.txt ├── Assignment5 ├── KdTree.java ├── KdTreeVisualizer.java ├── NearestNeighborVisualizer.java ├── PointSET.java ├── RangeSearchVisualizer.java ├── RectHV.java └── input100K.txt └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | *.zip 2 | *.DS_Store 3 | *.class -------------------------------------------------------------------------------- /Assignment1/Percolation.java: -------------------------------------------------------------------------------- 1 | public class Percolation { 2 | private boolean[][] opened; 3 | private int top; 4 | private int bottom; 5 | private WeightedQuickUnionUF uf; 6 | private WeightedQuickUnionUF uf2; 7 | private int len; 8 | 9 | public Percolation(int N) 10 | { 11 | if (N <= 0) { 12 | throw new IllegalArgumentException("Given N <= 0"); 13 | } 14 | opened = new boolean[N][N]; 15 | uf = new WeightedQuickUnionUF(N*N + 2); 16 | uf2 = new WeightedQuickUnionUF(N*N + 1); 17 | top = N*N; 18 | bottom = N*N + 1; 19 | len = N; 20 | } 21 | 22 | public void open(int i, int j) 23 | { 24 | if (checkIndex(i, j)) { 25 | opened[i-1][j-1] = true; 26 | if (i == 1) { 27 | uf.union(j-1, top); 28 | uf2.union(j-1, top); 29 | } 30 | if (i == len) uf.union((i-1)*len+j-1, bottom); 31 | if (i > 1 && isOpen(i-1, j)) { 32 | uf.union((i-1)*len+j-1, (i-2)*len+j-1); 33 | uf2.union((i-1)*len+j-1, (i-2)*len+j-1); 34 | } 35 | if (i < len && isOpen(i+1, j)) { 36 | uf.union((i-1)*len+j-1, i*len+j-1); 37 | uf2.union((i-1)*len+j-1, i*len+j-1); 38 | } 39 | if (j > 1 && isOpen(i, j-1)) { 40 | uf.union((i-1)*len+j-1, (i-1)*len+j-2); 41 | uf2.union((i-1)*len+j-1, (i-1)*len+j-2); 42 | } 43 | if (j < len && isOpen(i, j+1)) { 44 | uf.union((i-1)*len+j-1, (i-1)*len+j); 45 | uf2.union((i-1)*len+j-1, (i-1)*len+j); 46 | } 47 | } else { 48 | throw new IndexOutOfBoundsException(); 49 | } 50 | } 51 | 52 | public boolean isOpen(int i, int j) 53 | { 54 | if (checkIndex(i, j)) { 55 | return opened[i-1][j-1]; 56 | } 57 | throw new IndexOutOfBoundsException(); 58 | } 59 | 60 | public boolean isFull(int i, int j) 61 | { 62 | if (checkIndex(i, j)) { 63 | return uf2.connected((i-1)*len+j-1, top); 64 | } 65 | throw new IndexOutOfBoundsException(); 66 | } 67 | 68 | public boolean percolates() 69 | { 70 | return uf.connected(top, bottom); 71 | } 72 | 73 | private boolean checkIndex(int i, int j) 74 | { 75 | if (i < 1 || i > len || j < 1 || j > len) return false; 76 | return true; 77 | } 78 | } -------------------------------------------------------------------------------- /Assignment1/PercolationStats.java: -------------------------------------------------------------------------------- 1 | public class PercolationStats { 2 | private double[] x; 3 | private int experiments; 4 | 5 | // perform T independent computational experiments on an N-by-N grid 6 | public PercolationStats(int N, int T) 7 | { 8 | experiments = T; 9 | if (N <= 0 || T <= 0) { 10 | throw new IllegalArgumentException("Given N <= 0 || T <= 0"); 11 | } 12 | 13 | x = new double[experiments]; 14 | for (int t = 0; t < experiments; t++) 15 | { 16 | int numOfOpens = 0; 17 | Percolation pc = new Percolation(N); 18 | while (!pc.percolates()) 19 | { 20 | int i = StdRandom.uniform(1, N+1); 21 | int j = StdRandom.uniform(1, N+1); 22 | if (!pc.isOpen(i, j) && !pc.isFull(i, j)) { 23 | pc.open(i, j); 24 | numOfOpens++; 25 | } 26 | } 27 | x[t] = (double) numOfOpens/(N*N); 28 | } 29 | } 30 | 31 | // sample mean of percolation threshold 32 | public double mean() 33 | { 34 | return StdStats.mean(x); 35 | } 36 | 37 | // sample standard deviation of percolation threshold 38 | public double stddev() 39 | { 40 | return StdStats.stddev(x); 41 | } 42 | 43 | // returns lower bound of the 95% confidence interval 44 | public double confidenceLo() 45 | { 46 | return mean() - ((1.96 * stddev()) / Math.sqrt(experiments)); 47 | } 48 | 49 | // returns upper bound of the 95% confidence interval 50 | public double confidenceHi() 51 | { 52 | return mean() + ((1.96 * stddev()) / Math.sqrt(experiments)); 53 | } 54 | 55 | public static void main(String[] args) 56 | { 57 | PercolationStats ps = new PercolationStats(Integer.parseInt(args[0]), Integer.parseInt(args[1])); 58 | 59 | String confidence = ps.confidenceLo() + ", " + ps.confidenceHi(); 60 | StdOut.println("mean = " + ps.mean()); 61 | StdOut.println("stddev = " + ps.stddev()); 62 | StdOut.println("95% confidence interval = " + confidence); 63 | } 64 | } -------------------------------------------------------------------------------- /Assignment2/Deque.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | 3 | public class Deque implements Iterable { 4 | private Node first, last; 5 | private int size; 6 | 7 | private class Node 8 | { 9 | Item item; 10 | Node next; 11 | Node prev; 12 | } 13 | 14 | public Deque() 15 | { 16 | size = 0; 17 | first = null; 18 | last = null; 19 | } 20 | 21 | private class DequeIterator implements Iterator 22 | { 23 | private Node current = first; 24 | 25 | public boolean hasNext() { return current != null; } 26 | public void remove() { throw new java.lang.UnsupportedOperationException(); } 27 | public Item next() 28 | { 29 | if (!hasNext()) throw new java.util.NoSuchElementException(); 30 | Item item = current.item; 31 | current = current.next; 32 | return item; 33 | } 34 | } 35 | 36 | public boolean isEmpty() { return size == 0; } 37 | 38 | public int size() { return size; } 39 | 40 | public void addFirst(Item item) 41 | { 42 | if (item == null) throw new NullPointerException(); 43 | Node oldfirst = first; 44 | first = new Node(); 45 | first.item = item; 46 | first.next = oldfirst; 47 | first.prev = null; 48 | if (isEmpty()) last = first; 49 | else oldfirst.prev = first; 50 | size++; 51 | } 52 | 53 | public void addLast(Item item) 54 | { 55 | if (item == null) throw new java.lang.NullPointerException(); 56 | Node oldlast = last; 57 | last = new Node(); 58 | last.item = item; 59 | last.next = null; 60 | last.prev = oldlast; 61 | if (isEmpty()) first = last; 62 | else oldlast.next = last; 63 | size++; 64 | } 65 | 66 | public Item removeFirst() 67 | { 68 | if (isEmpty()) throw new java.util.NoSuchElementException(); 69 | Item item = first.item; 70 | first = first.next; 71 | size--; 72 | if (isEmpty()) last = first; 73 | else first.prev = null; 74 | return item; 75 | } 76 | 77 | public Item removeLast() 78 | { 79 | if (isEmpty()) throw new java.util.NoSuchElementException(); 80 | Item item = last.item; 81 | last = last.prev; 82 | size--; 83 | if (isEmpty()) first = last; 84 | else last.next = null; 85 | return item; 86 | } 87 | 88 | public Iterator iterator() { return new DequeIterator(); } 89 | 90 | 91 | // public static void main(String[] args) { ; } 92 | } -------------------------------------------------------------------------------- /Assignment2/RandomizedQueue.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | 3 | public class RandomizedQueue implements Iterable { 4 | private int size; 5 | private Item[] s; 6 | 7 | public RandomizedQueue() 8 | { 9 | size = 0; 10 | s = (Item[]) new Object[1]; 11 | } 12 | 13 | private class RandomizedQueueIterator implements Iterator 14 | { 15 | private int i = size; 16 | private int[] order; 17 | 18 | public RandomizedQueueIterator() 19 | { 20 | order = new int[i]; 21 | for (int j = 0; j < i; ++j) { 22 | order[j] = j; 23 | } 24 | StdRandom.shuffle(order); 25 | } 26 | 27 | public boolean hasNext() { return i > 0; } 28 | public void remove() { throw new java.lang.UnsupportedOperationException(); } 29 | public Item next() 30 | { 31 | if (!hasNext()) throw new java.util.NoSuchElementException(); 32 | return s[order[--i]]; 33 | } 34 | } 35 | 36 | public boolean isEmpty() { return size == 0; } 37 | 38 | public int size() { return size; } 39 | 40 | private void resize(int capacity) 41 | { 42 | Item[] copy = (Item[]) new Object[capacity]; 43 | for (int i = 0; i < size; i++) 44 | copy[i] = s[i]; 45 | s = copy; 46 | } 47 | 48 | public void enqueue(Item item) 49 | { 50 | if (item == null) throw new NullPointerException(); 51 | s[size++] = item; 52 | if (size == s.length) resize(2 * s.length); 53 | } 54 | 55 | public Item dequeue() 56 | { 57 | if (size == 0) throw new java.util.NoSuchElementException(); 58 | int r = StdRandom.uniform(size); 59 | Item item = s[r]; 60 | s[r] = s[size-1]; 61 | s[--size] = null; 62 | if (size > 0 && size == s.length/4) resize(s.length/2); 63 | return item; 64 | } 65 | 66 | public Item sample() 67 | { 68 | if (size == 0) throw new java.util.NoSuchElementException(); 69 | int r = StdRandom.uniform(size); 70 | return s[r]; 71 | } 72 | 73 | public Iterator iterator() { return new RandomizedQueueIterator(); } 74 | 75 | // public static void main(String[] args) { ; } 76 | } -------------------------------------------------------------------------------- /Assignment2/Subset.java: -------------------------------------------------------------------------------- 1 | public class Subset { 2 | public static void main(String[] args) 3 | { 4 | RandomizedQueue strs = new RandomizedQueue(); 5 | while (!StdIn.isEmpty()) { 6 | strs.enqueue(StdIn.readString()); 7 | } 8 | 9 | int k = Integer.parseInt(args[0]); 10 | for (int i = 0; i < k; i++) { 11 | StdOut.println(strs.dequeue()); 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /Assignment3/Brute.java: -------------------------------------------------------------------------------- 1 | public class Brute { 2 | public static void main(String[] args) { 3 | In in = new In(args[0]); 4 | int N = in.readInt(); 5 | Point[] points = new Point[N]; 6 | 7 | StdDraw.setXscale(0, 32768); 8 | StdDraw.setYscale(0, 32768); 9 | 10 | for (int j = 0; j < N; j++) { 11 | int x = in.readInt(); 12 | int y = in.readInt(); 13 | Point point = new Point(x, y); 14 | points[j] = point; 15 | point.draw(); 16 | } 17 | 18 | Quick.sort(points); 19 | 20 | for (int p = 0; p < N; p++) { 21 | for (int q = p+1; q < N; q++) { 22 | for (int r = q+1; r < N; r++) { 23 | for (int s = r+1; s < N; s++) { 24 | if (points[p].slopeTo(points[q]) == points[p].slopeTo(points[r]) && points[p].slopeTo(points[q]) == points[p].slopeTo(points[s])) { 25 | StdOut.println(points[p].toString() + " -> " + points[q].toString() + " -> " + points[r].toString() + " -> " +points[s].toString()); 26 | points[p].drawTo(points[s]); 27 | } 28 | } 29 | } 30 | } 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Assignment3/Fast.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Fast { 4 | public static void main(String[] args) { 5 | In in = new In(args[0]); 6 | int N = in.readInt(); 7 | Point[] points = new Point[N]; 8 | Point[] ySortPoints = new Point[N]; 9 | Point[] result = new Point[N]; 10 | 11 | 12 | StdDraw.setXscale(0, 32768); 13 | StdDraw.setYscale(0, 32768); 14 | 15 | for (int j = 0; j < N; j++) { 16 | int x = in.readInt(); 17 | int y = in.readInt(); 18 | Point point = new Point(x, y); 19 | points[j] = point; 20 | ySortPoints[j] = point; 21 | point.draw(); 22 | } 23 | 24 | Arrays.sort(ySortPoints); 25 | Arrays.sort(points); 26 | 27 | HashSet set = new HashSet(); 28 | 29 | for (int i = 0; i < N; i++) { 30 | Arrays.sort(points, ySortPoints[i].SLOPE_ORDER); 31 | int count = 1; 32 | for (int j = 1; j < N; j++) { 33 | if (ySortPoints[i].slopeTo(points[j-1]) == ySortPoints[i].slopeTo(points[j])) { 34 | result[count++] = points[j]; 35 | } else { 36 | if (count >= 3) { 37 | result[count++] = ySortPoints[i]; 38 | Arrays.sort(result, 0, count); 39 | if (!set.contains(result[0].toString() + result[count-1].toString())) { 40 | for (int k = 0; k < count-1; k++) { 41 | StdOut.print(result[k].toString() + " -> "); 42 | } 43 | StdOut.print(result[count-1].toString() + "\n"); 44 | set.add(result[0].toString() + result[count-1].toString()); 45 | result[0].drawTo(result[count-1]); 46 | result = new Point[N]; 47 | } 48 | } 49 | result[0] = points[j]; 50 | count = 1; 51 | } 52 | // This part need to be fixed. Too ugly to process the end case. 53 | if (count >= 3 && j == N-1) { 54 | result[count++] = ySortPoints[i]; 55 | Arrays.sort(result, 0, count); 56 | if (!set.contains(result[0].toString() + result[count-1].toString())) { 57 | for (int k = 0; k < count-1; k++) { 58 | StdOut.print(result[k].toString() + " -> "); 59 | } 60 | StdOut.print(result[count-1].toString() + "\n"); 61 | set.add(result[0].toString() + result[count-1].toString()); 62 | result[0].drawTo(result[count-1]); 63 | result = new Point[N]; 64 | } 65 | } 66 | } 67 | } 68 | } 69 | } -------------------------------------------------------------------------------- /Assignment3/Fast2.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Fast2 { 4 | public static void main(String[] args) { 5 | // Rescale the coordinate system. 6 | StdDraw.setXscale(0, 32768); 7 | StdDraw.setYscale(0, 32768); 8 | // Read points from the input file. 9 | In in = new In(args[0]); 10 | int pointsCount = in.readInt(); 11 | Point[] points = new Point[pointsCount]; 12 | for (int i = 0; i < pointsCount; i++) { 13 | int x = in.readInt(); 14 | int y = in.readInt(); 15 | points[i] = new Point(x, y); 16 | points[i].draw(); 17 | } 18 | // Go each point p. 19 | for (int p = 0; p < pointsCount; p++) { 20 | // Sort the points according to the slopes they makes with p. 21 | Arrays.sort(points, points[p].SLOPE_ORDER); 22 | // Check if any 3 (or more) adjacent points in the sorted order have equal slopes with respect to p 23 | ArrayList collinearPoints = new ArrayList(pointsCount); 24 | for (int q = 0; q < pointsCount - 1; q++) { 25 | if (p == q) { 26 | continue; 27 | } 28 | if (collinearPoints.isEmpty()) { 29 | collinearPoints.add(points[q]); 30 | } else if (points[p].slopeTo(points[q - 1]) == points[p].slopeTo(points[q])) { 31 | collinearPoints.add(points[q]); 32 | } else if (collinearPoints.size() > 2) { 33 | // Draw collinear points. 34 | collinearPoints.add(points[p]); 35 | Collections.sort(collinearPoints); 36 | // Display collinear points. 37 | for (int i = 0; i < 3; i++) { 38 | StdOut.print(collinearPoints.get(i)); 39 | StdOut.print(" -> "); 40 | } 41 | StdOut.println(Collections.max(collinearPoints)); 42 | Collections.min(collinearPoints).drawTo(Collections.max(collinearPoints)); 43 | break; 44 | } else { 45 | collinearPoints.clear(); 46 | collinearPoints.add(points[q]); 47 | } 48 | } 49 | } 50 | } 51 | } -------------------------------------------------------------------------------- /Assignment3/Point.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Name: 3 | * Email: 4 | * 5 | * Compilation: javac Point.java 6 | * Execution: 7 | * Dependencies: StdDraw.java 8 | * 9 | * Description: An immutable data type for points in the plane. 10 | * 11 | *************************************************************************/ 12 | 13 | import java.util.Comparator; 14 | 15 | public class Point implements Comparable { 16 | 17 | // compare points by slope 18 | public final Comparator SLOPE_ORDER = new BySlope(); // YOUR DEFINITION HERE 19 | 20 | private final int x; // x coordinate 21 | private final int y; // y coordinate 22 | 23 | // create the point (x, y) 24 | public Point(int x, int y) { 25 | /* DO NOT MODIFY */ 26 | this.x = x; 27 | this.y = y; 28 | } 29 | 30 | 31 | private class BySlope implements Comparator { 32 | public int compare(Point point1, Point point2) { 33 | if (slopeTo(point1) < slopeTo(point2)) return -1; 34 | if (slopeTo(point1) > slopeTo(point2)) return 1; 35 | return 0; 36 | } 37 | } 38 | // plot this point to standard drawing 39 | public void draw() { 40 | /* DO NOT MODIFY */ 41 | StdDraw.point(x, y); 42 | } 43 | 44 | // draw line between this point and that point to standard drawing 45 | public void drawTo(Point that) { 46 | /* DO NOT MODIFY */ 47 | StdDraw.line(this.x, this.y, that.x, that.y); 48 | } 49 | 50 | // slope between this point and that point 51 | public double slopeTo(Point that) { 52 | /* YOUR CODE HERE */ 53 | if (that.y == this.y && that.x == this.x) return Double.NEGATIVE_INFINITY; 54 | if (that.x == this.x) return Double.POSITIVE_INFINITY; 55 | if (that.y == this.y) return 0; 56 | return (double) (that.y-this.y) / (that.x-this.x); 57 | } 58 | 59 | // is this point lexicographically smaller than that one? 60 | // comparing y-coordinates and breaking ties by x-coordinates 61 | public int compareTo(Point that) { 62 | /* YOUR CODE HERE */ 63 | if (this.y < that.y) return -1; 64 | if (this.y > that.y) return 1; 65 | if (this.x < that.x) return -1; 66 | if (this.x > that.x) return 1; 67 | return 0; 68 | } 69 | 70 | // return string representation of this point 71 | public String toString() { 72 | /* DO NOT MODIFY */ 73 | return "(" + x + ", " + y + ")"; 74 | } 75 | 76 | // unit test 77 | public static void main(String[] args) { 78 | /* YOUR CODE HERE */ 79 | } 80 | } -------------------------------------------------------------------------------- /Assignment3/input6.txt: -------------------------------------------------------------------------------- 1 | 6 2 | 19000 10000 3 | 18000 10000 4 | 32000 10000 5 | 21000 10000 6 | 1234 5678 7 | 14000 10000 -------------------------------------------------------------------------------- /Assignment3/input8.txt: -------------------------------------------------------------------------------- 1 | 12 2 | 10000 0 3 | 0 10000 4 | 3000 7000 5 | 7000 3000 6 | 20000 21000 7 | 3000 4000 8 | 14000 15000 9 | 6000 7000 10 | 1000 17000 11 | 1000 27000 12 | 1000 28000 13 | 1000 31000 -------------------------------------------------------------------------------- /Assignment4/Board.java: -------------------------------------------------------------------------------- 1 | public class Board { 2 | // construct a board from an N-by-N array of blocks 3 | // (where blocks[i][j] = block in row i, column j) 4 | 5 | private final int N; 6 | private final int[][] data; 7 | 8 | public Board(int[][] blocks) { 9 | this(blocks, 0); 10 | } 11 | 12 | private Board(int[][] blocks, int moves) { 13 | this.N = blocks.length; 14 | this.data = new int[N][N]; 15 | 16 | for (int i = 0; i < N; i++) { 17 | for (int j = 0; j < N; j++) { 18 | this.data[i][j] = blocks[i][j]; 19 | } 20 | } 21 | } 22 | 23 | // board dimension N 24 | public int dimension() { 25 | return N; 26 | } 27 | 28 | // number of blocks out of place 29 | public int hamming() { 30 | int num, hammingValue = 0; 31 | for (int i = 0; i < N; i++) { 32 | for (int j = 0; j < N; j++) { 33 | num = i * N + j + 1; 34 | if (i == N-1 && j == N-1) break; 35 | if (data[i][j] != num) hammingValue++; 36 | num++; 37 | } 38 | } 39 | return hammingValue; 40 | } 41 | 42 | // sum of Manhattan distances between blocks and goal 43 | public int manhattan() { 44 | int manhattanValue = 0; 45 | for (int i = 0; i < N; i++) { 46 | for (int j = 0; j < N; j++) { 47 | if (data[i][j] == 0) continue; 48 | int iTmp = (data[i][j]-1) / N; 49 | int jTmp = (data[i][j]-1) % N; 50 | manhattanValue += (Math.abs(iTmp - i) + Math.abs(jTmp - j)); 51 | } 52 | } 53 | return manhattanValue; 54 | } 55 | 56 | // is this board the goal board? 57 | public boolean isGoal() { 58 | int num = 1; 59 | if (data[N-1][N-1] != 0) return false; 60 | 61 | for (int i = 0; i < N; i++) { 62 | for (int j = 0; j < N; j++) { 63 | if (data[i][j] == 0) break; 64 | if (data[i][j] != num) return false; 65 | num++; 66 | } 67 | } 68 | return true; 69 | } 70 | 71 | // a board obtained by exchanging two adjacent blocks in the same row 72 | public Board twin() { 73 | Board bb = new Board(data); 74 | 75 | if (bb.data[0][0] == 0) { 76 | exch(bb.data, 1, 0, 1, 1); 77 | } else if (bb.data[0][1] == 0) { 78 | exch(bb.data, 1, 0, 1, 1); 79 | } else { 80 | exch(bb.data, 0, 0, 0, 1); 81 | } 82 | return bb; 83 | } 84 | 85 | // does this board equal y? 86 | public boolean equals(Object Y) { 87 | if (Y == null) return false; 88 | if (Y == this) return true; 89 | 90 | if (Y.getClass() != this.getClass()) return false; 91 | 92 | Board that = (Board) Y; 93 | 94 | if (that.dimension() != this.dimension()) return false; 95 | 96 | for (int i = 0; i < N; i++) { 97 | for (int j = 0; j < N; j++) { 98 | if (this.data[i][j] != (that.data)[i][j]) return false; 99 | } 100 | } 101 | return true; 102 | } 103 | 104 | // all neighboring boards 105 | public Iterable neighbors() { 106 | Stack stack = new Stack(); 107 | 108 | int row = 0, col = 0; 109 | int[][] dataTmp = new int[N][N]; 110 | 111 | for (int i = 0; i < N; i++) { 112 | for (int j = 0; j < N; j++) { 113 | dataTmp[i][j] = data[i][j]; 114 | if (data[i][j] == 0) { 115 | row = i; 116 | col = j; 117 | } 118 | } 119 | } 120 | 121 | // shift with left 122 | if (col > 0) { 123 | exch(dataTmp, row, col, row, col-1); 124 | stack.push(new Board(dataTmp)); 125 | exch(dataTmp, row, col, row, col-1); 126 | } 127 | 128 | // shift with right 129 | if (col < N-1) { 130 | exch(dataTmp, row, col, row, col+1); 131 | stack.push(new Board(dataTmp)); 132 | exch(dataTmp, row, col, row, col+1); 133 | } 134 | 135 | // shift with up 136 | if (row > 0) { 137 | exch(dataTmp, row, col, row-1, col); 138 | stack.push(new Board(dataTmp)); 139 | exch(dataTmp, row, col, row-1, col); 140 | } 141 | 142 | // shift with down 143 | if (row < N-1) { 144 | exch(dataTmp, row, col, row+1, col); 145 | stack.push(new Board(dataTmp)); 146 | exch(dataTmp, row, col, row+1, col); 147 | } 148 | return stack; 149 | } 150 | 151 | private void exch(int[][] matrix, int i, int j, int p, int q) { 152 | int tmp = matrix[i][j]; 153 | matrix[i][j] = matrix[p][q]; 154 | matrix[p][q] = tmp; 155 | } 156 | 157 | // string representation of the board (in the output format specified below) 158 | public String toString() { 159 | StringBuilder str = new StringBuilder(dimension() + "\n"); 160 | 161 | for (int i = 0; i < N; i++) { 162 | for (int j = 0; j < N; j++) { 163 | str.append(data[i][j]); 164 | str.append(" "); 165 | } 166 | str.append("\n"); 167 | } 168 | return str.toString(); 169 | } 170 | 171 | // public static void main(String[] args) { 172 | // int[][] input = new int[][]{{0, 1, 3}, {4, 2, 5}, {7, 8, 6}}; 173 | // int[][] input2 = new int[][]{{8, 1, 3}, {4, 0, 2}, {7, 6, 5}}; 174 | // int[][] input3 = new int[][]{{0, 5, 7}, {1, 8, 4}, {3, 2, 6}}; 175 | // 176 | // Board testBoard = new Board(input); 177 | // Board testBoard2 = new Board(input2); 178 | // Board testBoard3 = new Board(input3); 179 | // 180 | // StdOut.println(testBoard3.manhattan()); 181 | // 182 | // Iterable result = testBoard.neighbors(); 183 | // 184 | // for (Board b : result) { 185 | // StdOut.println(b.toString()); 186 | // } 187 | // } 188 | } -------------------------------------------------------------------------------- /Assignment4/Solver.java: -------------------------------------------------------------------------------- 1 | import java.util.Comparator; 2 | 3 | public class Solver { 4 | 5 | private MinPQ pq; 6 | private MinPQ pqTwin; 7 | private Node finalNode; 8 | private boolean solvable; 9 | 10 | private class Node { 11 | private Board board; 12 | private Node prevNode; 13 | 14 | public Node(Board board, Node prevNode) { 15 | this.board = board; 16 | this.prevNode = prevNode; 17 | } 18 | } 19 | 20 | public Solver(Board initial) { 21 | pq = new MinPQ(nodeComparator); 22 | pqTwin = new MinPQ(nodeComparator); 23 | 24 | solvable = false; 25 | 26 | Node node = new Node(initial, null); 27 | Node nodeTwin = new Node(initial.twin(), null); 28 | 29 | pq.insert(node); 30 | pqTwin.insert(nodeTwin); 31 | 32 | node = pq.delMin(); 33 | nodeTwin = pqTwin.delMin(); 34 | 35 | while (!node.board.isGoal() && !nodeTwin.board.isGoal()) { 36 | 37 | for (Board b : node.board.neighbors()) { 38 | if (node.prevNode == null || !b.equals(node.prevNode.board)) { 39 | Node neighbor = new Node(b, node); 40 | pq.insert(neighbor); 41 | } 42 | } 43 | 44 | for (Board bTwin : nodeTwin.board.neighbors()) { 45 | if (nodeTwin.prevNode == null || !bTwin.equals(nodeTwin.prevNode.board)) { 46 | Node neighbor = new Node(bTwin, nodeTwin); 47 | pqTwin.insert(neighbor); 48 | } 49 | } 50 | 51 | node = pq.delMin(); 52 | nodeTwin = pqTwin.delMin(); 53 | } 54 | 55 | if (node.board.isGoal()) { 56 | solvable = true; 57 | finalNode = node; 58 | } 59 | } 60 | 61 | // is the initial board solvable? 62 | public boolean isSolvable() { 63 | return solvable; 64 | } 65 | 66 | // min number of moves to solve initial board; -1 if no solution 67 | public int moves() { 68 | if (!solvable) return -1; 69 | Node current = finalNode; 70 | int moves = 0; 71 | 72 | while (current.prevNode != null) { 73 | moves++; 74 | current = current.prevNode; 75 | } 76 | return moves; 77 | } 78 | 79 | // to add number of moves to hamming or manhattan distance 80 | private static int numMoves(Node node) { 81 | int moves = 0; 82 | Node current = node; 83 | 84 | while (current.prevNode != null) { 85 | moves++; 86 | current = current.prevNode; 87 | } 88 | return moves; 89 | } 90 | 91 | // sequence of boards in a shortest solution; null if no solution 92 | public Iterable solution() { 93 | if (!solvable) return null; 94 | 95 | Node current = finalNode; 96 | Stack boards = new Stack(); 97 | boards.push(current.board); 98 | 99 | while (current.prevNode != null) { 100 | boards.push(current.prevNode.board); 101 | current = current.prevNode; 102 | } 103 | return boards; 104 | } 105 | 106 | private Comparator nodeComparator = new Comparator() { 107 | @Override 108 | public int compare(Node a, Node b) { 109 | return a.board.manhattan() + numMoves(a) - b.board.manhattan() - numMoves(b); 110 | } 111 | }; 112 | 113 | // solve a slider puzzle (given below) 114 | public static void main(String[] args) { 115 | // create initial board from file 116 | In in = new In(args[0]); 117 | int N = in.readInt(); 118 | int[][] blocks = new int[N][N]; 119 | for (int i = 0; i < N; i++) 120 | for (int j = 0; j < N; j++) 121 | blocks[i][j] = in.readInt(); 122 | Board initial = new Board(blocks); 123 | 124 | // solve the puzzle 125 | Solver solver = new Solver(initial); 126 | 127 | // print solution to standard output 128 | if (!solver.isSolvable()) 129 | StdOut.println("No solution possible"); 130 | else { 131 | StdOut.println("Minimum number of moves = " + solver.moves()); 132 | for (Board board : solver.solution()) 133 | StdOut.println(board); 134 | } 135 | } 136 | } -------------------------------------------------------------------------------- /Assignment4/puzzle-unsolvable3x3.txt: -------------------------------------------------------------------------------- 1 | 3 2 | 1 2 3 3 | 4 5 6 4 | 8 7 0 -------------------------------------------------------------------------------- /Assignment4/puzzle04.txt: -------------------------------------------------------------------------------- 1 | 3 2 | 0 1 3 3 | 4 2 5 4 | 7 8 6 -------------------------------------------------------------------------------- /Assignment5/KdTree.java: -------------------------------------------------------------------------------- 1 | public class KdTree { 2 | private Node root; 3 | private int size; 4 | private RectHV board; 5 | 6 | private class Node { 7 | private Point2D key; 8 | private Point2D val; 9 | private Node left, right; 10 | private boolean isHorizontal = false; 11 | 12 | public Node(Point2D key, Point2D val, Node left, Node right, boolean isHorizontal) { 13 | this.key = key; 14 | this.val = val; 15 | this.left = left; 16 | this.right = right; 17 | this.isHorizontal = isHorizontal; 18 | } 19 | } 20 | 21 | // construct an empty set of points 22 | public KdTree() { 23 | root = null; 24 | size = 0; 25 | board = new RectHV(0, 0, 1.0, 1.0); 26 | } 27 | 28 | // is the set empty? 29 | public boolean isEmpty() { 30 | return size == 0; 31 | } 32 | 33 | // number of points in the set 34 | public int size() { 35 | return size; 36 | } 37 | 38 | // add the point to the set (if it is not already in the set) 39 | // refer to BST put function 40 | public void insert(Point2D p) { 41 | root = put(root, p, p, false); 42 | } 43 | 44 | private Node put(Node node, Point2D key, Point2D val, boolean isHorizontal) { 45 | if (node == null) { 46 | size++; 47 | return new Node(key, val, null, null, isHorizontal); 48 | } 49 | 50 | if (node.key.x() == key.x() && node.key.y() == key.y()) { 51 | node.val = val; 52 | } else if ((!node.isHorizontal && node.key.x() >= key.x()) || (node.isHorizontal && node.key.y() >= key.y())) { 53 | node.left = put(node.left, key, val, !isHorizontal); 54 | } else { 55 | node.right = put(node.right, key, val, !isHorizontal); 56 | } 57 | 58 | return node; 59 | } 60 | 61 | 62 | // does the set contain point p? 63 | public boolean contains(Point2D p) { 64 | Node node = root; 65 | while (node != null) { 66 | if (node.key.x() == p.x() && node.key.y() == p.y()) { 67 | return true; 68 | } else if ((!node.isHorizontal && node.key.x() >= p.x()) || (node.isHorizontal && node.key.y() >= p.y())) { 69 | node = node.left; 70 | } else { 71 | node = node.right; 72 | } 73 | } 74 | return false; 75 | } 76 | 77 | // draw all points to standard draw 78 | public void draw() { 79 | StdDraw.setScale(0, 1); 80 | draw(root, board); 81 | } 82 | 83 | private void draw(Node node, RectHV rect) { 84 | if (node != null) { 85 | StdDraw.setPenColor(StdDraw.BLACK); 86 | StdDraw.setPenRadius(0.02); 87 | new Point2D(node.key.x(), node.key.y()).draw(); 88 | StdDraw.setPenRadius(); 89 | 90 | if (!node.isHorizontal) { 91 | StdDraw.setPenColor(StdDraw.RED); 92 | new Point2D(node.key.x(), rect.ymin()).drawTo(new Point2D(node.key.x(), rect.ymax())); 93 | } else { 94 | StdDraw.setPenColor(StdDraw.BLUE); 95 | new Point2D(rect.xmin(), node.key.y()).drawTo(new Point2D(rect.xmax(), node.key.y())); 96 | } 97 | draw(node.left, leftRect(rect, node)); 98 | draw(node.right, rightRect(rect, node)); 99 | } 100 | } 101 | 102 | // all points that are inside the rectangle 103 | public Iterable range(RectHV rect) { 104 | Stack points = new Stack(); 105 | get(root, board, rect, points); 106 | return points; 107 | } 108 | 109 | private RectHV leftRect(RectHV rect, Node p) { 110 | if (p.isHorizontal) { 111 | return new RectHV(rect.xmin(), rect.ymin(), rect.xmax(), p.key.y()); 112 | } 113 | return new RectHV(rect.xmin(), rect.ymin(), p.key.x(), rect.ymax()); 114 | } 115 | 116 | private RectHV rightRect(RectHV rect, Node p) { 117 | if (p.isHorizontal) { 118 | return new RectHV(rect.xmin(), p.key.y(), rect.xmax(), rect.ymax()); 119 | } 120 | return new RectHV(p.key.x(), rect.ymin(), rect.xmax(), rect.ymax()); 121 | } 122 | 123 | private void get(Node node, RectHV nodeRect, RectHV rect, Stack pointsIn) { 124 | if (node != null) { 125 | if (nodeRect.intersects(rect)) { 126 | if (rect.contains(node.val)) pointsIn.push(node.val); 127 | get(node.left, leftRect(nodeRect, node), rect, pointsIn); 128 | get(node.right, rightRect(nodeRect, node), rect, pointsIn); 129 | } 130 | } 131 | } 132 | 133 | private Point2D nearestNeigh(Node node, RectHV rect, Point2D point, Point2D nearPoint) { 134 | Point2D nearestPoint = nearPoint; 135 | if (node != null) { 136 | if (nearestPoint == null || nearestPoint.distanceSquaredTo(point) > rect.distanceSquaredTo(point)) { 137 | if (nearestPoint == null) { 138 | nearestPoint = node.key; 139 | } else { 140 | if (node.key.distanceSquaredTo(point) < nearestPoint.distanceSquaredTo(point)) { 141 | nearestPoint = node.key; 142 | } 143 | } 144 | 145 | if (!node.isHorizontal) { 146 | RectHV leftRect = new RectHV(rect.xmin(), rect.ymin(), node.key.x(), rect.ymax()); 147 | RectHV rightRect = new RectHV(node.key.x(), rect.ymin(), rect.xmax(), rect.ymax()); 148 | if (point.x() <= node.key.x()) { 149 | nearestPoint = nearestNeigh(node.left, leftRect, point, nearestPoint); 150 | nearestPoint = nearestNeigh(node.right, rightRect, point, nearestPoint); 151 | } else { 152 | nearestPoint = nearestNeigh(node.right, rightRect, point, nearestPoint); 153 | nearestPoint = nearestNeigh(node.left, leftRect, point, nearestPoint); 154 | } 155 | } else { 156 | RectHV leftRect = new RectHV(rect.xmin(), rect.ymin(), rect.xmax(), node.key.y()); 157 | RectHV rightRect = new RectHV(rect.xmin(), node.key.y(), rect.xmax(), rect.ymax()); 158 | if (point.y() <= node.key.y()) { 159 | nearestPoint = nearestNeigh(node.left, leftRect, point, nearestPoint); 160 | nearestPoint = nearestNeigh(node.right, rightRect, point, nearestPoint); 161 | } else { 162 | nearestPoint = nearestNeigh(node.right, rightRect, point, nearestPoint); 163 | nearestPoint = nearestNeigh(node.left, leftRect, point, nearestPoint); 164 | } 165 | } 166 | } 167 | } 168 | return nearestPoint; 169 | } 170 | 171 | // a nearest neighbor in the set to point p; null if the set is empty 172 | public Point2D nearest(Point2D p) { 173 | return nearestNeigh(root, board, p, null); 174 | } 175 | 176 | // unit testing of the methods (optional) 177 | public static void main(String[] args) { 178 | } 179 | 180 | } -------------------------------------------------------------------------------- /Assignment5/KdTreeVisualizer.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac KdTreeVisualizer.java 3 | * Execution: java KdTreeVisualizer 4 | * Dependencies: StdDraw.java Point2D.java 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 | public class KdTreeVisualizer { 12 | 13 | public static void main(String[] args) { 14 | StdDraw.show(0); 15 | KdTree kdtree = new KdTree(); 16 | while (true) { 17 | if (StdDraw.mousePressed()) { 18 | double x = StdDraw.mouseX(); 19 | double y = StdDraw.mouseY(); 20 | System.out.printf("%8.6f %8.6f\n", x, y); 21 | Point2D p = new Point2D(x, y); 22 | kdtree.insert(p); 23 | StdDraw.clear(); 24 | kdtree.draw(); 25 | } 26 | StdDraw.show(50); 27 | } 28 | 29 | } 30 | } -------------------------------------------------------------------------------- /Assignment5/NearestNeighborVisualizer.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac NearestNeighborVisualizer.java 3 | * Execution: java NearestNeighborVisualizer input.txt 4 | * Dependencies: PointSET.java KdTree.java Point2D.java In.java StdDraw.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 | public class NearestNeighborVisualizer { 15 | 16 | public static void main(String[] args) { 17 | String filename = args[0]; 18 | In in = new In(filename); 19 | 20 | StdDraw.show(0); 21 | 22 | // initialize the two data structures with point from standard input 23 | PointSET brute = new PointSET(); 24 | KdTree kdtree = new KdTree(); 25 | while (!in.isEmpty()) { 26 | double x = in.readDouble(); 27 | double y = in.readDouble(); 28 | Point2D p = new Point2D(x, y); 29 | kdtree.insert(p); 30 | brute.insert(p); 31 | } 32 | 33 | while (true) { 34 | 35 | // the location (x, y) of the mouse 36 | double x = StdDraw.mouseX(); 37 | double y = StdDraw.mouseY(); 38 | Point2D query = new Point2D(x, y); 39 | 40 | // draw all of the points 41 | StdDraw.clear(); 42 | StdDraw.setPenColor(StdDraw.BLACK); 43 | StdDraw.setPenRadius(.01); 44 | brute.draw(); 45 | 46 | // draw in red the nearest neighbor (using brute-force algorithm) 47 | StdDraw.setPenRadius(.03); 48 | StdDraw.setPenColor(StdDraw.RED); 49 | brute.nearest(query).draw(); 50 | StdDraw.setPenRadius(.02); 51 | 52 | // draw in blue the nearest neighbor (using kd-tree algorithm) 53 | StdDraw.setPenColor(StdDraw.BLUE); 54 | kdtree.nearest(query).draw(); 55 | StdDraw.show(0); 56 | StdDraw.show(40); 57 | } 58 | } 59 | } -------------------------------------------------------------------------------- /Assignment5/PointSET.java: -------------------------------------------------------------------------------- 1 | import java.util.TreeSet; 2 | 3 | public class PointSET { 4 | private TreeSet set; 5 | 6 | // construct an empty set of points 7 | public PointSET() { 8 | set = new TreeSet(); 9 | } 10 | 11 | // is the set empty? 12 | public boolean isEmpty() { 13 | return set.isEmpty(); 14 | } 15 | 16 | // number of points in the set 17 | public int size() { 18 | return set.size(); 19 | } 20 | 21 | // add the point to the set (if it is not already in the set) 22 | public void insert(Point2D p) { 23 | set.add(p); 24 | } 25 | 26 | // does the set contain point p? 27 | public boolean contains(Point2D p) { 28 | return set.contains(p); 29 | } 30 | 31 | // draw all points to standard draw 32 | public void draw() { 33 | for (Point2D p:set) p.draw(); 34 | } 35 | 36 | // all points that are inside the rectangle 37 | public Iterable range(RectHV rect) { 38 | Stack points = new Stack(); 39 | for (Point2D p:set) { 40 | if (rect.contains(p)) points.push(p); 41 | } 42 | return points; 43 | } 44 | 45 | // a nearest neighbor in the set to point p; null if the set is empty 46 | public Point2D nearest(Point2D p) { 47 | if (set.isEmpty()) return null; 48 | Point2D pp = set.first(); 49 | double minDistance = p.distanceSquaredTo(pp); 50 | for (Point2D point:set) { 51 | if (p.distanceSquaredTo(point) <= minDistance) { 52 | pp = point; 53 | minDistance = p.distanceSquaredTo(point); 54 | } 55 | } 56 | return pp; 57 | } 58 | 59 | // unit testing of the methods (optional) 60 | public static void main(String[] args) { 61 | } 62 | 63 | } -------------------------------------------------------------------------------- /Assignment5/RangeSearchVisualizer.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac RangeSearchVisualizer.java 3 | * Execution: java RangeSearchVisualizer input.txt 4 | * Dependencies: PointSET.java KdTree.java Point2D.java RectHV.java 5 | * StdDraw.java In.java 6 | * 7 | * Read points from a file (specified as a command-line arugment) and 8 | * draw to standard draw. Also draw all of the points in the rectangle 9 | * the user selects by dragging the mouse. 10 | * 11 | * The range search results using the brute-force algorithm are drawn 12 | * in red; the results using the kd-tree algorithms are drawn in blue. 13 | * 14 | *************************************************************************/ 15 | 16 | public class RangeSearchVisualizer { 17 | 18 | public static void main(String[] args) { 19 | 20 | String filename = args[0]; 21 | In in = new In(filename); 22 | 23 | 24 | StdDraw.show(0); 25 | 26 | // initialize the data structures with N points 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 | double x0 = 0.0, y0 = 0.0; // initial endpoint of rectangle 38 | double x1 = 0.0, y1 = 0.0; // current location of mouse 39 | boolean isDragging = false; // is the user dragging a rectangle 40 | 41 | // draw the points 42 | StdDraw.clear(); 43 | StdDraw.setPenColor(StdDraw.BLACK); 44 | StdDraw.setPenRadius(.01); 45 | brute.draw(); 46 | 47 | while (true) { 48 | StdDraw.show(40); 49 | 50 | // user starts to drag a rectangle 51 | if (StdDraw.mousePressed() && !isDragging) { 52 | x0 = StdDraw.mouseX(); 53 | y0 = StdDraw.mouseY(); 54 | isDragging = true; 55 | continue; 56 | } 57 | 58 | // user is dragging a rectangle 59 | else if (StdDraw.mousePressed() && isDragging) { 60 | x1 = StdDraw.mouseX(); 61 | y1 = StdDraw.mouseY(); 62 | continue; 63 | } 64 | 65 | // mouse no longer pressed 66 | else if (!StdDraw.mousePressed() && isDragging) { 67 | isDragging = false; 68 | } 69 | 70 | 71 | RectHV rect = new RectHV(Math.min(x0, x1), Math.min(y0, y1), 72 | Math.max(x0, x1), Math.max(y0, y1)); 73 | // draw the points 74 | StdDraw.clear(); 75 | StdDraw.setPenColor(StdDraw.BLACK); 76 | StdDraw.setPenRadius(.01); 77 | brute.draw(); 78 | 79 | // draw the rectangle 80 | StdDraw.setPenColor(StdDraw.BLACK); 81 | StdDraw.setPenRadius(); 82 | rect.draw(); 83 | 84 | // draw the range search results for brute-force data structure in red 85 | StdDraw.setPenRadius(.03); 86 | StdDraw.setPenColor(StdDraw.RED); 87 | for (Point2D p : brute.range(rect)) 88 | p.draw(); 89 | 90 | // draw the range search results for kd-tree in blue 91 | StdDraw.setPenRadius(.02); 92 | StdDraw.setPenColor(StdDraw.BLUE); 93 | for (Point2D p : kdtree.range(rect)) 94 | p.draw(); 95 | 96 | StdDraw.show(40); 97 | } 98 | } 99 | } -------------------------------------------------------------------------------- /Assignment5/RectHV.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac RectHV.java 3 | * Execution: java RectHV 4 | * Dependencies: Point2D.java 5 | * 6 | * Implementation of 2D axis-aligned rectangle. 7 | * 8 | *************************************************************************/ 9 | 10 | public class RectHV { 11 | private final double xmin, ymin; // minimum x- and y-coordinates 12 | private final double xmax, ymax; // maximum x- and y-coordinates 13 | 14 | // construct the axis-aligned rectangle [xmin, xmax] x [ymin, ymax] 15 | public RectHV(double xmin, double ymin, double xmax, double ymax) { 16 | if (xmax < xmin || ymax < ymin) { 17 | throw new IllegalArgumentException("Invalid rectangle"); 18 | } 19 | this.xmin = xmin; 20 | this.ymin = ymin; 21 | this.xmax = xmax; 22 | this.ymax = ymax; 23 | } 24 | 25 | // accessor methods for 4 coordinates 26 | public double xmin() { return xmin; } 27 | public double ymin() { return ymin; } 28 | public double xmax() { return xmax; } 29 | public double ymax() { return ymax; } 30 | 31 | // width and height of rectangle 32 | public double width() { return xmax - xmin; } 33 | public double height() { return ymax - ymin; } 34 | 35 | // does this axis-aligned rectangle intersect that one? 36 | public boolean intersects(RectHV that) { 37 | return this.xmax >= that.xmin && this.ymax >= that.ymin 38 | && that.xmax >= this.xmin && that.ymax >= this.ymin; 39 | } 40 | 41 | // draw this axis-aligned rectangle 42 | public void draw() { 43 | StdDraw.line(xmin, ymin, xmax, ymin); 44 | StdDraw.line(xmax, ymin, xmax, ymax); 45 | StdDraw.line(xmax, ymax, xmin, ymax); 46 | StdDraw.line(xmin, ymax, xmin, ymin); 47 | } 48 | 49 | // distance from p to closest point on this axis-aligned rectangle 50 | public double distanceTo(Point2D p) { 51 | return Math.sqrt(this.distanceSquaredTo(p)); 52 | } 53 | 54 | // distance squared from p to closest point on this axis-aligned rectangle 55 | public double distanceSquaredTo(Point2D p) { 56 | double dx = 0.0, dy = 0.0; 57 | if (p.x() < xmin) dx = p.x() - xmin; 58 | else if (p.x() > xmax) dx = p.x() - xmax; 59 | if (p.y() < ymin) dy = p.y() - ymin; 60 | else if (p.y() > ymax) dy = p.y() - ymax; 61 | return dx*dx + dy*dy; 62 | } 63 | 64 | // does this axis-aligned rectangle contain p? 65 | public boolean contains(Point2D p) { 66 | return (p.x() >= xmin) && (p.x() <= xmax) 67 | && (p.y() >= ymin) && (p.y() <= ymax); 68 | } 69 | 70 | // are the two axis-aligned rectangles equal? 71 | public boolean equals(Object y) { 72 | if (y == this) return true; 73 | if (y == null) return false; 74 | if (y.getClass() != this.getClass()) return false; 75 | RectHV that = (RectHV) y; 76 | if (this.xmin != that.xmin) return false; 77 | if (this.ymin != that.ymin) return false; 78 | if (this.xmax != that.xmax) return false; 79 | if (this.ymax != that.ymax) return false; 80 | return true; 81 | } 82 | 83 | // return a string representation of this axis-aligned rectangle 84 | public String toString() { 85 | return "[" + xmin + ", " + xmax + "] x [" + ymin + ", " + ymax + "]"; 86 | } 87 | 88 | } -------------------------------------------------------------------------------- /Assignment5/input100K.txt: -------------------------------------------------------------------------------- 1 | 0.158530 0.486901 2 | 0.792202 0.762825 3 | 0.738013 0.827616 4 | 0.615232 0.064454 5 | 0.107092 0.863317 6 | 0.395908 0.043916 7 | 0.848473 0.112317 8 | 0.095420 0.786050 9 | 0.684045 0.631946 10 | 0.771410 0.386939 11 | 0.997176 0.122313 12 | 0.758012 0.929986 13 | 0.762533 0.084336 14 | 0.533326 0.509709 15 | 0.636874 0.972299 16 | 0.950162 0.341602 17 | 0.441805 0.922723 18 | 0.374015 0.653670 19 | 0.778271 0.564235 20 | 0.671664 0.493681 21 | 0.052601 0.617204 22 | 0.924451 0.805943 23 | 0.765215 0.477260 24 | 0.202208 0.132361 25 | 0.515627 0.743434 26 | 0.726965 0.074768 27 | 0.811187 0.699469 28 | 0.279975 0.219012 29 | 0.432028 0.086015 30 | 0.761284 0.565975 31 | 0.800981 0.111699 32 | 0.397958 0.640721 33 | 0.534756 0.542728 34 | 0.215252 0.358151 35 | 0.111487 0.883491 36 | 0.034437 0.412054 37 | 0.379750 0.114754 -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | The codes are solutions for the following assignments: 3 | 4 | - Programming Assignment 1: Percolation 5 | 6 | - Programming Assignment 2: Randomized Queues and Deques 7 | 8 | - Programming Assignment 3: Collinear Points 9 | 10 | - Programming Assignment 4: 8 Puzzle 11 | 12 | - Programming Assignment 5: Kd-Trees --------------------------------------------------------------------------------