├── Assignment-1 ├── Percolation.java └── PercolationStats.java ├── Assignment-2 ├── Deque.java ├── Permutation.java └── RandomizedQueue.java ├── Assignment-3 ├── BruteCollinearPoints.java ├── FastCollinearPoints.java ├── LineSegment.java └── Point.java ├── Assignment-4 ├── Board.java ├── PuzzleChecker.java └── Solver.java ├── Assignment-5 ├── KdTree.java ├── KdTreeVisualizer.java ├── NearestNeighborVisualizer.java ├── PointSET.java └── RangeSearchVisualizer.java ├── LICENSE ├── Lecture Slides ├── 13StacksAndQueues.pdf ├── 14AnalysisOfAlgorithms.pdf ├── 15UnionFind.pdf ├── 21ElementarySorts.pdf ├── 22Mergesort.pdf ├── 23Quicksort.pdf ├── 24PriorityQueues.pdf ├── 31ElementarySymbolTables.pdf ├── 32BinarySearchTrees.pdf ├── 33BalancedSearchTrees.pdf ├── 34HashTables.pdf ├── 35SearchingApplications.pdf └── 99GeometricSearch.pdf ├── README.md ├── Week2 ├── DutchNationalFlag.java ├── Insertion.java ├── Intersection.java ├── KnuthShuffle.java ├── Selection.java └── Shell.java ├── Week3 ├── CountingInversions.java ├── MergeSmall.java └── MergeSort1.java └── Week4 └── MinPQ.java /Assignment-1/Percolation.java: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************* 2 | * Author : Deepak Kumar Sood 3 | * Date : 30-Dec-2017 4 | * Last updated : 30-Dec-2017 5 | * 6 | * Compilation : use DrJava 7 | * Execution : java-algs4 PercolationStats 200 100 8 | * 9 | * Purpose of the program : A program to estimate the value of the percolation threshold via Monte Carlo simulation. 10 | * Assingment link : http://coursera.cs.princeton.edu/algs4/assignments/percolation.html 11 | * Score : 100/100 12 | **********************************************************************************************************************/ 13 | 14 | import edu.princeton.cs.algs4.WeightedQuickUnionUF; 15 | 16 | public class Percolation { 17 | 18 | // size of the grid 19 | private final int n; 20 | 21 | // Weighted Quick Union Find implementation 22 | private final WeightedQuickUnionUF uf; 23 | private final WeightedQuickUnionUF uf2; 24 | 25 | // array to store the grid in one dimension DS 26 | private boolean[] arr; 27 | 28 | // counter for number of open sites in the grid 29 | private int numOfOpenSites; 30 | 31 | /** 32 | * create n-by-n grid, with all sites blocked 33 | * Default Constructor for setting up the union find 34 | */ 35 | public Percolation(int n) { 36 | if (n <= 0) { 37 | throw new IllegalArgumentException(); 38 | } 39 | 40 | this.n = n; 41 | numOfOpenSites = 0; 42 | arr = new boolean[n*n + 2]; 43 | uf = new WeightedQuickUnionUF(n*n + 2); 44 | uf2 = new WeightedQuickUnionUF(n*n + 1); 45 | } 46 | 47 | private boolean isSiteInvalid(int row, int col) { 48 | return row < 1 || col < 1 || row > this.n || col > this.n; 49 | } 50 | 51 | private int getArrIndex(int row, int col) { 52 | return (row-1)*this.n + col; 53 | } 54 | 55 | // open site (row, col) if it is not open already 56 | public void open(int row, int col) { 57 | if (isSiteInvalid(row, col)) { 58 | throw new IllegalArgumentException(); 59 | } 60 | 61 | int index = getArrIndex(row, col); 62 | if (!isOpen(row, col)) { 63 | numOfOpenSites++; 64 | this.arr[index] = true; 65 | 66 | if (row == 1) { 67 | uf.union(index, 0); 68 | uf2.union(index, 0); 69 | } 70 | 71 | if (row == this.n) 72 | uf.union(index, this.n * this.n + 1); 73 | 74 | // top site 75 | if (row > 1 && isOpen(row-1, col)) { 76 | uf.union(index, getArrIndex(row-1, col)); 77 | uf2.union(index, getArrIndex(row-1, col)); 78 | } 79 | 80 | // bottom site 81 | if (row < n && isOpen(row+1, col)) { 82 | uf.union(index, getArrIndex(row+1, col)); 83 | uf2.union(index, getArrIndex(row+1, col)); 84 | } 85 | 86 | // left site 87 | if (col > 1 && isOpen(row, col-1)) { 88 | uf.union(index, getArrIndex(row, col-1)); 89 | uf2.union(index, getArrIndex(row, col-1)); 90 | } 91 | 92 | // right site 93 | if (col < n && isOpen(row, col+1)) { 94 | uf.union(index, getArrIndex(row, col+1)); 95 | uf2.union(index, getArrIndex(row, col+1)); 96 | } 97 | } 98 | } 99 | 100 | // is site (row, col) open? 101 | public boolean isOpen(int row, int col) { 102 | if (isSiteInvalid(row, col)) { 103 | throw new IllegalArgumentException(); 104 | } 105 | return this.arr[getArrIndex(row, col)]; 106 | } 107 | 108 | // is site (row, col) full 109 | public boolean isFull(int row, int col) { 110 | if (isSiteInvalid(row, col)) { 111 | throw new IllegalArgumentException(); 112 | } 113 | 114 | int index = getArrIndex(row, col); 115 | 116 | return uf2.connected(0, index); 117 | } 118 | 119 | // number of open sites 120 | public int numberOfOpenSites() { 121 | return numOfOpenSites; 122 | } 123 | 124 | // does the system percolate 125 | public boolean percolates() { 126 | return uf.connected(0, n*n + 1); 127 | } 128 | } -------------------------------------------------------------------------------- /Assignment-1/PercolationStats.java: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************* 2 | * Author : Deepak Kumar Sood 3 | * Date : 30-Dec-2017 4 | * Last updated : 30-Dec-2017 5 | * 6 | * Compilation : use DrJava 7 | * Execution : java-algs4 PercolationStats 200 100 8 | * 9 | * Purpose of the program : A program to estimate the value of the percolation threshold via Monte Carlo simulation. 10 | * Assingment link : http://coursera.cs.princeton.edu/algs4/assignments/percolation.html 11 | * Score : 100/100 12 | **********************************************************************************************************************/ 13 | 14 | import edu.princeton.cs.algs4.StdRandom; 15 | import edu.princeton.cs.algs4.StdStats; 16 | 17 | public class PercolationStats { 18 | 19 | private static final double CONFIDENCE_95 = 1.96; 20 | 21 | private double meanVal = -1; 22 | private double stddevVal = -1; 23 | 24 | private final double[] results; 25 | 26 | // perform trials independent experiments on an n-by-n grid 27 | public PercolationStats(int n, int trials) { 28 | if (n <= 0 || trials <= 0) { 29 | throw new IllegalArgumentException(); 30 | } 31 | results = new double[trials]; 32 | for (int i = 0; i < trials; i++) { 33 | 34 | Percolation percolation = new Percolation(n); 35 | while (!percolation.percolates()) { 36 | int row = StdRandom.uniform(n) + 1; 37 | int col = StdRandom.uniform(n) + 1; 38 | if (!percolation.isOpen(row, col)) { 39 | percolation.open(row, col); 40 | } 41 | } 42 | 43 | results[i] = (double) percolation.numberOfOpenSites() / (n*n); 44 | } 45 | } 46 | 47 | // sample mean of percolation threshold 48 | public double mean() { 49 | if (meanVal == -1) 50 | this.meanVal = StdStats.mean(results); 51 | return meanVal; 52 | } 53 | 54 | // sample standard deviation of percolation threshold 55 | public double stddev() { 56 | if (stddevVal == -1) 57 | this.stddevVal = StdStats.stddev(results); 58 | return stddevVal; 59 | } 60 | 61 | // low endpoint of 95% confidence interval 62 | public double confidenceLo() { 63 | if (meanVal == -1) 64 | mean(); 65 | if (stddevVal == -1) 66 | stddev(); 67 | return meanVal - (CONFIDENCE_95 * stddevVal / Math.sqrt(results.length)); 68 | } 69 | 70 | // high endpoint of 95% confidence interval 71 | public double confidenceHi() { 72 | if (meanVal == -1) 73 | mean(); 74 | if (stddevVal == -1) 75 | stddev(); 76 | return meanVal + (CONFIDENCE_95 * stddevVal / Math.sqrt(results.length)); 77 | } 78 | 79 | // test client 80 | public static void main(String[] args) { 81 | int n = Integer.parseInt(args[0]); 82 | int trials = Integer.parseInt(args[1]); 83 | 84 | PercolationStats percolationStats = new PercolationStats(n, trials); 85 | System.out.println("mean = " + percolationStats.mean()); 86 | System.out.println("stddev = " + percolationStats.stddev()); 87 | System.out.println("95% confidence interval = [" + percolationStats.confidenceLo() + ", " + percolationStats.confidenceHi() + "]"); 88 | } 89 | } -------------------------------------------------------------------------------- /Assignment-2/Deque.java: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************* 2 | * Author : Deepak Kumar Sood 3 | * Date : 7-Jan-2017 4 | * Last updated : 7-Jan-2017 5 | * 6 | * Compilation : use DrJava 7 | * Execution : java-algs4 Dequeue 8 | * 9 | * Purpose of the program : A generic Double Ended Queue with Iterator 10 | * Assingment link : http://coursera.cs.princeton.edu/algs4/assignments/queues.html 11 | * Score : 100/100 12 | **********************************************************************************************************************/ 13 | 14 | import java.util.NoSuchElementException; 15 | import java.util.Iterator; 16 | 17 | public class Deque implements Iterable { 18 | 19 | private int first, last, n; 20 | private Item[] dq; 21 | 22 | /** 23 | * construct an empty deque 24 | */ 25 | public Deque() { 26 | first = 0; 27 | last = 0; 28 | n = 0; 29 | dq = (Item[]) new Object[2]; 30 | } 31 | 32 | /** 33 | * is the deque empty? 34 | */ 35 | public boolean isEmpty() { 36 | return n == 0; 37 | } 38 | 39 | /** 40 | * return the number of items on the deque 41 | */ 42 | public int size() { 43 | return n; 44 | } 45 | 46 | /** 47 | * add the item to the front 48 | */ 49 | public void addFirst(Item item) { 50 | if (item == null) throw new IllegalArgumentException(); 51 | 52 | if (n == dq.length) resize(dq.length*2); 53 | 54 | if (first == last && dq[first] == null) { 55 | dq[first] = item; 56 | } else if (first == 0) { 57 | first = dq.length-1; 58 | dq[first] = item; 59 | } else { 60 | first--; 61 | dq[first] = item; 62 | } 63 | n++; 64 | } 65 | 66 | /** 67 | * add the item to the end 68 | */ 69 | public void addLast(Item item) { 70 | if (item == null) throw new IllegalArgumentException(); 71 | 72 | if (n == dq.length) resize(dq.length*2); 73 | 74 | if (first == last && dq[last] == null) { 75 | dq[last] = item; 76 | } else if (last == dq.length-1) { 77 | last = 0; 78 | dq[last] = item; 79 | } else { 80 | last++; 81 | dq[last] = item; 82 | } 83 | n++; 84 | } 85 | 86 | private void resize(int capacity) { 87 | Item[] temp = (Item[]) new Object[capacity]; 88 | for (int i = 0; i < n; i++) { 89 | temp[i] = dq[(first + i) % dq.length]; 90 | } 91 | dq = temp; 92 | first = 0; 93 | last = n-1; 94 | } 95 | 96 | /** 97 | * remove and return the item from the front 98 | */ 99 | public Item removeFirst() { 100 | if (!isEmpty()) { 101 | Item item = dq[first]; 102 | dq[first] = null; 103 | 104 | if(first == dq.length-1) { 105 | first = 0; 106 | } else { 107 | first++; 108 | } 109 | 110 | n--; 111 | 112 | if (n > 0 && n == dq.length/4) resize(dq.length/2); 113 | 114 | return item; 115 | } else { 116 | throw new NoSuchElementException(); 117 | } 118 | } 119 | 120 | /** 121 | * remove and return the item from the end 122 | */ 123 | public Item removeLast() { 124 | if (!isEmpty()) { 125 | Item item = dq[last]; 126 | dq[last] = null; 127 | if (last == 0 && n > 1) { 128 | last = dq.length - 1; 129 | } else if (last != 0 && n != 1) { 130 | last--; 131 | } 132 | 133 | n--; 134 | 135 | if (n > 0 && n == dq.length/4) resize(dq.length/2); 136 | 137 | return item; 138 | } else { 139 | throw new NoSuchElementException(); 140 | } 141 | } 142 | 143 | /** 144 | * return an iterator over items in order from front to end 145 | */ 146 | public Iterator iterator() { 147 | return new ArrayIterator(); 148 | } 149 | 150 | private class ArrayIterator implements Iterator { 151 | private int i = 0; 152 | public boolean hasNext() { 153 | return i < n; 154 | } 155 | 156 | public void remove() { 157 | throw new UnsupportedOperationException(); 158 | } 159 | 160 | public Item next() { 161 | if (!hasNext()) { 162 | throw new NoSuchElementException(); 163 | } 164 | Item item = dq[(i + first) % dq.length]; 165 | i++; 166 | return item; 167 | } 168 | } 169 | } -------------------------------------------------------------------------------- /Assignment-2/Permutation.java: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************* 2 | * Author : Deepak Kumar Sood 3 | * Date : 7-Jan-2017 4 | * Last updated : 7-Jan-2017 5 | * 6 | * Compilation : use DrJava 7 | * Execution : java-algs4 Permutation 3 < distinct.txt 8 | * 9 | * Purpose of the program : Client program for using RandomizedQueue 10 | * Assingment link : http://coursera.cs.princeton.edu/algs4/assignments/queues.html 11 | * Score : 100/100 12 | **********************************************************************************************************************/ 13 | 14 | import edu.princeton.cs.algs4.StdIn; 15 | 16 | public class Permutation { 17 | public static void main(String[] args) { 18 | 19 | int k = Integer.parseInt(args[0]); 20 | 21 | RandomizedQueue queue = new RandomizedQueue(); 22 | 23 | while (!StdIn.isEmpty()) { 24 | queue.enqueue(StdIn.readString()); 25 | } 26 | 27 | for (int i = 0; i < k; i++) { 28 | System.out.println(queue.dequeue()); 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /Assignment-2/RandomizedQueue.java: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************* 2 | * Author : Deepak Kumar Sood 3 | * Date : 7-Jan-2017 4 | * Last updated : 7-Jan-2017 5 | * 6 | * Compilation : use DrJava 7 | * Execution : java-algs4 RandomizedQueue 8 | * 9 | * Purpose of the program : A generic Randomized Queue with Iterator 10 | * Assingment link : http://coursera.cs.princeton.edu/algs4/assignments/queues.html 11 | * Score : 100/100 12 | **********************************************************************************************************************/ 13 | 14 | import java.util.NoSuchElementException; 15 | import java.util.Iterator; 16 | import edu.princeton.cs.algs4.StdRandom; 17 | 18 | public class RandomizedQueue implements Iterable { 19 | 20 | private int n; 21 | private Item[] q; 22 | 23 | /** 24 | * construct an empty randomized queue 25 | */ 26 | public RandomizedQueue() { 27 | n = 0; 28 | q = (Item[]) new Object[2]; 29 | } 30 | 31 | /** 32 | * is the randomized queue empty? 33 | */ 34 | public boolean isEmpty() { 35 | return n == 0; 36 | } 37 | 38 | /** 39 | * return the number of items on the randomized queue 40 | */ 41 | public int size() { 42 | return n; 43 | } 44 | 45 | /** 46 | * add the item 47 | */ 48 | public void enqueue(Item item) { 49 | if (item == null) { throw new IllegalArgumentException(); } 50 | if (n == q.length) resize(q.length*2); 51 | 52 | q[n++] = item; 53 | } 54 | 55 | private void resize(int capacity) { 56 | Item[] temp = (Item[]) new Object[capacity]; 57 | for (int i = 0; i < n; i++) { 58 | temp[i] = q[i]; 59 | } 60 | q = temp; 61 | } 62 | 63 | /** 64 | * remove and return a random item 65 | */ 66 | public Item dequeue() { 67 | if (isEmpty()) { throw new NoSuchElementException(); } 68 | int index = StdRandom.uniform(n); 69 | Item item = q[index]; 70 | q[index] = q[--n]; 71 | q[n] = null; 72 | 73 | if (n > 0 && n == q.length/4) resize(q.length / 2); 74 | 75 | return item; 76 | } 77 | 78 | /** 79 | * return a random item (but do not remove it) 80 | */ 81 | public Item sample() { 82 | if (isEmpty()) { throw new NoSuchElementException(); } 83 | 84 | return q[StdRandom.uniform(n)]; 85 | } 86 | 87 | /** 88 | * return an independent iterator over items in random order 89 | */ 90 | public Iterator iterator() { 91 | return new ArrayIterator(); 92 | } 93 | 94 | private class ArrayIterator implements Iterator { 95 | private int current; 96 | private int[] random; 97 | 98 | public ArrayIterator() { 99 | this.random = new int[n]; 100 | for (int i = 0; i < n; i++) { 101 | random[i] = i; 102 | } 103 | StdRandom.shuffle(random); 104 | current = 0; 105 | } 106 | 107 | public boolean hasNext() { return current != random.length; } 108 | public void remove() { throw new UnsupportedOperationException(); } 109 | public Item next() { 110 | if (!hasNext()) throw new NoSuchElementException(); 111 | return q[random[current++]]; 112 | } 113 | } 114 | } -------------------------------------------------------------------------------- /Assignment-3/BruteCollinearPoints.java: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************* 2 | * Author : Deepak Kumar Sood 3 | * Date : 14-Jan-2017 4 | * Last updated : 14-Jan-2017 5 | * 6 | * Compilation : javac-algs4 Point.java 7 | * Execution : java-algs4 Point 8 | * 9 | * Purpose of the program : To calculate collinear points using brute force. 10 | * Assingment link : http://coursera.cs.princeton.edu/algs4/assignments/collinear.html 11 | * Score : 100/100 12 | **********************************************************************************************************************/ 13 | import java.util.ArrayList; 14 | import java.util.Arrays; 15 | 16 | import edu.princeton.cs.algs4.In; 17 | import edu.princeton.cs.algs4.StdOut; 18 | import edu.princeton.cs.algs4.StdDraw; 19 | 20 | public class BruteCollinearPoints { 21 | 22 | private final ArrayList segments; 23 | 24 | /** 25 | * Finds all line segments containing 4 points 26 | */ 27 | public BruteCollinearPoints(Point[] points) { 28 | if (points == null) 29 | throw new IllegalArgumentException("Points cannot be null"); 30 | 31 | checkNullEntries(points); 32 | 33 | checkDuplicateEntries(points); 34 | 35 | Point[] pointCopy = points.clone(); 36 | Arrays.sort(pointCopy); 37 | 38 | segments = new ArrayList(); 39 | 40 | for (int p = 0; p < pointCopy.length - 3; p++) { 41 | for (int q = p + 1; q < pointCopy.length - 2; q++) { 42 | for (int r = q + 1; r < pointCopy.length - 1; r++) { 43 | for (int s = r + 1; s < pointCopy.length; s++) { 44 | if (pointCopy[p].slopeTo(pointCopy[q]) == pointCopy[p].slopeTo(pointCopy[r]) && 45 | pointCopy[p].slopeTo(pointCopy[q]) == pointCopy[p].slopeTo(pointCopy[s])) { 46 | segments.add(new LineSegment(pointCopy[p], pointCopy[s])); 47 | } 48 | } 49 | } 50 | } 51 | } 52 | } 53 | 54 | private void checkNullEntries(Point[] points) { 55 | for (int i = 0; i < points.length; i++) { 56 | if (points[i] == null) { 57 | throw new IllegalArgumentException("Null entries in array"); 58 | } 59 | } 60 | } 61 | 62 | private void checkDuplicateEntries(Point[] points) { 63 | for (int i = 0; i < points.length - 1; i++) { 64 | for (int j = i+1; j < points.length; j++) { 65 | if (points[i].compareTo(points[j]) == 0) { 66 | throw new IllegalArgumentException("Duplicate points in array"); 67 | } 68 | } 69 | } 70 | } 71 | 72 | /** 73 | * The number of line segments 74 | */ 75 | public int numberOfSegments() { 76 | return segments.size(); 77 | } 78 | 79 | /** 80 | * The line segments 81 | */ 82 | public LineSegment[] segments() { 83 | return segments.toArray(new LineSegment[segments.size()]); 84 | } 85 | 86 | public static void main(String[] args) { 87 | 88 | // read the n points from a file 89 | In in = new In(args[0]); 90 | int n = in.readInt(); 91 | Point[] points = new Point[n]; 92 | for (int i = 0; i < n; i++) { 93 | int x = in.readInt(); 94 | int y = in.readInt(); 95 | points[i] = new Point(x, y); 96 | } 97 | 98 | // draw the points 99 | StdDraw.enableDoubleBuffering(); 100 | StdDraw.setXscale(0, 32768); 101 | StdDraw.setYscale(0, 32768); 102 | for (Point p : points) { 103 | p.draw(); 104 | } 105 | StdDraw.show(); 106 | 107 | // print and draw the line segments 108 | BruteCollinearPoints collinear = new BruteCollinearPoints(points); 109 | for (LineSegment segment : collinear.segments()) { 110 | StdOut.println(segment); 111 | segment.draw(); 112 | } 113 | StdDraw.show(); 114 | } 115 | } -------------------------------------------------------------------------------- /Assignment-3/FastCollinearPoints.java: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************* 2 | * Author : Deepak Kumar Sood 3 | * Date : 14-Jan-2017 4 | * Last updated : 14-Jan-2017 5 | * 6 | * Compilation : javac-algs4 FastCollinearPoints.java 7 | * Execution : java-algs4 FastCollinearPoints 8 | * 9 | * Purpose of the program : To calculate collinear points using a fast algorithm 10 | * Assingment link : http://coursera.cs.princeton.edu/algs4/assignments/collinear.html 11 | * Score : 100/100 12 | **********************************************************************************************************************/ 13 | import java.util.ArrayList; 14 | import java.util.Arrays; 15 | 16 | import edu.princeton.cs.algs4.In; 17 | import edu.princeton.cs.algs4.StdOut; 18 | import edu.princeton.cs.algs4.StdDraw; 19 | 20 | public class FastCollinearPoints { 21 | 22 | private final ArrayList segments = new ArrayList<>(); 23 | 24 | // finds all line segments containing 4 or more points 25 | public FastCollinearPoints(Point[] points) { 26 | if (points == null) 27 | throw new IllegalArgumentException(); 28 | 29 | checkNullEntries(points); 30 | 31 | checkDuplicateEntries(points); 32 | 33 | Point[] pointCopy = points.clone(); 34 | Arrays.sort(pointCopy); 35 | 36 | for (int i = 0; i < pointCopy.length - 3; i++) { 37 | Arrays.sort(pointCopy); 38 | 39 | // Sort the points according to the slopes they makes with p. 40 | // Check if any 3 (or more) adjacent points in the sorted order 41 | // have equal slopes with respect to p. If so, these points, 42 | // together with p, are collinear. 43 | 44 | Arrays.sort(pointCopy, pointCopy[i].slopeOrder()); 45 | 46 | for (int p = 0, first = 1, last = 2; last < pointCopy.length; last++) { 47 | // find last collinear to p point 48 | while (last < pointCopy.length 49 | && Double.compare(pointCopy[p].slopeTo(pointCopy[first]), pointCopy[p].slopeTo(pointCopy[last])) == 0) { 50 | last++; 51 | } 52 | // if found at least 3 elements, make segment if it's unique 53 | if (last - first >= 3 && pointCopy[p].compareTo(pointCopy[first]) < 0) { 54 | segments.add(new LineSegment(pointCopy[p], pointCopy[last - 1])); 55 | } 56 | // Try to find next 57 | first = last; 58 | } 59 | } 60 | } 61 | 62 | private void checkNullEntries(Point[] points) { 63 | for (int i = 0; i < points.length; i++) { 64 | if (points[i] == null) { 65 | throw new IllegalArgumentException("Null entries in array"); 66 | } 67 | } 68 | } 69 | 70 | private void checkDuplicateEntries(Point[] points) { 71 | for (int i = 0; i < points.length - 1; i++) { 72 | for (int j = i+1; j < points.length; j++) { 73 | if (points[i].compareTo(points[j]) == 0) { 74 | throw new IllegalArgumentException("Duplicate points in array"); 75 | } 76 | } 77 | } 78 | } 79 | 80 | // the number of line segments 81 | public int numberOfSegments() { 82 | return segments.size(); 83 | } 84 | 85 | // the line segments 86 | public LineSegment[] segments() { 87 | return segments.toArray(new LineSegment[segments.size()]); 88 | } 89 | 90 | public static void main(String[] args) { 91 | // read the n points from a file 92 | In in = new In(args[0]); 93 | int n = in.readInt(); 94 | Point[] points = new Point[n]; 95 | for (int i = 0; i < n; i++) { 96 | int x = in.readInt(); 97 | int y = in.readInt(); 98 | points[i] = new Point(x, y); 99 | } 100 | 101 | // draw the points 102 | StdDraw.enableDoubleBuffering(); 103 | StdDraw.setXscale(0, 32768); 104 | StdDraw.setYscale(0, 32768); 105 | for (Point p : points) { 106 | p.draw(); 107 | } 108 | StdDraw.show(); 109 | 110 | // print and draw the line segments 111 | FastCollinearPoints collinear = new FastCollinearPoints(points); 112 | for (LineSegment segment : collinear.segments()) { 113 | StdOut.println(segment); 114 | segment.draw(); 115 | } 116 | StdDraw.show(); 117 | } 118 | } -------------------------------------------------------------------------------- /Assignment-3/LineSegment.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac LineSegment.java 3 | * Execution: none 4 | * Dependencies: Point.java 5 | * 6 | * An immutable data type for Line segments in the plane. 7 | * For use on Coursera, Algorithms Part I programming assignment. 8 | * 9 | * DO NOT MODIFY THIS CODE. 10 | * 11 | *************************************************************************/ 12 | 13 | public class LineSegment { 14 | private final Point p; // one endpoint of this line segment 15 | private final Point q; // the other endpoint of this line segment 16 | 17 | /** 18 | * Initializes a new line segment. 19 | * 20 | * @param p one endpoint 21 | * @param q the other endpoint 22 | * @throws NullPointerException if either p or q 23 | * is null 24 | */ 25 | public LineSegment(Point p, Point q) { 26 | if (p == null || q == null) { 27 | throw new NullPointerException("argument is null"); 28 | } 29 | this.p = p; 30 | this.q = q; 31 | } 32 | 33 | 34 | /** 35 | * Draws this line segment to standard draw. 36 | */ 37 | public void draw() { 38 | p.drawTo(q); 39 | } 40 | 41 | /** 42 | * Returns a string representation of this line segment 43 | * This method is provide for debugging; 44 | * your program should not rely on the format of the string representation. 45 | * 46 | * @return a string representation of this line segment 47 | */ 48 | public String toString() { 49 | return p + " -> " + q; 50 | } 51 | 52 | /** 53 | * Throws an exception if called. The hashCode() method is not supported because 54 | * hashing has not yet been introduced in this course. Moreover, hashing does not 55 | * typically lead to good *worst-case* performance guarantees, as required on this 56 | * assignment. 57 | * 58 | * @throws UnsupportedOperationException if called 59 | */ 60 | public int hashCode() { 61 | throw new UnsupportedOperationException(); 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /Assignment-3/Point.java: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************* 2 | * Author : Deepak Kumar Sood 3 | * Date : 14-Jan-2017 4 | * Last updated : 14-Jan-2017 5 | * 6 | * Compilation : javac-algs4 Point.java 7 | * Execution : java-algs4 Point 8 | * 9 | * Purpose of the program : An immutable data type for points in the plane. 10 | * Assingment link : http://coursera.cs.princeton.edu/algs4/assignments/collinear.html 11 | * Score : 100/100 12 | **********************************************************************************************************************/ 13 | 14 | import java.util.Comparator; 15 | import edu.princeton.cs.algs4.StdDraw; 16 | 17 | public class Point implements Comparable { 18 | 19 | private final int x; // x-coordinate of this point 20 | private final int y; // y-coordinate of this point 21 | 22 | /** 23 | * Initializes a new point. 24 | * 25 | * @param x the x-coordinate of the point 26 | * @param y the y-coordinate of the point 27 | */ 28 | public Point(int x, int y) { 29 | /* DO NOT MODIFY */ 30 | this.x = x; 31 | this.y = y; 32 | } 33 | 34 | /** 35 | * Draws this point to standard draw. 36 | */ 37 | public void draw() { 38 | /* DO NOT MODIFY */ 39 | StdDraw.point(x, y); 40 | } 41 | 42 | /** 43 | * Draws the line segment between this point and the specified point 44 | * to standard draw. 45 | * 46 | * @param that the other point 47 | */ 48 | public void drawTo(Point that) { 49 | /* DO NOT MODIFY */ 50 | StdDraw.line(this.x, this.y, that.x, that.y); 51 | } 52 | 53 | /** 54 | * Returns the slope between this point and the specified point. 55 | * Formally, if the two points are (x0, y0) and (x1, y1), then the slope 56 | * is (y1 - y0) / (x1 - x0). For completeness, the slope is defined to be 57 | * +0.0 if the line segment connecting the two points is horizontal; 58 | * Double.POSITIVE_INFINITY if the line segment is vertical; 59 | * and Double.NEGATIVE_INFINITY if (x0, y0) and (x1, y1) are equal. 60 | * 61 | * @param that the other point 62 | * @return the slope between this point and the specified point 63 | */ 64 | public double slopeTo(Point that) { 65 | /* Both are equal */ 66 | if (this.compareTo(that) == 0) 67 | return Double.NEGATIVE_INFINITY; 68 | 69 | /* Horizontal line segment */ 70 | if (that.y == this.y) 71 | return 0.0; 72 | 73 | /* Vertical line segment */ 74 | if (that.x == this.x) 75 | return Double.POSITIVE_INFINITY; 76 | 77 | double diffX = that.x - this.x; 78 | double diffY = that.y - this.y; 79 | 80 | return diffY / diffX; 81 | } 82 | 83 | /** 84 | * Compares two points by y-coordinate, breaking ties by x-coordinate. 85 | * Formally, the invoking point (x0, y0) is less than the argument point 86 | * (x1, y1) if and only if either y0 < y1 or if y0 = y1 and x0 < x1. 87 | * 88 | * @param that the other point 89 | * @return the value 0 if this point is equal to the argument 90 | * point (x0 = x1 and y0 = y1); 91 | * a negative integer if this point is less than the argument 92 | * point; and a positive integer if this point is greater than the 93 | * argument point 94 | */ 95 | public int compareTo(Point that) { 96 | /* YOUR CODE HERE */ 97 | if (this.y < that.y) return -1; 98 | if (this.y > that.y) return +1; 99 | if (this.x < that.x) return -1; 100 | if (this.x > that.x) return +1; 101 | return 0; 102 | } 103 | 104 | /** 105 | * Compares two points by the slope they make with this point. 106 | * The slope is defined as in the slopeTo() method. 107 | * 108 | * @return the Comparator that defines this ordering on points 109 | */ 110 | public Comparator slopeOrder() { 111 | /* YOUR CODE HERE */ 112 | return new Comparator() { 113 | @Override 114 | public int compare(Point a, Point b) { 115 | double slopeDiff = slopeTo(a) - slopeTo(b); 116 | if (slopeDiff > 0) return 1; 117 | else if (slopeDiff < 0) return -1; 118 | else return 0; 119 | } 120 | }; 121 | } 122 | 123 | 124 | /** 125 | * Returns a string representation of this point. 126 | * This method is provide for debugging; 127 | * your program should not rely on the format of the string representation. 128 | * 129 | * @return a string representation of this point 130 | */ 131 | public String toString() { 132 | /* DO NOT MODIFY */ 133 | return "(" + x + ", " + y + ")"; 134 | } 135 | 136 | /** 137 | * Unit tests the Point data type. 138 | */ 139 | public static void main(String[] args) { 140 | /* YOUR CODE HERE */ 141 | Point first = new Point(1, 2); 142 | Point second = new Point(2, 4); 143 | 144 | System.out.println(first.slopeTo(second)); 145 | } 146 | } -------------------------------------------------------------------------------- /Assignment-4/Board.java: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************* 2 | * Author : Deepak Kumar Sood 3 | * Date : 21-Jan-2017 4 | * Last updated : 21-Jan-2017 5 | * 6 | * Compilation : javac-algs4 Board.java 7 | * Execution : java-algs4 Board 8 | * 9 | * Purpose of the program : To find the solution to 8-puzzle problem using A* Search Algorithm 10 | * Assingment link : http://coursera.cs.princeton.edu/algs4/assignments/8puzzle.html 11 | * Score : 90/100 12 | **********************************************************************************************************************/ 13 | import java.util.Arrays; 14 | import edu.princeton.cs.algs4.Queue; 15 | 16 | import edu.princeton.cs.algs4.In; 17 | import edu.princeton.cs.algs4.StdOut; 18 | 19 | public class Board { 20 | 21 | private final int size; 22 | private int[] board; 23 | 24 | /** 25 | * construct a board from an n-by-n array of blocks 26 | * (where blocks[i][j] = block in row i, column j) 27 | */ 28 | public Board(int[][] blocks) { 29 | size = blocks[0].length; 30 | board = new int[size * size]; 31 | for (int i = 0; i < size; i++) 32 | for (int j = 0; j < size; j++) 33 | board[i * size + j] = blocks[i][j]; 34 | } 35 | 36 | /** 37 | * private constructor useful in twin() 38 | */ 39 | private Board(int[] board) { 40 | size = (int) Math.sqrt(board.length); 41 | this.board = new int[board.length]; 42 | for (int i = 0; i < board.length; i++) 43 | this.board[i] = board[i]; 44 | } 45 | 46 | /** 47 | * board dimension n 48 | */ 49 | public int dimension() { 50 | return size; 51 | } 52 | 53 | /** 54 | * number of blocks out of place 55 | */ 56 | public int hamming() { 57 | int count = 0; 58 | for (int i = 0; i < size * size; i++) 59 | if (board[i] != i + 1 && board[i] != 0) 60 | count++; 61 | return count; 62 | } 63 | 64 | /** 65 | * sum of Manhattan distances between blocks and goal 66 | */ 67 | public int manhattan() { 68 | int sum = 0; 69 | for (int i = 0; i < size * size; i++) 70 | if (board[i] != i + 1 && board[i] != 0) 71 | sum += manhattan(board[i], i); 72 | return sum; 73 | } 74 | 75 | /** 76 | * return manhattan distance of a misplaced block 77 | */ 78 | private int manhattan(int goal, int current) { 79 | int row, col; 80 | row = Math.abs((goal - 1) / size - current / size); 81 | col = Math.abs((goal - 1) % size - current % size); 82 | return row + col; 83 | } 84 | 85 | /** 86 | * is this board the goal board? 87 | */ 88 | public boolean isGoal() { 89 | for (int i = 0; i < size * size - 1; i++) 90 | if (board[i] != i + 1) 91 | return false; 92 | return true; 93 | } 94 | 95 | /** 96 | * a board that is obtained by exchanging any pair of blocks 97 | */ 98 | public Board twin() { 99 | Board twin; 100 | if (size == 1) return null; 101 | twin = new Board(board); 102 | 103 | if (board[0] != 0 && board[1] != 0) 104 | exch(twin, 0, 1); 105 | else 106 | exch(twin, size, size + 1); 107 | return twin; 108 | } 109 | 110 | /** 111 | * exchange two elements in the array 112 | */ 113 | private Board exch(Board a, int i, int j) { 114 | int temp = a.board[i]; 115 | a.board[i] = a.board[j]; 116 | a.board[j] = temp; 117 | return a; 118 | } 119 | 120 | /** 121 | * does this board equal y? 122 | */ 123 | public boolean equals(Object y) { 124 | if (y == this) return true; 125 | if (y == null) return false; 126 | if (y.getClass() != this.getClass()) return false; 127 | 128 | Board that = (Board) y; 129 | return Arrays.equals(this.board, that.board); 130 | } 131 | 132 | /** 133 | * all neighboring boards 134 | */ 135 | public Iterable neighbors() { 136 | int index = 0; 137 | boolean found = false; 138 | Board neighbor; 139 | Queue q = new Queue(); 140 | 141 | for (int i = 0; i < board.length; i++) 142 | if (board[i] == 0) { 143 | index = i; 144 | found = true; 145 | break; 146 | } 147 | 148 | if (!found) return null; 149 | 150 | // exchange with upper block 151 | if (index / size != 0) { 152 | neighbor = new Board(board); 153 | exch(neighbor, index, index - size); 154 | q.enqueue(neighbor); 155 | } 156 | 157 | // exchange with lower block 158 | if (index / size != (size - 1)) { 159 | neighbor = new Board(board); 160 | exch(neighbor, index, index + size); 161 | q.enqueue(neighbor); 162 | } 163 | 164 | // exchange with left block 165 | if ((index % size) != 0) { 166 | neighbor = new Board(board); 167 | exch(neighbor, index, index - 1); 168 | q.enqueue(neighbor); 169 | } 170 | 171 | // exchange with right block 172 | if ((index % size) != size - 1) { 173 | neighbor = new Board(board); 174 | exch(neighbor, index, index + 1); 175 | q.enqueue(neighbor); 176 | } 177 | 178 | return q; 179 | } 180 | 181 | /** 182 | * string representation of this board (in the output format specified below) 183 | */ 184 | public String toString() { 185 | StringBuilder s = new StringBuilder(); 186 | s.append(size + "\n"); 187 | for (int i = 0; i < size; i++) { 188 | for (int j = 0; j < size; j++) 189 | s.append(String.format("%2d ", board[i * size + j])); 190 | s.append("\n"); 191 | } 192 | return s.toString(); 193 | } 194 | 195 | /** 196 | * unit tests 197 | */ 198 | public static void main(String[] args) { 199 | In in = new In(args[0]); 200 | int n = in.readInt(); 201 | int[][] blocks = new int[n][n]; 202 | for (int i = 0; i < n; i++) 203 | for (int j = 0; j < n; j++) 204 | blocks[i][j] = in.readInt(); 205 | Board initial = new Board(blocks); 206 | StdOut.println(initial); 207 | } 208 | } -------------------------------------------------------------------------------- /Assignment-4/PuzzleChecker.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac PuzzleChecker.java 3 | * Execution: java PuzzleChecker filename1.txt filename2.txt ... 4 | * Dependencies: Board.java Solver.java 5 | * 6 | * This program creates an initial board from each filename specified 7 | * on the command line and finds the minimum number of moves to 8 | * reach the goal state. 9 | * 10 | * % java PuzzleChecker puzzle*.txt 11 | * puzzle00.txt: 0 12 | * puzzle01.txt: 1 13 | * puzzle02.txt: 2 14 | * puzzle03.txt: 3 15 | * puzzle04.txt: 4 16 | * puzzle05.txt: 5 17 | * puzzle06.txt: 6 18 | * ... 19 | * puzzle3x3-impossible: -1 20 | * ... 21 | * puzzle42.txt: 42 22 | * puzzle43.txt: 43 23 | * puzzle44.txt: 44 24 | * puzzle45.txt: 45 25 | * 26 | ******************************************************************************/ 27 | 28 | import edu.princeton.cs.algs4.In; 29 | import edu.princeton.cs.algs4.StdOut; 30 | 31 | public class PuzzleChecker { 32 | 33 | public static void main(String[] args) { 34 | 35 | // for each command-line argument 36 | for (String filename : args) { 37 | 38 | // read in the board specified in the filename 39 | In in = new In(filename); 40 | int n = in.readInt(); 41 | int[][] tiles = new int[n][n]; 42 | for (int i = 0; i < n; i++) { 43 | for (int j = 0; j < n; j++) { 44 | tiles[i][j] = in.readInt(); 45 | } 46 | } 47 | 48 | // solve the slider puzzle 49 | Board initial = new Board(tiles); 50 | Solver solver = new Solver(initial); 51 | StdOut.println(filename + ": " + solver.moves()); 52 | } 53 | } 54 | } -------------------------------------------------------------------------------- /Assignment-4/Solver.java: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************* 2 | * Author : Deepak Kumar Sood 3 | * Date : 21-Jan-2017 4 | * Last updated : 21-Jan-2017 5 | * 6 | * Compilation : javac-algs4 Solver.java 7 | * Execution : java-algs4 Solver 8 | * 9 | * Purpose of the program : To find the solution to 8-puzzle problem using A* Search Algorithm 10 | * Assingment link : http://coursera.cs.princeton.edu/algs4/assignments/8puzzle.html 11 | * Score : 90/100 12 | **********************************************************************************************************************/ 13 | import java.util.Comparator; 14 | 15 | import edu.princeton.cs.algs4.In; 16 | import edu.princeton.cs.algs4.StdOut; 17 | import edu.princeton.cs.algs4.MinPQ; 18 | import edu.princeton.cs.algs4.Stack; 19 | 20 | public class Solver { 21 | 22 | private SearchNode goal; 23 | 24 | private class SearchNode { 25 | private int moves; 26 | private Board board; 27 | private SearchNode prev; 28 | // cache the manhattan distance to avoid recomputing its value 29 | private final int manhattanPriority; 30 | 31 | public SearchNode(Board initial) { 32 | moves = 0; 33 | prev = null; 34 | board = initial; 35 | manhattanPriority = board.manhattan(); 36 | } 37 | } 38 | 39 | /** 40 | * find a solution to the initial board (using the A* algorithm) 41 | */ 42 | public Solver(Board initial) { 43 | if (initial == null) throw new IllegalArgumentException(); 44 | 45 | PriorityOrder order = new PriorityOrder(); 46 | MinPQ PQ = new MinPQ(order); 47 | MinPQ twinPQ = new MinPQ(order); 48 | SearchNode node = new SearchNode(initial); 49 | SearchNode twinNode = new SearchNode(initial); 50 | PQ.insert(node); 51 | twinPQ.insert(twinNode); 52 | 53 | SearchNode min = PQ.delMin(); 54 | SearchNode twinMin = twinPQ.delMin(); 55 | 56 | while (!min.board.isGoal() && !twinMin.board.isGoal()) { 57 | 58 | for (Board b : min.board.neighbors()) { 59 | if (min.prev == null || !b.equals(min.prev.board)) { // check if move back this previous state 60 | SearchNode n = new SearchNode(b); 61 | n.moves = min.moves + 1; 62 | n.prev = min; 63 | PQ.insert(n); 64 | } 65 | } 66 | 67 | for (Board b : twinMin.board.neighbors()) { 68 | if (twinMin.prev == null || !b.equals(twinMin.prev.board)) { 69 | SearchNode n = new SearchNode(b); 70 | n.moves = twinMin.moves + 1; 71 | n.prev = twinMin; 72 | twinPQ.insert(n); 73 | } 74 | } 75 | 76 | min = PQ.delMin(); 77 | twinMin = twinPQ.delMin(); 78 | } 79 | if (min.board.isGoal()) goal = min; 80 | else goal = null; 81 | } 82 | 83 | private class PriorityOrder implements Comparator { 84 | public int compare(SearchNode a, SearchNode b) { 85 | int pa = a.manhattanPriority + a.moves; 86 | int pb = b.manhattanPriority + b.moves; 87 | if (pa > pb) return 1; 88 | if (pa < pb) return -1; 89 | else return 0; 90 | } 91 | } 92 | 93 | /** 94 | * is the initial board solvable? 95 | */ 96 | public boolean isSolvable() { 97 | return goal != null; 98 | } 99 | 100 | /** 101 | * min number of moves to solve initial board; -1 if unsolvable 102 | */ 103 | public int moves() { 104 | if (!isSolvable()) return -1; 105 | else return goal.moves; 106 | } 107 | 108 | /** 109 | * sequence of boards in a shortest solution; null if unsolvable 110 | */ 111 | public Iterable solution() { 112 | if (!isSolvable()) return null; 113 | Stack s = new Stack(); 114 | for (SearchNode n = goal; n != null; n = n.prev) 115 | s.push(n.board); 116 | return s; 117 | } 118 | 119 | public static void main(String[] args) { 120 | 121 | // create initial board from file 122 | In in = new In(args[0]); 123 | int n = in.readInt(); 124 | int[][] blocks = new int[n][n]; 125 | for (int i = 0; i < n; i++) 126 | for (int j = 0; j < n; j++) 127 | blocks[i][j] = in.readInt(); 128 | Board initial = new Board(blocks); 129 | 130 | // solve the puzzle 131 | Solver solver = new Solver(initial); 132 | 133 | // print solution to standard output 134 | if (!solver.isSolvable()) 135 | StdOut.println("No solution possible"); 136 | else { 137 | StdOut.println("Minimum number of moves = " + solver.moves()); 138 | for (Board board : solver.solution()) 139 | StdOut.println(board); 140 | } 141 | } 142 | } -------------------------------------------------------------------------------- /Assignment-5/KdTree.java: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************* 2 | * Author : Deepak Kumar Sood 3 | * Date : 25-Jan-2017 4 | * Last updated : 25-Jan-2017 5 | * 6 | * Compilation : javac-algs4 KdTree.java 7 | * Execution : java-algs4 KdTree 8 | * 9 | * Purpose of the program : Implementation of KdTree for range search and nearest neighbor search 10 | * Assingment link : http://coursera.cs.princeton.edu/algs4/assignments/kdtree.html 11 | * Score : 99/100 12 | **********************************************************************************************************************/ 13 | import edu.princeton.cs.algs4.Point2D; 14 | import edu.princeton.cs.algs4.RectHV; 15 | import edu.princeton.cs.algs4.StdDraw; 16 | import edu.princeton.cs.algs4.Queue; 17 | 18 | public class KdTree { 19 | 20 | private Node root; 21 | private int size; 22 | 23 | private static class Node { 24 | // the 2d point 25 | private final Point2D p; 26 | 27 | // the axis-aligned rectangle corresponding to this node 28 | private final RectHV rect; 29 | 30 | // the left/bottom subtree 31 | private Node lb; 32 | 33 | // the right/top subtree 34 | private Node rb; 35 | 36 | // public constructor 37 | public Node(Point2D p, RectHV rect) { 38 | this.p = p; 39 | 40 | RectHV r = rect; 41 | if (r == null) 42 | r = new RectHV(0, 0, 1, 1); 43 | this.rect = r; 44 | } 45 | } 46 | 47 | // construct an empty set of points 48 | public KdTree() { 49 | root = null; 50 | size = 0; 51 | } 52 | 53 | // is the set empty? 54 | public boolean isEmpty() { 55 | return root == null; 56 | } 57 | 58 | // number of points in the set 59 | public int size() { 60 | return size; 61 | } 62 | 63 | // insert a horizontal node 64 | private Node insertH(Node node, Point2D p, RectHV rect) { 65 | if (node == null) { 66 | size++; 67 | return new Node(p, rect); 68 | } 69 | if (node.p.equals(p)) return node; 70 | 71 | RectHV r; 72 | int cmp = Point2D.Y_ORDER.compare(node.p, p); 73 | if (cmp > 0) { 74 | if (node.lb == null) 75 | r = new RectHV(rect.xmin(), rect.ymin(), rect.xmax(), node.p.y()); 76 | else 77 | r = node.lb.rect; 78 | node.lb = insertV(node.lb, p, r); 79 | } else { 80 | if (node.rb == null) 81 | r = new RectHV(rect.xmin(), node.p.y(), rect.xmax(), rect.ymax()); 82 | else 83 | r = node.rb.rect; 84 | node.rb = insertV(node.rb, p, r); 85 | } 86 | 87 | return node; 88 | } 89 | 90 | // insert a vertical node 91 | private Node insertV(Node node, Point2D p, RectHV rect) { 92 | if (node == null) { 93 | size++; 94 | return new Node(p, rect); 95 | } 96 | 97 | // if two points are same 98 | if (node.p.equals(p)) return node; 99 | 100 | RectHV r; 101 | int cmp = Point2D.X_ORDER.compare(node.p, p); 102 | if (cmp > 0) { 103 | if (node.lb == null) 104 | r = new RectHV(rect.xmin(), rect.ymin(), node.p.x(), rect.ymax()); 105 | else 106 | r = node.lb.rect; 107 | node.lb = insertH(node.lb, p, r); 108 | } else { 109 | if (node.rb == null) 110 | r = new RectHV(node.p.x(), rect.ymin(), rect.xmax(), rect.ymax()); 111 | else 112 | r = node.rb.rect; 113 | node.rb = insertH(node.rb, p, r); 114 | } 115 | 116 | return node; 117 | } 118 | 119 | // add the point to the set (if it is not already in the set) 120 | public void insert(Point2D p) { 121 | if (p == null) throw new IllegalArgumentException(); 122 | 123 | if (isEmpty()) 124 | root = insertV(root, p, null); 125 | else 126 | root = insertV(root, p, root.rect); 127 | } 128 | 129 | private boolean contains(Node node, Point2D p, boolean vert) { 130 | if (node == null) return false; 131 | if (node.p.equals(p)) return true; 132 | int cmp; 133 | if (vert) 134 | cmp = Point2D.X_ORDER.compare(node.p, p); 135 | else 136 | cmp = Point2D.Y_ORDER.compare(node.p, p); 137 | if (cmp > 0) 138 | return contains(node.lb, p, !vert); 139 | else 140 | return contains(node.rb, p, !vert); 141 | } 142 | 143 | // does the set contain point p? 144 | public boolean contains(Point2D p) { 145 | if (p == null) throw new IllegalArgumentException(); 146 | 147 | return contains(root, p, true); 148 | } 149 | 150 | private void draw(Node node, boolean vert) { 151 | if (node.lb != null) draw(node.lb, !vert); 152 | if (node.rb != null) draw(node.rb, !vert); 153 | 154 | StdDraw.setPenColor(StdDraw.BLACK); 155 | StdDraw.setPenRadius(0.01); 156 | StdDraw.point(node.p.x(), node.p.y()); 157 | 158 | double xmin, ymin, xmax, ymax; 159 | if (vert) { 160 | StdDraw.setPenColor(StdDraw.RED); 161 | xmin = node.p.x(); 162 | xmax = node.p.x(); 163 | ymin = node.rect.ymin(); 164 | ymax = node.rect.ymax(); 165 | } else { 166 | StdDraw.setPenColor(StdDraw.BLUE); 167 | ymin = node.p.y(); 168 | ymax = node.p.y(); 169 | xmin = node.rect.xmin(); 170 | xmax = node.rect.xmax(); 171 | } 172 | StdDraw.setPenRadius(); 173 | StdDraw.line(xmin, ymin, xmax, ymax); 174 | } 175 | 176 | // draw all points to standard draw 177 | public void draw() { 178 | StdDraw.rectangle(0.5, 0.5, 0.5, 0.5); 179 | if (isEmpty()) return; 180 | draw(root, true); 181 | } 182 | 183 | private void range(Node node, RectHV rect, Queue queue) { 184 | if (node == null) 185 | return; 186 | if (rect.contains(node.p)) 187 | queue.enqueue(node.p); 188 | if (node.lb != null && rect.intersects(node.lb.rect)) 189 | range(node.lb, rect, queue); 190 | if (node.rb != null && rect.intersects(node.rb.rect)) 191 | range(node.rb, rect, queue); 192 | } 193 | 194 | // all points that are inside the rectangle (or on the boundary) 195 | public Iterable range(RectHV rect) { 196 | if (rect == null) throw new IllegalArgumentException(); 197 | 198 | Queue queue = new Queue(); 199 | range(root, rect, queue); 200 | return queue; 201 | } 202 | 203 | private Point2D nearest(Node node, Point2D p, Point2D mp, boolean vert) { 204 | Point2D min = mp; 205 | 206 | if (node == null) return min; 207 | if (p.distanceSquaredTo(node.p) < p.distanceSquaredTo(min)) 208 | min = node.p; 209 | 210 | if (vert) { 211 | if (node.p.x() < p.x()) { 212 | min = nearest(node.rb, p, min, !vert); 213 | if (node.lb != null && (min.distanceSquaredTo(p) > node.lb.rect.distanceSquaredTo(p))) 214 | min = nearest(node.lb, p, min, !vert); 215 | } else { 216 | min = nearest(node.lb, p, min, !vert); 217 | if (node.rb != null && (min.distanceSquaredTo(p) > node.rb.rect.distanceSquaredTo(p))) 218 | min = nearest(node.rb, p, min, !vert); 219 | } 220 | } else { 221 | if (node.p.y() < p.y()) { 222 | min = nearest(node.rb, p, min, !vert); 223 | if (node.lb != null && (min.distanceSquaredTo(p) > node.lb.rect.distanceSquaredTo(p))) 224 | min = nearest(node.lb, p, min, !vert); 225 | } else { 226 | min = nearest(node.lb, p, min, !vert); 227 | if (node.rb != null && (min.distanceSquaredTo(p) > node.rb.rect.distanceSquaredTo(p))) 228 | min = nearest(node.rb, p, min, !vert); 229 | } 230 | } 231 | return min; 232 | } 233 | 234 | // a nearest neighbor in the set to point p; null if the set is empty 235 | public Point2D nearest(Point2D p) { 236 | if (p == null) throw new IllegalArgumentException(); 237 | 238 | if (isEmpty()) return null; 239 | return nearest(root, p, root.p, true); 240 | } 241 | } -------------------------------------------------------------------------------- /Assignment-5/KdTreeVisualizer.java: -------------------------------------------------------------------------------- 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.isMousePressed()) { 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(20); 37 | } 38 | 39 | } 40 | } -------------------------------------------------------------------------------- /Assignment-5/NearestNeighborVisualizer.java: -------------------------------------------------------------------------------- 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 | 22 | // initialize the two data structures with point from file 23 | String filename = args[0]; 24 | In in = new In(filename); 25 | PointSET brute = new PointSET(); 26 | KdTree kdtree = new KdTree(); 27 | while (!in.isEmpty()) { 28 | double x = in.readDouble(); 29 | double y = in.readDouble(); 30 | Point2D p = new Point2D(x, y); 31 | kdtree.insert(p); 32 | brute.insert(p); 33 | } 34 | 35 | // process nearest neighbor queries 36 | StdDraw.enableDoubleBuffering(); 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 | } -------------------------------------------------------------------------------- /Assignment-5/PointSET.java: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************* 2 | * Author : Deepak Kumar Sood 3 | * Date : 25-Jan-2017 4 | * Last updated : 25-Jan-2017 5 | * 6 | * Compilation : javac-algs4 PointSET.java 7 | * Execution : java-algs4 PointSET 8 | * 9 | * Purpose of the program : Brute Force implementation for range search and nearest neighbor search 10 | * Assingment link : http://coursera.cs.princeton.edu/algs4/assignments/kdtree.html 11 | * Score : 99/100 12 | **********************************************************************************************************************/ 13 | import edu.princeton.cs.algs4.SET; 14 | import edu.princeton.cs.algs4.RectHV; 15 | import edu.princeton.cs.algs4.Point2D; 16 | 17 | import edu.princeton.cs.algs4.StdDraw; 18 | 19 | import edu.princeton.cs.algs4.Stack; 20 | 21 | public class PointSET { 22 | 23 | private final SET set; 24 | 25 | // construct an empty set of points 26 | public PointSET() { 27 | set = new SET(); 28 | } 29 | 30 | // is the set empty? 31 | public boolean isEmpty() { 32 | return set.isEmpty(); 33 | } 34 | 35 | // number of points in the set 36 | public int size() { 37 | return set.size(); 38 | } 39 | 40 | // add the point to the set (if it is not already in the set) 41 | public void insert(Point2D p) { 42 | if (p == null) throw new IllegalArgumentException(); 43 | set.add(p); 44 | } 45 | 46 | // does the set contain point p? 47 | public boolean contains(Point2D p) { 48 | if (p == null) throw new IllegalArgumentException(); 49 | return set.contains(p); 50 | } 51 | 52 | // draw all points to standard draw 53 | public void draw() { 54 | StdDraw.setPenColor(StdDraw.BLACK); 55 | StdDraw.setPenRadius(0.01); 56 | 57 | for (Point2D dot : set) 58 | StdDraw.point(dot.x(), dot.y()); 59 | } 60 | 61 | // all points that are inside the rectangle (or on the boundary) 62 | public Iterable range(RectHV rect) { 63 | if (rect == null) throw new IllegalArgumentException(); 64 | 65 | Stack stack = new Stack(); 66 | 67 | for (Point2D dot : set) 68 | if (rect.contains(dot)) 69 | stack.push(dot); 70 | 71 | return stack; 72 | } 73 | 74 | // a nearest neighbor in the set to point p; null if the set is empty 75 | public Point2D nearest(Point2D p) { 76 | if (p == null) throw new IllegalArgumentException(); 77 | 78 | if (isEmpty()) return null; 79 | 80 | double dist, minDist = Double.POSITIVE_INFINITY; 81 | Point2D nn = null; 82 | 83 | for (Point2D dot : set) { 84 | dist = p.distanceSquaredTo(dot); 85 | if (dist < minDist) { 86 | minDist = dist; 87 | nn = dot; 88 | } 89 | } 90 | return nn; 91 | } 92 | } -------------------------------------------------------------------------------- /Assignment-5/RangeSearchVisualizer.java: -------------------------------------------------------------------------------- 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 | // initialize the data structures from file 25 | String filename = args[0]; 26 | In in = new In(filename); 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(0.01); 45 | brute.draw(); 46 | StdDraw.show(); 47 | 48 | // process range search queries 49 | StdDraw.enableDoubleBuffering(); 50 | while (true) { 51 | 52 | // user starts to drag a rectangle 53 | if (StdDraw.isMousePressed() && !isDragging) { 54 | x0 = x1 = StdDraw.mouseX(); 55 | y0 = y1 = StdDraw.mouseY(); 56 | isDragging = true; 57 | } 58 | 59 | // user is dragging a rectangle 60 | else if (StdDraw.isMousePressed() && isDragging) { 61 | x1 = StdDraw.mouseX(); 62 | y1 = StdDraw.mouseY(); 63 | } 64 | 65 | // user stops dragging rectangle 66 | else if (!StdDraw.isMousePressed() && isDragging) { 67 | isDragging = false; 68 | } 69 | 70 | // draw the points 71 | StdDraw.clear(); 72 | StdDraw.setPenColor(StdDraw.BLACK); 73 | StdDraw.setPenRadius(0.01); 74 | brute.draw(); 75 | 76 | // draw the rectangle 77 | RectHV rect = new RectHV(Math.min(x0, x1), Math.min(y0, y1), 78 | Math.max(x0, x1), Math.max(y0, y1)); 79 | StdDraw.setPenColor(StdDraw.BLACK); 80 | StdDraw.setPenRadius(); 81 | rect.draw(); 82 | 83 | // draw the range search results for brute-force data structure in red 84 | StdDraw.setPenRadius(0.03); 85 | StdDraw.setPenColor(StdDraw.RED); 86 | for (Point2D p : brute.range(rect)) 87 | p.draw(); 88 | 89 | // draw the range search results for kd-tree in blue 90 | StdDraw.setPenRadius(.02); 91 | StdDraw.setPenColor(StdDraw.BLUE); 92 | for (Point2D p : kdtree.range(rect)) 93 | p.draw(); 94 | 95 | StdDraw.show(); 96 | StdDraw.pause(20); 97 | } 98 | } 99 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Deepak Sood 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Lecture Slides/13StacksAndQueues.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepaksood619/Coursera-Algorithms-Part-1/58b7565f03cfee0cfba253a10f4e91927f280670/Lecture Slides/13StacksAndQueues.pdf -------------------------------------------------------------------------------- /Lecture Slides/14AnalysisOfAlgorithms.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepaksood619/Coursera-Algorithms-Part-1/58b7565f03cfee0cfba253a10f4e91927f280670/Lecture Slides/14AnalysisOfAlgorithms.pdf -------------------------------------------------------------------------------- /Lecture Slides/15UnionFind.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepaksood619/Coursera-Algorithms-Part-1/58b7565f03cfee0cfba253a10f4e91927f280670/Lecture Slides/15UnionFind.pdf -------------------------------------------------------------------------------- /Lecture Slides/21ElementarySorts.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepaksood619/Coursera-Algorithms-Part-1/58b7565f03cfee0cfba253a10f4e91927f280670/Lecture Slides/21ElementarySorts.pdf -------------------------------------------------------------------------------- /Lecture Slides/22Mergesort.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepaksood619/Coursera-Algorithms-Part-1/58b7565f03cfee0cfba253a10f4e91927f280670/Lecture Slides/22Mergesort.pdf -------------------------------------------------------------------------------- /Lecture Slides/23Quicksort.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepaksood619/Coursera-Algorithms-Part-1/58b7565f03cfee0cfba253a10f4e91927f280670/Lecture Slides/23Quicksort.pdf -------------------------------------------------------------------------------- /Lecture Slides/24PriorityQueues.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepaksood619/Coursera-Algorithms-Part-1/58b7565f03cfee0cfba253a10f4e91927f280670/Lecture Slides/24PriorityQueues.pdf -------------------------------------------------------------------------------- /Lecture Slides/31ElementarySymbolTables.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepaksood619/Coursera-Algorithms-Part-1/58b7565f03cfee0cfba253a10f4e91927f280670/Lecture Slides/31ElementarySymbolTables.pdf -------------------------------------------------------------------------------- /Lecture Slides/32BinarySearchTrees.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepaksood619/Coursera-Algorithms-Part-1/58b7565f03cfee0cfba253a10f4e91927f280670/Lecture Slides/32BinarySearchTrees.pdf -------------------------------------------------------------------------------- /Lecture Slides/33BalancedSearchTrees.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepaksood619/Coursera-Algorithms-Part-1/58b7565f03cfee0cfba253a10f4e91927f280670/Lecture Slides/33BalancedSearchTrees.pdf -------------------------------------------------------------------------------- /Lecture Slides/34HashTables.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepaksood619/Coursera-Algorithms-Part-1/58b7565f03cfee0cfba253a10f4e91927f280670/Lecture Slides/34HashTables.pdf -------------------------------------------------------------------------------- /Lecture Slides/35SearchingApplications.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepaksood619/Coursera-Algorithms-Part-1/58b7565f03cfee0cfba253a10f4e91927f280670/Lecture Slides/35SearchingApplications.pdf -------------------------------------------------------------------------------- /Lecture Slides/99GeometricSearch.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepaksood619/Coursera-Algorithms-Part-1/58b7565f03cfee0cfba253a10f4e91927f280670/Lecture Slides/99GeometricSearch.pdf -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Coursera-Algorithms-Part-1 2 | 3 | ## Assignment - 1 4 | Problem Statement - A program to estimate the value of the percolation threshold via Monte Carlo simulation. 5 | 6 | Website - [Percolation.html](http://coursera.cs.princeton.edu/algs4/assignments/percolation.html) 7 | 8 | Score - 100/100 9 | 10 | ## Assignment - 2 11 | Problem Statement - A generic Randomized Queue and Dequeue implementation 12 | 13 | Website - [Queues.html](http://coursera.cs.princeton.edu/algs4/assignments/queues.html) 14 | 15 | Score - 100/100 16 | 17 | ## Assignment - 3 18 | Problem Statement - Calculate Collinear points in a given set of points 19 | 20 | Website - [Collinear.html](http://coursera.cs.princeton.edu/algs4/assignments/collinear.html) 21 | 22 | Score - 100/100 23 | 24 | ## Assignment - 4 25 | Problem Statement - To find the solution to 8-puzzle problem using A* Search Algorithm 26 | 27 | Website - [8puzzle.html](http://coursera.cs.princeton.edu/algs4/assignments/8puzzle.html) 28 | 29 | Score - 90/100 30 | 31 | ## Assignment - 5 32 | Problem Statement - Implement Range Search and Nearest Neighbor Search using 2dtree 33 | 34 | Website - [Kdtree.html](http://coursera.cs.princeton.edu/algs4/assignments/kdtree.html) 35 | 36 | Score - 99/100 37 | 38 | #### Final Course Grade - 97.8% 39 | -------------------------------------------------------------------------------- /Week2/DutchNationalFlag.java: -------------------------------------------------------------------------------- 1 | // 0 - low-1 (zero) 2 | // low - mid-1 (one) 3 | // high+1 - n (two) 4 | // mid - high (unknown) 5 | 6 | class DutchNationalFlag { 7 | 8 | public static void sort012(int[] arr, int len) { 9 | int low = 0; 10 | int mid = 0; 11 | int high = len-1; 12 | 13 | while(mid <= high) { 14 | switch (arr[mid]) { 15 | case 0: 16 | swap(arr, mid, low); 17 | mid++; 18 | low++; 19 | break; 20 | 21 | case 1: 22 | mid++; 23 | break; 24 | 25 | case 2: 26 | swap(arr, high, mid); 27 | high--; 28 | break; 29 | } 30 | } 31 | } 32 | 33 | public static void swap(int[] arr, int i, int j) { 34 | arr[i] = arr[i] + arr[j]; 35 | arr[j] = arr[i] - arr[j]; 36 | arr[i] = arr[i] - arr[j]; 37 | } 38 | 39 | public static void main (String[] args) 40 | { 41 | int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; 42 | int arr_size = arr.length; 43 | sort012(arr, arr_size); 44 | System.out.println("Array after seggregation "); 45 | 46 | for (int i = 0; i < arr_size; i++) { 47 | System.out.print(arr[i] + " "); 48 | } 49 | } 50 | } -------------------------------------------------------------------------------- /Week2/Insertion.java: -------------------------------------------------------------------------------- 1 | public class Insertion { 2 | 3 | public static void sort(Comparable[] a) { 4 | int N = a.length; 5 | for (int i = 1; i < N; i++) { 6 | int j = i; 7 | while(j > 0 && less(a[j], a[j-1])) { 8 | exch(a, j, j-1); 9 | j--; 10 | } 11 | } 12 | } 13 | 14 | private static boolean less(Comparable v, Comparable w) { 15 | return v.compareTo(w) < 0; 16 | } 17 | 18 | private static void exch(Comparable[] a, int i, int j) { 19 | Comparable swap = a[i]; 20 | a[i] = a[j]; 21 | a[j] = swap; 22 | } 23 | 24 | public static void main(String[] args) { 25 | Integer[] arr = {9, 8, 7, 1, 5, 4, 3, 2, 6}; 26 | Insertion.sort(arr); 27 | 28 | for (int i = 0; i < arr.length; i++) { 29 | System.out.print(arr[i] + " "); 30 | } 31 | 32 | } 33 | } -------------------------------------------------------------------------------- /Week2/Intersection.java: -------------------------------------------------------------------------------- 1 | import edu.princeton.cs.algs4.Merge; 2 | 3 | public class Intersection { 4 | class Point implements Comparable { 5 | private int x; 6 | private int y; 7 | 8 | public Point(int x, int y) { 9 | this.x = x; 10 | this.y = y; 11 | } 12 | 13 | @Override 14 | public int compareTo(Point that) { 15 | if (that.x > this.x) return -1; 16 | if (that.x < this.x) return 1; 17 | if (that.y > this.y) return -1; 18 | if (that.y < this.y) return 1; 19 | return 0; 20 | } 21 | 22 | public int countIntersection(Point[] a, Point[] b) { 23 | Merge.sort(a); 24 | Merge.sort(b); 25 | 26 | int i = 0; 27 | int j = 0; 28 | int count = 0; 29 | 30 | while (i < a.length && j < b.length) { 31 | int val = a[i].compareTo(b[i]); 32 | if (val == 0) { 33 | count++; 34 | i++; 35 | j++; 36 | } else if (val < 0) i++; 37 | else j++; 38 | } 39 | return count; 40 | } 41 | } 42 | } -------------------------------------------------------------------------------- /Week2/KnuthShuffle.java: -------------------------------------------------------------------------------- 1 | import edu.princeton.cs.algs4.StdRandom; 2 | 3 | public class KnuthShuffle { 4 | 5 | public static void shuffle(Comparable[] a) { 6 | int N = a.length; 7 | for (int i = 1; i < N; i++) { 8 | int rand = StdRandom.uniform(i); 9 | exch(a, i, rand); 10 | } 11 | } 12 | 13 | private static boolean less(Comparable v, Comparable w) { 14 | return v.compareTo(w) < 0; 15 | } 16 | 17 | private static void exch(Comparable[] a, int i, int j) { 18 | Comparable swap = a[i]; 19 | a[i] = a[j]; 20 | a[j] = swap; 21 | } 22 | 23 | public static void main(String[] args) { 24 | Integer[] arr = {1,2,3,4,5,6,7,8,9}; 25 | KnuthShuffle.shuffle(arr); 26 | 27 | for (int i = 0; i < arr.length; i++) { 28 | System.out.print(arr[i] + " "); 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /Week2/Selection.java: -------------------------------------------------------------------------------- 1 | public class Selection { 2 | 3 | public static void sort(Comparable[] a) { 4 | int N = a.length; 5 | for (int i = 0; i < N-1; i++) { 6 | int min = i; 7 | for (int j = i+1; j < N; j++) 8 | if (less(a[j], a[min])) 9 | min = j; 10 | exch(a, i, min); 11 | } 12 | } 13 | 14 | private static boolean less(Comparable v, Comparable w) { 15 | return v.compareTo(w) < 0; 16 | } 17 | 18 | private static void exch(Comparable[] a, int i, int j) { 19 | Comparable swap = a[i]; 20 | a[i] = a[j]; 21 | a[j] = swap; 22 | } 23 | 24 | public static void main(String[] args) { 25 | Integer[] arr = {9, 8, 7, 1, 5, 4, 3, 2, 6}; 26 | Selection.sort(arr); 27 | 28 | for (int i = 0; i < arr.length; i++) { 29 | System.out.print(arr[i] + " "); 30 | } 31 | 32 | } 33 | } -------------------------------------------------------------------------------- /Week2/Shell.java: -------------------------------------------------------------------------------- 1 | public class Shell { 2 | 3 | public static void sort(Comparable[] a) { 4 | int N = a.length; 5 | int h = 1; 6 | 7 | while (h < N/3) h = 3*h + 1; 8 | 9 | while (h >= 1) { 10 | for (int i = h; i < N; i++) { 11 | for (int j = i; j >= h && less(a[j], a[j-h]); j -= h) 12 | exch(a, j, j-h); 13 | } 14 | h = h/3; 15 | } 16 | } 17 | 18 | private static boolean less(Comparable v, Comparable w) { 19 | return v.compareTo(w) < 0; 20 | } 21 | 22 | private static void exch(Comparable[] a, int i, int j) { 23 | Comparable swap = a[i]; 24 | a[i] = a[j]; 25 | a[j] = swap; 26 | } 27 | 28 | public static void main(String[] args) { 29 | Integer[] arr = {9, 8, 7, 1, 5, 4, 3, 2, 6}; 30 | Shell.sort(arr); 31 | 32 | for (int i = 0; i < arr.length; i++) { 33 | System.out.print(arr[i] + " "); 34 | } 35 | 36 | } 37 | } -------------------------------------------------------------------------------- /Week3/CountingInversions.java: -------------------------------------------------------------------------------- 1 | class CountingInversions { 2 | 3 | private static int count(int[] arr) { 4 | int count = 0; 5 | for (int i = 0; i < arr.length-1; i++) { 6 | for (int j = i+1; j < arr.length; j++) { 7 | if (arr[i] > arr[j]) 8 | count++; 9 | } 10 | } 11 | return count; 12 | } 13 | 14 | public static void main(String[] args) { 15 | int[] arr = {4,3,2,1}; 16 | System.out.println(count(arr)); 17 | } 18 | } -------------------------------------------------------------------------------- /Week3/MergeSmall.java: -------------------------------------------------------------------------------- 1 | class MergeSmall { 2 | 3 | private static void merge(int[] arr) { 4 | int low = 0; 5 | int high = arr.length - 1; 6 | int n = (low + high) / 2 + 1; 7 | 8 | int[] aux = new int[n]; 9 | 10 | // copy first half to aux 11 | for (int i = 0; i < n; i++) { 12 | aux[i] = arr[i]; 13 | } 14 | // index for first half of array 15 | int i = 0; 16 | 17 | // index for second half of array 18 | int j = n; 19 | 20 | // index for auxiliary array 21 | int k = 0; 22 | 23 | while(i <= high) { 24 | if (k >= n) { 25 | arr[i++] = arr[j++]; 26 | } else if(j > high) { 27 | arr[i++] = aux[k++]; 28 | } else if (arr[j] < aux[k]) { 29 | arr[i++] = arr[j++]; 30 | } else { 31 | arr[i++] = aux[k++]; 32 | } 33 | } 34 | 35 | } 36 | 37 | public static void main(String[] args) { 38 | int[] arr = {2,4,6,1,3,5}; 39 | merge(arr); 40 | 41 | for (int i = 0; i < arr.length; i++) { 42 | System.out.print(arr[i] + " "); 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /Week3/MergeSort1.java: -------------------------------------------------------------------------------- 1 | class MergeSort1 { 2 | 3 | private static void merge(int[] arr, int[] aux, int low, int mid, int high) { 4 | for (int k = low; k <= high; k++) { 5 | aux[k] = arr[k]; 6 | } 7 | 8 | int i = low, j = mid+1; 9 | for (int k = low; k <= high; k++) { 10 | if (i > mid) arr[k] = aux[j++]; 11 | else if (j > high) arr[k] = aux[i++]; 12 | else if (less(aux[j], aux[i])) arr[k] = aux[j++]; 13 | else arr[k] = aux[i++]; 14 | } 15 | } 16 | 17 | private static boolean less(Comparable v, Comparable w) { 18 | return v.compareTo(w) < 0; 19 | } 20 | 21 | private static void mergeSort(int[] arr, int[] aux, int low, int high) { 22 | if (high <= low) return; 23 | int mid = (low + high) / 2; 24 | mergeSort(arr, aux, low, mid); 25 | mergeSort(arr, aux, mid+1, high); 26 | merge(arr, aux, low, mid, high); 27 | } 28 | 29 | public static void sort(int[] arr) { 30 | int[] aux = new int[arr.length]; 31 | mergeSort(arr, aux, 0, arr.length - 1); 32 | } 33 | 34 | public static void main(String[] args) { 35 | int[] arr = {9,8,7,6,1,4,3,2,5}; 36 | sort(arr); 37 | 38 | for (int i = 0; i < arr.length; i++) { 39 | System.out.print(arr[i] + " "); 40 | } 41 | } 42 | } -------------------------------------------------------------------------------- /Week4/MinPQ.java: -------------------------------------------------------------------------------- 1 | import java.util.Comparator; 2 | import java.util.Iterator; 3 | import java.util.NoSuchElementException; 4 | 5 | import edu.princeton.cs.algs4.StdIn; 6 | import edu.princeton.cs.algs4.StdOut; 7 | 8 | class MinPQ implements Iterable { 9 | 10 | private Key[] pq; // store items at indices 1 to n 11 | private int n; // number of items on priority queue 12 | private Comparator comparator; // optional comparator 13 | 14 | public MinPQ(int initCapacity) { 15 | pq = (Key[]) new Object[initCapacity + 1]; 16 | n = 0; 17 | } 18 | 19 | public MinPQ() { 20 | this(1); 21 | } 22 | 23 | public MinPQ(int initCapacity, Comparator comparator) { 24 | this.comparator = comparator; 25 | pq = (Key[]) new Object[initCapacity + 1]; 26 | n = 0; 27 | } 28 | 29 | public MinPQ(Comparator comparator) { 30 | this(1, comparator); 31 | } 32 | 33 | public MinPQ(Key[] keys) { 34 | n = keys.length; 35 | pq = (Key[]) new Object[keys.length + 1]; 36 | for (int i = 0; i < keys.length; i++) 37 | pq[i+1] = keys[i]; 38 | for (int k = n/2; k >= 1; k--) 39 | sink(k); 40 | assert isMinHeap(); 41 | } 42 | 43 | public boolean isEmpty() { 44 | return n == 0; 45 | } 46 | 47 | public int size() { 48 | return n; 49 | } 50 | 51 | public Key min() { 52 | if (isEmpty()) throw new NoSuchElementException("Priority queue underflow"); 53 | return pq[1]; 54 | } 55 | 56 | private void resize(int capacity) { 57 | assert capacity > n; 58 | Key[] temp = (Key[]) new Object[capacity]; 59 | for (int i = 1; i <= n; i++) 60 | temp[i] = pq[i]; 61 | pq = temp; 62 | } 63 | 64 | public void insert(Key x) { 65 | if (n == pq.length - 1) resize(2 * pq.length); 66 | 67 | pq[++n] = x; 68 | swim(n); 69 | assert isMinHeap(); 70 | } 71 | 72 | public Key delMin() { 73 | if (isEmpty()) throw new NoSuchElementException("Priority queue underflow"); 74 | Key min = pq[1]; 75 | exch(1, n--); 76 | sink(1); 77 | pq[n+1] = null; 78 | if ((n > 0) && (n == (pq.length -1) / 4)) resize(pq.length / 2); 79 | assert isMinHeap(); 80 | return min; 81 | } 82 | 83 | private void swim(int k) { 84 | while (k > 1 && greater(k/2, k)) { 85 | exch(k, k/2); 86 | k = k/2; 87 | } 88 | } 89 | 90 | private void sink(int k) { 91 | while (2*k <= n) { 92 | int j = 2*k; 93 | if (j < n && greater(j, j+1)) j++; 94 | if (!greater(k, j)) break; 95 | exch(k, j); 96 | k = j; 97 | } 98 | } 99 | 100 | private boolean greater(int i, int j) { 101 | if (comparator == null) { 102 | return ((Comparable) pq[i]).compareTo(pq[j]) > 0; 103 | } else { 104 | return comparator.compare(pq[i], pq[j]) > 0; 105 | } 106 | } 107 | 108 | private void exch(int i, int j) { 109 | Key swap = pq[i]; 110 | pq[i] = pq[j]; 111 | pq[j] = swap; 112 | } 113 | 114 | private boolean isMinHeap() { 115 | return isMinHeap(1); 116 | } 117 | 118 | private boolean isMinHeap(int k) { 119 | if (k > n) return true; 120 | int left = 2*k; 121 | int right = 2*k + 1; 122 | if (left <= n && greater(k, left)) return false; 123 | if (right <= n && greater(k, right)) return false; 124 | return isMinHeap(left) && isMinHeap(right); 125 | } 126 | 127 | public Iterator iterator() { 128 | return new HeapIterator(); 129 | } 130 | 131 | private class HeapIterator implements Iterator { 132 | private MinPQ copy; 133 | 134 | public HeapIterator() { 135 | if (comparator == null) copy = new MinPQ(size()); 136 | else copy = new MinPQ(size(), comparator); 137 | for (int i = 1; i <= n; i++) 138 | copy.insert(pq[i]); 139 | } 140 | 141 | public boolean hasNext() { return !copy.isEmpty(); } 142 | public void remove() { throw new UnsupportedOperationException(); } 143 | 144 | public Key next() { 145 | if (!hasNext()) throw new NoSuchElementException(); 146 | return copy.delMin(); 147 | } 148 | } 149 | 150 | public static void main(String[] args) { 151 | MinPQ pq = new MinPQ(); 152 | while (!StdIn.isEmpty()) { 153 | String item = StdIn.readString(); 154 | if (!item.equals("-")) pq.insert(item); 155 | else if (!pq.isEmpty()) StdOut.print(pq.delMin() + " "); 156 | } 157 | StdOut.println("(" + pq.size() + " left on pq)"); 158 | for (String item : pq) { 159 | StdOut.println(item); 160 | } 161 | } 162 | } --------------------------------------------------------------------------------