question
stringlengths
34
5.67k
answer
stringlengths
20
20.1k
support_files
listlengths
0
4
metadata
dict
Add a method isFull() to /****************************************************************************** * Compilation: javac FixedCapacityStackOfStrings.java * Execution: java FixedCapacityStackOfStrings * Dependencies: StdIn.java StdOut.java * * Stack of strings implementation with a fixed-size array. * * % more tobe.txt * to be or not to - be - - that - - - is * * % java FixedCapacityStackOfStrings 5 < tobe.txt * to be not that or be * * Remark: bare-bones implementation. Does not do repeated * doubling or null out empty array entries to avoid loitering. * ******************************************************************************/ import java.util.Iterator; import java.util.NoSuchElementException; public class FixedCapacityStackOfStrings implements Iterable<String> { private String[] a; // holds the items private int n; // number of items in stack // create an empty stack with given capacity public FixedCapacityStackOfStrings(int capacity) { a = new String[capacity]; n = 0; } public boolean isEmpty() { return n == 0; } public boolean isFull() { return n == a.length; } public void push(String item) { a[n++] = item; } public String pop() { return a[--n]; } public String peek() { return a[n-1]; } public Iterator<String> iterator() { return new ReverseArrayIterator(); } // an array iterator, in reverse order public class ReverseArrayIterator implements Iterator<String> { private int i = n-1; public boolean hasNext() { return i >= 0; } public String next() { if (!hasNext()) throw new NoSuchElementException(); return a[i--]; } } public static void main(String[] args) { int max = Integer.parseInt(args[0]); FixedCapacityStackOfStrings stack = new FixedCapacityStackOfStrings(max); while (!StdIn.isEmpty()) { String item = StdIn.readString(); if (!item.equals("-")) stack.push(item); else if (stack.isEmpty()) StdOut.println("BAD INPUT"); else StdOut.print(stack.pop() + " "); } StdOut.println(); // print what's left on the stack StdOut.print("Left on stack: "); for (String s : stack) { StdOut.print(s + " "); } StdOut.println(); } }
/****************************************************************************** * Compilation: javac FixedCapacityStackOfStrings.java * Execution: java FixedCapacityStackOfStrings * Dependencies: StdIn.java StdOut.java * * Stack of strings implementation with a fixed-size array. * * % more tobe.txt * to be or not to - be - - that - - - is * * % java FixedCapacityStackOfStrings 5 < tobe.txt * to be not that or be * * Remark: bare-bones implementation. Does not do repeated * doubling or null out empty array entries to avoid loitering. * ******************************************************************************/ import java.util.Iterator; import java.util.NoSuchElementException; public class FixedCapacityStackOfStrings implements Iterable<String> { private String[] a; // holds the items private int n; // number of items in stack // create an empty stack with given capacity public FixedCapacityStackOfStrings(int capacity) { a = new String[capacity]; n = 0; } public boolean isEmpty() { return n == 0; } public boolean isFull() { return n == a.length; } public void push(String item) { a[n++] = item; } public String pop() { return a[--n]; } public String peek() { return a[n-1]; } public Iterator<String> iterator() { return new ReverseArrayIterator(); } // an array iterator, in reverse order public class ReverseArrayIterator implements Iterator<String> { private int i = n-1; public boolean hasNext() { return i >= 0; } public String next() { if (!hasNext()) throw new NoSuchElementException(); return a[i--]; } } public static void main(String[] args) { int max = Integer.parseInt(args[0]); FixedCapacityStackOfStrings stack = new FixedCapacityStackOfStrings(max); while (!StdIn.isEmpty()) { String item = StdIn.readString(); if (!item.equals("-")) stack.push(item); else if (stack.isEmpty()) StdOut.println("BAD INPUT"); else StdOut.print(stack.pop() + " "); } StdOut.println(); // print what's left on the stack StdOut.print("Left on stack: "); for (String s : stack) { StdOut.print(s + " "); } StdOut.println(); } }
[]
{ "number": "1.3.1", "code_execution": true, "url": "https://algs4.cs.princeton.edu/13stacks/FixedCapacityStackOfStrings.java", "params": [ "5 < tobe.txt" ], "dependencies": [ "StdIn.java", "StdOut.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Write a stack client Parentheses.java that reads in sequence of left and right parentheses, braces, and brackets from standard input and uses a stack to determine whether the sequence is properly balanced. For example, your program should print true for [()]{}{[()()]()} and false for [(]).
/****************************************************************************** * Compilation: javac Parentheses.java * Execution: java Parentheses * Dependencies: In.java Stack.java * * Reads in a text file and checks to see if the parentheses are balanced. * * % java Parentheses * [()]{}{[()()]()} * true * * % java Parentheses * [(]) * false * ******************************************************************************/ public class Parentheses { private static final char LEFT_PAREN = '('; private static final char RIGHT_PAREN = ')'; private static final char LEFT_BRACE = '{'; private static final char RIGHT_BRACE = '}'; private static final char LEFT_BRACKET = '['; private static final char RIGHT_BRACKET = ']'; public static boolean isBalanced(String s) { Stack<Character> stack = new Stack<Character>(); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == LEFT_PAREN) stack.push(LEFT_PAREN); if (s.charAt(i) == LEFT_BRACE) stack.push(LEFT_BRACE); if (s.charAt(i) == LEFT_BRACKET) stack.push(LEFT_BRACKET); if (s.charAt(i) == RIGHT_PAREN) { if (stack.isEmpty()) return false; if (stack.pop() != LEFT_PAREN) return false; } else if (s.charAt(i) == RIGHT_BRACE) { if (stack.isEmpty()) return false; if (stack.pop() != LEFT_BRACE) return false; } else if (s.charAt(i) == RIGHT_BRACKET) { if (stack.isEmpty()) return false; if (stack.pop() != LEFT_BRACKET) return false; } } return stack.isEmpty(); } public static void main(String[] args) { In in = new In(); String s = in.readAll().trim(); StdOut.println(isBalanced(s)); } }
[]
{ "number": "1.3.4", "code_execution": true, "url": "https://algs4.cs.princeton.edu/13stacks/Parentheses.java", "params": [ "<<< \"[(])\"", "<<< \"[()]{}{[()()]()}\"" ], "dependencies": [ "In.java", "Stack.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Add a method peek to '/****************************************************************************** * Compilation: javac Stack.java * Execution: java Stack < input.txt * Dependencies: StdIn.java StdOut.java * Data files: https://algs4.cs.princeton.edu/13stacks/tobe.txt * * A generic stack, implemented using a singly linked list. * Each stack element is of type Item. * * This version uses a static nested class Node (to save 8 bytes per * Node), whereas the version in the textbook uses a non-static nested * class (for simplicity). * * % more tobe.txt * to be or not to - be - - that - - - is * * % java Stack < tobe.txt * to be not that or be (2 left on stack) * ******************************************************************************/ import java.util.Iterator; import java.util.NoSuchElementException; /** * The {@code Stack} class represents a last-in-first-out (LIFO) stack of generic items. * It supports the usual <em>push</em> and <em>pop</em> operations, along with methods * for peeking at the top item, testing if the stack is empty, and iterating through * the items in LIFO order. * <p> * This implementation uses a singly linked list with a static nested class for * linked-list nodes. See {@link LinkedStack} for the version from the * textbook that uses a non-static nested class. * See {@link ResizingArrayStack} for a version that uses a resizing array. * The <em>push</em>, <em>pop</em>, <em>peek</em>, <em>size</em>, and <em>is-empty</em> * operations all take constant time in the worst case. * <p> * For additional documentation, * see <a href="https://algs4.cs.princeton.edu/13stacks">Section 1.3</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne * * @param <Item> the generic type each item in this stack */ public class Stack<Item> implements Iterable<Item> { private Node<Item> first; // top of stack private int n; // size of the stack // helper linked list class private static class Node<Item> { private Item item; private Node<Item> next; } /** * Initializes an empty stack. */ public Stack() { first = null; n = 0; } /** * Returns true if this stack is empty. * * @return true if this stack is empty; false otherwise */ public boolean isEmpty() { return first == null; } /** * Returns the number of items in this stack. * * @return the number of items in this stack */ public int size() { return n; } /** * Adds the item to this stack. * * @param item the item to add */ public void push(Item item) { Node<Item> oldfirst = first; first = new Node<Item>(); first.item = item; first.next = oldfirst; n++; } /** * Removes and returns the item most recently added to this stack. * * @return the item most recently added * @throws NoSuchElementException if this stack is empty */ public Item pop() { if (isEmpty()) throw new NoSuchElementException("Stack underflow"); Item item = first.item; // save item to return first = first.next; // delete first node n--; return item; // return the saved item } /** * Returns (but does not remove) the item most recently added to this stack. * * @return the item most recently added to this stack * @throws NoSuchElementException if this stack is empty */ public Item peek() { if (isEmpty()) throw new NoSuchElementException("Stack underflow"); return first.item; } /** * Returns a string representation of this stack. * * @return the sequence of items in this stack in LIFO order, separated by spaces */ public String toString() { StringBuilder s = new StringBuilder(); for (Item item : this) { s.append(item); s.append(' '); } return s.toString(); } /** * Returns an iterator to this stack that iterates through the items in LIFO order. * * @return an iterator to this stack that iterates through the items in LIFO order */ public Iterator<Item> iterator() { return new LinkedIterator(first); } // the iterator private class LinkedIterator implements Iterator<Item> { private Node<Item> current; public LinkedIterator(Node<Item> first) { current = first; } // is there a next item? public boolean hasNext() { return current != null; } // returns the next item public Item next() { if (!hasNext()) throw new NoSuchElementException(); Item item = current.item; current = current.next; return item; } } /** * Unit tests the {@code Stack} data type. * * @param args the command-line arguments */ public static void main(String[] args) { Stack<String> stack = new Stack<String>(); while (!StdIn.isEmpty()) { String item = StdIn.readString(); if (!item.equals("-")) stack.push(item); else if (!stack.isEmpty()) StdOut.print(stack.pop() + " "); } StdOut.println("(" + stack.size() + " left on stack)"); } } ' that returns the most recently inserted item on the stack (without popping it).
/****************************************************************************** * Compilation: javac Stack.java * Execution: java Stack < input.txt * Dependencies: StdIn.java StdOut.java * Data files: https://algs4.cs.princeton.edu/13stacks/tobe.txt * * A generic stack, implemented using a singly linked list. * Each stack element is of type Item. * * This version uses a static nested class Node (to save 8 bytes per * Node), whereas the version in the textbook uses a non-static nested * class (for simplicity). * * % more tobe.txt * to be or not to - be - - that - - - is * * % java Stack < tobe.txt * to be not that or be (2 left on stack) * ******************************************************************************/ import java.util.Iterator; import java.util.NoSuchElementException; /** * The {@code Stack} class represents a last-in-first-out (LIFO) stack of generic items. * It supports the usual <em>push</em> and <em>pop</em> operations, along with methods * for peeking at the top item, testing if the stack is empty, and iterating through * the items in LIFO order. * <p> * This implementation uses a singly linked list with a static nested class for * linked-list nodes. See {@link LinkedStack} for the version from the * textbook that uses a non-static nested class. * See {@link ResizingArrayStack} for a version that uses a resizing array. * The <em>push</em>, <em>pop</em>, <em>peek</em>, <em>size</em>, and <em>is-empty</em> * operations all take constant time in the worst case. * <p> * For additional documentation, * see <a href="https://algs4.cs.princeton.edu/13stacks">Section 1.3</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne * * @param <Item> the generic type each item in this stack */ public class Stack<Item> implements Iterable<Item> { private Node<Item> first; // top of stack private int n; // size of the stack // helper linked list class private static class Node<Item> { private Item item; private Node<Item> next; } /** * Initializes an empty stack. */ public Stack() { first = null; n = 0; } /** * Returns true if this stack is empty. * * @return true if this stack is empty; false otherwise */ public boolean isEmpty() { return first == null; } /** * Returns the number of items in this stack. * * @return the number of items in this stack */ public int size() { return n; } /** * Adds the item to this stack. * * @param item the item to add */ public void push(Item item) { Node<Item> oldfirst = first; first = new Node<Item>(); first.item = item; first.next = oldfirst; n++; } /** * Removes and returns the item most recently added to this stack. * * @return the item most recently added * @throws NoSuchElementException if this stack is empty */ public Item pop() { if (isEmpty()) throw new NoSuchElementException("Stack underflow"); Item item = first.item; // save item to return first = first.next; // delete first node n--; return item; // return the saved item } /** * Returns (but does not remove) the item most recently added to this stack. * * @return the item most recently added to this stack * @throws NoSuchElementException if this stack is empty */ public Item peek() { if (isEmpty()) throw new NoSuchElementException("Stack underflow"); return first.item; } /** * Returns a string representation of this stack. * * @return the sequence of items in this stack in LIFO order, separated by spaces */ public String toString() { StringBuilder s = new StringBuilder(); for (Item item : this) { s.append(item); s.append(' '); } return s.toString(); } /** * Returns an iterator to this stack that iterates through the items in LIFO order. * * @return an iterator to this stack that iterates through the items in LIFO order */ public Iterator<Item> iterator() { return new LinkedIterator(first); } // the iterator private class LinkedIterator implements Iterator<Item> { private Node<Item> current; public LinkedIterator(Node<Item> first) { current = first; } // is there a next item? public boolean hasNext() { return current != null; } // returns the next item public Item next() { if (!hasNext()) throw new NoSuchElementException(); Item item = current.item; current = current.next; return item; } } /** * Unit tests the {@code Stack} data type. * * @param args the command-line arguments */ public static void main(String[] args) { Stack<String> stack = new Stack<String>(); while (!StdIn.isEmpty()) { String item = StdIn.readString(); if (!item.equals("-")) stack.push(item); else if (!stack.isEmpty()) StdOut.print(stack.pop() + " "); } StdOut.println("(" + stack.size() + " left on stack)"); } }
[]
{ "number": "1.3.7", "code_execution": true, "url": "https://algs4.cs.princeton.edu/13stacks/Stack.java", "params": [ "< tobe.txt" ], "dependencies": [ "StdIn.java", "StdOut.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Write a filter Program InfixToPostfix.java that converts an arithmetic expression from infix to postfix.
/****************************************************************************** * Compilation: javac InfixToPostfix.java * Execution: java InfixToPostFix * Dependencies: Stack.java StdIn.java StdOut.java * * Reads in a fully parenthesized infix expression from standard input * and prints an equivalent postfix expression to standard output. * * Windows users: replace [Ctrl-d] with [Ctrl-z] to signify end of file. * * % java InfixToPostfix * ( 2 + ( ( 3 + 4 ) * ( 5 * 6 ) ) ) * [Ctrl-d] * 2 3 4 + 5 6 * * + * * % java InfixToPostfix * ( ( ( 5 + ( 7 * ( 1 + 1 ) ) ) * 3 ) + ( 2 * ( 1 + 1 ) ) ) * 5 7 1 1 + * + 3 * 2 1 1 + * + * * % java InfixToPostfix | java EvaluatePostfix * ( 2 + ( ( 3 + 4 ) * ( 5 * 6 ) ) ) * [Ctrl-d] * 212 * ******************************************************************************/ public class InfixToPostfix { public static void main(String[] args) { Stack<String> stack = new Stack<String>(); while (!StdIn.isEmpty()) { String s = StdIn.readString(); if (s.equals("+")) stack.push(s); else if (s.equals("*")) stack.push(s); else if (s.equals(")")) StdOut.print(stack.pop() + " "); else if (s.equals("(")) StdOut.print(""); else StdOut.print(s + " "); } StdOut.println(); } }
[]
{ "number": "1.3.10", "code_execution": true, "url": "https://algs4.cs.princeton.edu/13stacks/InfixToPostfix.java", "params": [ "<<EOF\n( 2 + ( ( 3 + 4 ) * ( 5 * 6 ) ) )\nEOF", "<<EOF\n( ( ( 5 + ( 7 * ( 1 + 1 ) ) ) * 3 ) + ( 2 * ( 1 + 1 ) ) )\nEOF" ], "dependencies": [ "Stack.java", "StdIn.java", "StdOut.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Write a program EvaluatePostfix.java that that takes a postfix expression from standard input, evaluates it, and prints the value.
/****************************************************************************** * Compilation: javac EvaluatePostfix.java * Execution: java EvaluatePostfix < file.txt * Dependencies: Stack.java StdIn.java StdOut.java * * Evaluates postfix expresions using a stack. * * Windows users: replace [Ctrl-d] with [Ctrl-z] to signify end of file. * * % java EvaluatePostfix * 3 4 5 + * * [Ctrl-d] * 27 * * % java EvaluatePostfix * 1 2 3 4 5 * + 6 * * + * [Ctrl-d] * 277 * * % java EvaluatePostfix * 7 16 16 16 * * * 5 16 16 * * 3 16 * 1 + + + * [Ctrl-d] * 30001 * * % java EvaluatePostfix * 7 16 * 5 + 16 * 3 + 16 * 1 + * [Ctrl-d] * 30001 * * Known bugs * ---------- * - No error checking - assumes input is legal postfix expression. * - All token must be separated by whitespace, e.g., 1 5+ is illegal. * ******************************************************************************/ public class EvaluatePostfix { public static void main(String[] args) { Stack<Integer> stack = new Stack<Integer>(); while (!StdIn.isEmpty()) { String s = StdIn.readString(); if (s.equals("+")) stack.push(stack.pop() + stack.pop()); else if (s.equals("*")) stack.push(stack.pop() * stack.pop()); else stack.push(Integer.parseInt(s)); } StdOut.println(stack.pop()); } }
[]
{ "number": "1.3.11", "code_execution": true, "url": "https://algs4.cs.princeton.edu/13stacks/EvaluatePostfix.java", "params": [ "<<EOF\n3 4 5 + *\nEOF", "<<EOF\n1 2 3 4 5 * + 6 * * +\nEOF", "<<EOF\n7 16 16 16 * * * 5 16 16 * * 3 16 * 1 + + +\nEOF", "<<EOF\n7 16 * 5 + 16 * 3 + 16 * 1 +\nEOF" ], "dependencies": [ "Stack.java", "StdIn.java", "StdOut.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Develop a class ResizingArrayQueueOfStrings that implements the queue abstraction with a fixed-size array, and then extend your implementation to use array resizing to remove the size restriction.
/****************************************************************************** * Compilation: javac ResizingArrayQueue.java * Execution: java ResizingArrayQueue < input.txt * Dependencies: StdIn.java StdOut.java * Data files: https://algs4.cs.princeton.edu/13stacks/tobe.txt * * Queue implementation with a resizing array. * * % java ResizingArrayQueue < tobe.txt * to be or not to be (2 left on queue) * ******************************************************************************/ import java.util.Iterator; import java.util.NoSuchElementException; /** * The {@code ResizingArrayQueue} class represents a first-in-first-out (FIFO) * queue of generic items. * It supports the usual <em>enqueue</em> and <em>dequeue</em> * operations, along with methods for peeking at the first item, * testing if the queue is empty, and iterating through * the items in FIFO order. * <p> * This implementation uses a resizing array, which double the underlying array * when it is full and halves the underlying array when it is one-quarter full. * The <em>enqueue</em> and <em>dequeue</em> operations take constant amortized time. * The <em>size</em>, <em>peek</em>, and <em>is-empty</em> operations takes * constant time in the worst case. * <p> * For additional documentation, see <a href="https://algs4.cs.princeton.edu/13stacks">Section 1.3</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class ResizingArrayQueue<Item> implements Iterable<Item> { // initial capacity of underlying resizing array private static final int INIT_CAPACITY = 8; private Item[] q; // queue elements private int n; // number of elements on queue private int first; // index of first element of queue private int last; // index of next available slot /** * Initializes an empty queue. */ public ResizingArrayQueue() { q = (Item[]) new Object[INIT_CAPACITY]; n = 0; first = 0; last = 0; } /** * Is this queue empty? * @return true if this queue is empty; false otherwise */ public boolean isEmpty() { return n == 0; } /** * Returns the number of items in this queue. * @return the number of items in this queue */ public int size() { return n; } // resize the underlying array private void resize(int capacity) { assert capacity >= n; Item[] copy = (Item[]) new Object[capacity]; for (int i = 0; i < n; i++) { copy[i] = q[(first + i) % q.length]; } q = copy; first = 0; last = n; } /** * Adds the item to this queue. * @param item the item to add */ public void enqueue(Item item) { // double size of array if necessary and recopy to front of array if (n == q.length) resize(2*q.length); // double size of array if necessary q[last++] = item; // add item if (last == q.length) last = 0; // wrap-around n++; } /** * Removes and returns the item on this queue that was least recently added. * @return the item on this queue that was least recently added * @throws java.util.NoSuchElementException if this queue is empty */ public Item dequeue() { if (isEmpty()) throw new NoSuchElementException("Queue underflow"); Item item = q[first]; q[first] = null; // to avoid loitering n--; first++; if (first == q.length) first = 0; // wrap-around // shrink size of array if necessary if (n > 0 && n == q.length/4) resize(q.length/2); return item; } /** * Returns the item least recently added to this queue. * @return the item least recently added to this queue * @throws java.util.NoSuchElementException if this queue is empty */ public Item peek() { if (isEmpty()) throw new NoSuchElementException("Queue underflow"); return q[first]; } /** * Returns an iterator that iterates over the items in this queue in FIFO order. * @return an iterator that iterates over the items in this queue in FIFO order */ public Iterator<Item> iterator() { return new ArrayIterator(); } // an array iterator, from first to last-1 private class ArrayIterator implements Iterator<Item> { private int i = 0; public boolean hasNext() { return i < n; } public Item next() { if (!hasNext()) throw new NoSuchElementException(); Item item = q[(i + first) % q.length]; i++; return item; } } /** * Unit tests the {@code ResizingArrayQueue} data type. * * @param args the command-line arguments */ public static void main(String[] args) { ResizingArrayQueue<String> queue = new ResizingArrayQueue<String>(); while (!StdIn.isEmpty()) { String item = StdIn.readString(); if (!item.equals("-")) queue.enqueue(item); else if (!queue.isEmpty()) StdOut.print(queue.dequeue() + " "); } StdOut.println("(" + queue.size() + " left on queue)"); } }
[]
{ "number": "1.3.14", "code_execution": true, "url": "https://algs4.cs.princeton.edu/13stacks/ResizingArrayQueue.java", "params": [ "< tobe.txt" ], "dependencies": [ "StdIn.java", "StdOut.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Josephus problem. In the Josephus problem from antiquity, N people are in dire straits and agree to the following strategy to reduce the population. They arrange themselves in a circle (at positions numbered from 0 to N-1) and proceed around the circle, eliminating every Mth person until only one person is left. Legend has it that Josephus figured out where to sit to avoid being eliminated. Write a Queue client Josephus.java that takes M and N from the command line and prints out the order in which people are eliminated (and thus would show Josephus where to sit in the circle). % java Josephus 2 7 1 3 5 0 4 2 6
/****************************************************************************** * Compilation: javac Josephus.java * Execution: java Josephus m n * Dependencies: Queue.java * * Solves the Josephus problem. * * % java Josephus 2 7 * 1 3 5 0 4 2 6 * ******************************************************************************/ public class Josephus { public static void main(String[] args) { int m = Integer.parseInt(args[0]); int n = Integer.parseInt(args[1]); // initialize the queue Queue<Integer> queue = new Queue<Integer>(); for (int i = 0; i < n; i++) queue.enqueue(i); while (!queue.isEmpty()) { for (int i = 0; i < m-1; i++) queue.enqueue(queue.dequeue()); StdOut.print(queue.dequeue() + " "); } StdOut.println(); } }
[]
{ "number": "1.3.37", "code_execution": true, "url": "https://algs4.cs.princeton.edu/13stacks/Josephus.java", "params": [ "2 7" ], "dependencies": [ "Queue.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Develop classes QuickUnionUF.java that implement quick-union.
/****************************************************************************** * Compilation: javac QuickUnionUF.java * Execution: java QuickUnionUF < input.txt * Dependencies: StdIn.java StdOut.java * Data files: https://algs4.cs.princeton.edu/15uf/tinyUF.txt * https://algs4.cs.princeton.edu/15uf/mediumUF.txt * https://algs4.cs.princeton.edu/15uf/largeUF.txt * * Quick-union algorithm. * ******************************************************************************/ /** * The {@code QuickUnionUF} class represents a <em>union–find data type</em> * (also known as the <em>disjoint-sets data type</em>). * It supports the classic <em>union</em> and <em>find</em> operations, * along with a <em>count</em> operation that returns the total number * of sets. * <p> * The union–find data type models a collection of sets containing * <em>n</em> elements, with each element in exactly one set. * The elements are named 0 through <em>n</em>–1. * Initially, there are <em>n</em> sets, with each element in its * own set. The <em>canonical element</em> of a set * (also known as the <em>root</em>, <em>identifier</em>, * <em>leader</em>, or <em>set representative</em>) * is one distinguished element in the set. Here is a summary of * the operations: * <ul> * <li><em>find</em>(<em>p</em>) returns the canonical element * of the set containing <em>p</em>. The <em>find</em> operation * returns the same value for two elements if and only if * they are in the same set. * <li><em>union</em>(<em>p</em>, <em>q</em>) merges the set * containing element <em>p</em> with the set containing * element <em>q</em>. That is, if <em>p</em> and <em>q</em> * are in different sets, replace these two sets * with a new set that is the union of the two. * <li><em>count</em>() returns the number of sets. * </ul> * <p> * The canonical element of a set can change only when the set * itself changes during a call to <em>union</em>&mdash;it cannot * change during a call to either <em>find</em> or <em>count</em>. * <p> * This implementation uses <em>quick union</em>. * The constructor takes &Theta;(<em>n</em>) time, where * <em>n</em> is the number of sites. * The <em>union</em> and <em>find</em> operations take * &Theta;(<em>n</em>) time in the worst case. * The <em>count</em> operation takes &Theta;(1) time. * <p> * For alternative implementations of the same API, see * {@link UF}, {@link QuickFindUF}, and {@link WeightedQuickUnionUF}. * For additional documentation, * see <a href="https://algs4.cs.princeton.edu/15uf">Section 1.5</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class QuickUnionUF { private int[] parent; // parent[i] = parent of i private int count; // number of components /** * Initializes an empty union-find data structure with * {@code n} elements {@code 0} through {@code n-1}. * Initially, each element is in its own set. * * @param n the number of elements * @throws IllegalArgumentException if {@code n < 0} */ public QuickUnionUF(int n) { parent = new int[n]; count = n; for (int i = 0; i < n; i++) { parent[i] = i; } } /** * Returns the number of sets. * * @return the number of sets (between {@code 1} and {@code n}) */ public int count() { return count; } /** * Returns the canonical element of the set containing element {@code p}. * * @param p an element * @return the canonical element of the set containing {@code p} * @throws IllegalArgumentException unless {@code 0 <= p < n} */ public int find(int p) { validate(p); while (p != parent[p]) p = parent[p]; return p; } // validate that p is a valid index private void validate(int p) { int n = parent.length; if (p < 0 || p >= n) { throw new IllegalArgumentException("index " + p + " is not between 0 and " + (n-1)); } } /** * Returns true if the two elements are in the same set. * * @param p one element * @param q the other element * @return {@code true} if {@code p} and {@code q} are in the same set; * {@code false} otherwise * @throws IllegalArgumentException unless * both {@code 0 <= p < n} and {@code 0 <= q < n} * @deprecated Replace with two calls to {@link #find(int)}. */ @Deprecated public boolean connected(int p, int q) { return find(p) == find(q); } /** * Merges the set containing element {@code p} with the set * containing element {@code q}. * * @param p one element * @param q the other element * @throws IllegalArgumentException unless * both {@code 0 <= p < n} and {@code 0 <= q < n} */ public void union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; parent[rootP] = rootQ; count--; } /** * Reads an integer {@code n} and a sequence of pairs of integers * (between {@code 0} and {@code n-1}) from standard input, where each integer * in the pair represents some element; * if the elements are in different sets, merge the two sets * and print the pair to standard output. * * @param args the command-line arguments */ public static void main(String[] args) { int n = StdIn.readInt(); QuickUnionUF uf = new QuickUnionUF(n); while (!StdIn.isEmpty()) { int p = StdIn.readInt(); int q = StdIn.readInt(); if (uf.find(p) == uf.find(q)) continue; uf.union(p, q); StdOut.println(p + " " + q); } StdOut.println(uf.count() + " components"); } }
[]
{ "number": "1.5.7", "code_execution": true, "url": "https://algs4.cs.princeton.edu/15uf/QuickUnionUF.java", "params": [ "< tinyUF.txt", "< mediumUF.txt" ], "dependencies": [ "StdIn.java", "StdOut.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Develop classes QuickFindUF.java that implement quick-find.
/****************************************************************************** * Compilation: javac QuickFindUF.java * Execution: java QuickFindUF < input.txt * Dependencies: StdIn.java StdOut.java * Data files: https://algs4.cs.princeton.edu/15uf/tinyUF.txt * https://algs4.cs.princeton.edu/15uf/mediumUF.txt * https://algs4.cs.princeton.edu/15uf/largeUF.txt * * Quick-find algorithm. * ******************************************************************************/ /** * The {@code QuickFindUF} class represents a <em>union–find data type</em> * (also known as the <em>disjoint-sets data type</em>). * It supports the classic <em>union</em> and <em>find</em> operations, * along with a <em>count</em> operation that returns the total number * of sets. * <p> * The union–find data type models a collection of sets containing * <em>n</em> elements, with each element in exactly one set. * The elements are named 0 through <em>n</em>–1. * Initially, there are <em>n</em> sets, with each element in its * own set. The <em>canonical element</em> of a set * (also known as the <em>root</em>, <em>identifier</em>, * <em>leader</em>, or <em>set representative</em>) * is one distinguished element in the set. Here is a summary of * the operations: * <ul> * <li><em>find</em>(<em>p</em>) returns the canonical element * of the set containing <em>p</em>. The <em>find</em> operation * returns the same value for two elements if and only if * they are in the same set. * <li><em>union</em>(<em>p</em>, <em>q</em>) merges the set * containing element <em>p</em> with the set containing * element <em>q</em>. That is, if <em>p</em> and <em>q</em> * are in different sets, replace these two sets * with a new set that is the union of the two. * <li><em>count</em>() returns the number of sets. * </ul> * <p> * The canonical element of a set can change only when the set * itself changes during a call to <em>union</em>&mdash;it cannot * change during a call to either <em>find</em> or <em>count</em>. * <p> * This implementation uses <em>quick find</em>. * The constructor takes &Theta;(<em>n</em>) time, where <em>n</em> * is the number of sites. * The <em>find</em>, <em>connected</em>, and <em>count</em> * operations take &Theta;(1) time; the <em>union</em> operation * takes &Theta;(<em>n</em>) time. * <p> * For alternative implementations of the same API, see * {@link UF}, {@link QuickUnionUF}, and {@link WeightedQuickUnionUF}. * For additional documentation, see * <a href="https://algs4.cs.princeton.edu/15uf">Section 1.5</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class QuickFindUF { private int[] id; // id[i] = component identifier of i private int count; // number of components /** * Initializes an empty union-find data structure with * {@code n} elements {@code 0} through {@code n-1}. * Initially, each element is in its own set. * * @param n the number of elements * @throws IllegalArgumentException if {@code n < 0} */ public QuickFindUF(int n) { count = n; id = new int[n]; for (int i = 0; i < n; i++) id[i] = i; } /** * Returns the number of sets. * * @return the number of sets (between {@code 1} and {@code n}) */ public int count() { return count; } /** * Returns the canonical element of the set containing element {@code p}. * * @param p an element * @return the canonical element of the set containing {@code p} * @throws IllegalArgumentException unless {@code 0 <= p < n} */ public int find(int p) { validate(p); return id[p]; } // validate that p is a valid index private void validate(int p) { int n = id.length; if (p < 0 || p >= n) { throw new IllegalArgumentException("index " + p + " is not between 0 and " + (n-1)); } } /** * Returns true if the two elements are in the same set. * * @param p one element * @param q the other element * @return {@code true} if {@code p} and {@code q} are in the same set; * {@code false} otherwise * @throws IllegalArgumentException unless * both {@code 0 <= p < n} and {@code 0 <= q < n} * @deprecated Replace with two calls to {@link #find(int)}. */ @Deprecated public boolean connected(int p, int q) { validate(p); validate(q); return id[p] == id[q]; } /** * Merges the set containing element {@code p} with the set * containing element {@code q}. * * @param p one element * @param q the other element * @throws IllegalArgumentException unless * both {@code 0 <= p < n} and {@code 0 <= q < n} */ public void union(int p, int q) { validate(p); validate(q); int pID = id[p]; // needed for correctness int qID = id[q]; // to reduce the number of array accesses // p and q are already in the same component if (pID == qID) return; for (int i = 0; i < id.length; i++) if (id[i] == pID) id[i] = qID; count--; } /** * Reads an integer {@code n} and a sequence of pairs of integers * (between {@code 0} and {@code n-1}) from standard input, where each integer * in the pair represents some element; * if the elements are in different sets, merge the two sets * and print the pair to standard output. * * @param args the command-line arguments */ public static void main(String[] args) { int n = StdIn.readInt(); QuickFindUF uf = new QuickFindUF(n); while (!StdIn.isEmpty()) { int p = StdIn.readInt(); int q = StdIn.readInt(); if (uf.find(p) == uf.find(q)) continue; uf.union(p, q); StdOut.println(p + " " + q); } StdOut.println(uf.count() + " components"); } }
[]
{ "number": "1.5.7", "code_execution": true, "url": "https://algs4.cs.princeton.edu/15uf/QuickFindUF.java", "params": [ "< tinyUF.txt", "< mediumUF.txt" ], "dependencies": [ "StdIn.java", "StdOut.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Transaction sort test client. Write a class SortTransactions.java that consists of a static method main() that reads a sequence of transactions from standard input, sorts them, and prints the result on standard output.
/****************************************************************************** * Compilation: javac SortTransactions.java * Execution: java SortTransactions < input.txt * Dependencies: StdOut.java * Data file: https://algs4.cs.princeton.edu/21elementary/tinyBatch.txt * * % java SortTransactions < transactions.txt * Turing 1/11/2002 66.10 * Knuth 6/14/1999 288.34 * Turing 6/17/1990 644.08 * Dijkstra 9/10/2000 708.95 * Dijkstra 11/18/1995 837.42 * Hoare 8/12/2003 1025.70 * Bellman 10/26/2007 1358.62 * Knuth 7/25/2008 1564.55 * Turing 2/11/1991 2156.86 * Tarjan 10/13/1993 2520.97 * Dijkstra 8/22/2007 2678.40 * Hoare 5/10/1993 3229.27 * Knuth 11/11/2008 3284.33 * Turing 10/12/1993 3532.36 * Hoare 2/10/2005 4050.20 * Tarjan 3/26/2002 4121.85 * Hoare 8/18/1992 4381.21 * Tarjan 1/11/1999 4409.74 * Tarjan 2/12/1994 4732.35 * Thompson 2/27/2000 4747.08 * ******************************************************************************/ import java.util.Arrays; public class SortTransactions { public static Transaction[] readTransactions() { Queue<Transaction> queue = new Queue<Transaction>(); while (StdIn.hasNextLine()) { String line = StdIn.readLine(); Transaction transaction = new Transaction(line); queue.enqueue(transaction); } int n = queue.size(); Transaction[] transactions = new Transaction[n]; for (int i = 0; i < n; i++) transactions[i] = queue.dequeue(); return transactions; } public static void main(String[] args) { Transaction[] transactions = readTransactions(); Arrays.sort(transactions); for (int i = 0; i < transactions.length; i++) StdOut.println(transactions[i]); } }
[]
{ "number": "2.1.22", "code_execution": true, "url": "https://algs4.cs.princeton.edu/21elementary/SortTransactions.java", "params": [ "< tinyBatch.txt" ], "dependencies": [ "StdOut.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Insertion sort with sentinel. Develop an implementation InsertionX.java of insertion sort that eliminates the j > 0 test in the inner loop by first putting the smallest item into position
/****************************************************************************** * Compilation: javac InsertionX.java * Execution: java InsertionX < input.txt * Dependencies: StdOut.java StdIn.java * Data files: https://algs4.cs.princeton.edu/21elementary/tiny.txt * https://algs4.cs.princeton.edu/21elementary/words3.txt * * Sorts a sequence of strings from standard input using an optimized * version of insertion sort that uses half exchanges instead of * full exchanges to reduce data movement.. * * % more tiny.txt * S O R T E X A M P L E * * % java InsertionX < tiny.txt * A E E L M O P R S T X [ one string per line ] * * % more words3.txt * bed bug dad yes zoo ... all bad yet * * % java InsertionX < words3.txt * all bad bed bug dad ... yes yet zoo [ one string per line ] * ******************************************************************************/ /** * The {@code InsertionX} class provides static methods for sorting * an array using an optimized version of insertion sort (with half exchanges * and a sentinel). * <p> * In the worst case, this implementation makes ~ 1/2 <em>n</em><sup>2</sup> * compares to sort an array of length <em>n</em>. * So, it is not suitable for sorting large arrays * (unless the number of inversions is small). * <p> * This sorting algorithm is stable. * It uses &Theta;(1) extra memory (not including the input array). * <p> * For additional documentation, see * <a href="https://algs4.cs.princeton.edu/21elementary">Section 2.1</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class InsertionX { // This class should not be instantiated. private InsertionX() { } /** * Rearranges the array in ascending order, using the natural order. * @param a the array to be sorted */ public static void sort(Comparable[] a) { int n = a.length; // put smallest element in position to serve as sentinel int exchanges = 0; for (int i = n-1; i > 0; i--) { if (less(a[i], a[i-1])) { exch(a, i, i-1); exchanges++; } } if (exchanges == 0) return; // insertion sort with half-exchanges for (int i = 2; i < n; i++) { Comparable v = a[i]; int j = i; while (less(v, a[j-1])) { a[j] = a[j-1]; j--; } a[j] = v; } assert isSorted(a); } /*************************************************************************** * Helper sorting functions. ***************************************************************************/ // is v < w ? private static boolean less(Comparable v, Comparable w) { return v.compareTo(w) < 0; } // exchange a[i] and a[j] private static void exch(Object[] a, int i, int j) { Object swap = a[i]; a[i] = a[j]; a[j] = swap; } /*************************************************************************** * Check if array is sorted - useful for debugging. ***************************************************************************/ private static boolean isSorted(Comparable[] a) { for (int i = 1; i < a.length; i++) if (less(a[i], a[i-1])) return false; return true; } // print array to standard output private static void show(Comparable[] a) { for (int i = 0; i < a.length; i++) { StdOut.println(a[i]); } } /** * Reads in a sequence of strings from standard input; insertion sorts them; * and prints them to standard output in ascending order. * * @param args the command-line arguments */ public static void main(String[] args) { String[] a = StdIn.readAllStrings(); InsertionX.sort(a); show(a); } }
[]
{ "number": "2.1.23", "code_execution": true, "url": "https://algs4.cs.princeton.edu/21elementary/InsertionX.java", "params": [ "< words3.txt", "< tiny.txt" ], "dependencies": [ "StdOut.java", "StdIn.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Insertion sort without exchanges. Develop an implementation InsertionX.java of insertion sort that moves larger items to the right one position rather than doing full exchanges.
/****************************************************************************** * Compilation: javac InsertionX.java * Execution: java InsertionX < input.txt * Dependencies: StdOut.java StdIn.java * Data files: https://algs4.cs.princeton.edu/21elementary/tiny.txt * https://algs4.cs.princeton.edu/21elementary/words3.txt * * Sorts a sequence of strings from standard input using an optimized * version of insertion sort that uses half exchanges instead of * full exchanges to reduce data movement.. * * % more tiny.txt * S O R T E X A M P L E * * % java InsertionX < tiny.txt * A E E L M O P R S T X [ one string per line ] * * % more words3.txt * bed bug dad yes zoo ... all bad yet * * % java InsertionX < words3.txt * all bad bed bug dad ... yes yet zoo [ one string per line ] * ******************************************************************************/ /** * The {@code InsertionX} class provides static methods for sorting * an array using an optimized version of insertion sort (with half exchanges * and a sentinel). * <p> * In the worst case, this implementation makes ~ 1/2 <em>n</em><sup>2</sup> * compares to sort an array of length <em>n</em>. * So, it is not suitable for sorting large arrays * (unless the number of inversions is small). * <p> * This sorting algorithm is stable. * It uses &Theta;(1) extra memory (not including the input array). * <p> * For additional documentation, see * <a href="https://algs4.cs.princeton.edu/21elementary">Section 2.1</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class InsertionX { // This class should not be instantiated. private InsertionX() { } /** * Rearranges the array in ascending order, using the natural order. * @param a the array to be sorted */ public static void sort(Comparable[] a) { int n = a.length; // put smallest element in position to serve as sentinel int exchanges = 0; for (int i = n-1; i > 0; i--) { if (less(a[i], a[i-1])) { exch(a, i, i-1); exchanges++; } } if (exchanges == 0) return; // insertion sort with half-exchanges for (int i = 2; i < n; i++) { Comparable v = a[i]; int j = i; while (less(v, a[j-1])) { a[j] = a[j-1]; j--; } a[j] = v; } assert isSorted(a); } /*************************************************************************** * Helper sorting functions. ***************************************************************************/ // is v < w ? private static boolean less(Comparable v, Comparable w) { return v.compareTo(w) < 0; } // exchange a[i] and a[j] private static void exch(Object[] a, int i, int j) { Object swap = a[i]; a[i] = a[j]; a[j] = swap; } /*************************************************************************** * Check if array is sorted - useful for debugging. ***************************************************************************/ private static boolean isSorted(Comparable[] a) { for (int i = 1; i < a.length; i++) if (less(a[i], a[i-1])) return false; return true; } // print array to standard output private static void show(Comparable[] a) { for (int i = 0; i < a.length; i++) { StdOut.println(a[i]); } } /** * Reads in a sequence of strings from standard input; insertion sorts them; * and prints them to standard output in ascending order. * * @param args the command-line arguments */ public static void main(String[] args) { String[] a = StdIn.readAllStrings(); InsertionX.sort(a); show(a); } }
[]
{ "number": "2.1.24", "code_execution": true, "url": "https://algs4.cs.princeton.edu/21elementary/InsertionX.java", "params": [ "< words3.txt", "< tiny.txt" ], "dependencies": [ "StdOut.java", "StdIn.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Use of a static array like aux[] is inadvisable in library software because multiple clients might use the class concurrently. Give an implementation of Merge.java that does not use a static array.
/****************************************************************************** * Compilation: javac Merge.java * Execution: java Merge < input.txt * Dependencies: StdOut.java StdIn.java * Data files: https://algs4.cs.princeton.edu/22mergesort/tiny.txt * https://algs4.cs.princeton.edu/22mergesort/words3.txt * * Sorts a sequence of strings from standard input using mergesort. * * % more tiny.txt * S O R T E X A M P L E * * % java Merge < tiny.txt * A E E L M O P R S T X [ one string per line ] * * % more words3.txt * bed bug dad yes zoo ... all bad yet * * % java Merge < words3.txt * all bad bed bug dad ... yes yet zoo [ one string per line ] * ******************************************************************************/ /** * The {@code Merge} class provides static methods for sorting an * array using a top-down, recursive version of <em>mergesort</em>. * <p> * This implementation takes &Theta;(<em>n</em> log <em>n</em>) time * to sort any array of length <em>n</em> (assuming comparisons * take constant time). It makes between * ~ &frac12; <em>n</em> log<sub>2</sub> <em>n</em> and * ~ 1 <em>n</em> log<sub>2</sub> <em>n</em> compares. * <p> * This sorting algorithm is stable. * It uses &Theta;(<em>n</em>) extra memory (not including the input array). * <p> * For additional documentation, see * <a href="https://algs4.cs.princeton.edu/22mergesort">Section 2.2</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * For an optimized version, see {@link MergeX}. * * @author Robert Sedgewick * @author Kevin Wayne */ public class Merge { // This class should not be instantiated. private Merge() { } // stably merge a[lo .. mid] with a[mid+1 ..hi] using aux[lo .. hi] private static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) { // precondition: a[lo .. mid] and a[mid+1 .. hi] are sorted subarrays assert isSorted(a, lo, mid); assert isSorted(a, mid+1, hi); // copy to aux[] for (int k = lo; k <= hi; k++) { aux[k] = a[k]; } // merge back to a[] int i = lo, j = mid+1; for (int k = lo; k <= hi; k++) { if (i > mid) a[k] = aux[j++]; else if (j > hi) a[k] = aux[i++]; else if (less(aux[j], aux[i])) a[k] = aux[j++]; else a[k] = aux[i++]; } // postcondition: a[lo .. hi] is sorted assert isSorted(a, lo, hi); } // mergesort a[lo..hi] using auxiliary array aux[lo..hi] private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) { if (hi <= lo) return; int mid = lo + (hi - lo) / 2; sort(a, aux, lo, mid); sort(a, aux, mid + 1, hi); merge(a, aux, lo, mid, hi); } /** * Rearranges the array in ascending order, using the natural order. * @param a the array to be sorted */ public static void sort(Comparable[] a) { Comparable[] aux = new Comparable[a.length]; sort(a, aux, 0, a.length-1); assert isSorted(a); } /*************************************************************************** * Helper sorting function. ***************************************************************************/ // is v < w ? private static boolean less(Comparable v, Comparable w) { return v.compareTo(w) < 0; } /*************************************************************************** * Check if array is sorted - useful for debugging. ***************************************************************************/ private static boolean isSorted(Comparable[] a) { return isSorted(a, 0, a.length - 1); } private static boolean isSorted(Comparable[] a, int lo, int hi) { for (int i = lo + 1; i <= hi; i++) if (less(a[i], a[i-1])) return false; return true; } /*************************************************************************** * Index mergesort. ***************************************************************************/ // stably merge a[lo .. mid] with a[mid+1 .. hi] using aux[lo .. hi] private static void merge(Comparable[] a, int[] index, int[] aux, int lo, int mid, int hi) { // copy to aux[] for (int k = lo; k <= hi; k++) { aux[k] = index[k]; } // merge back to a[] int i = lo, j = mid+1; for (int k = lo; k <= hi; k++) { if (i > mid) index[k] = aux[j++]; else if (j > hi) index[k] = aux[i++]; else if (less(a[aux[j]], a[aux[i]])) index[k] = aux[j++]; else index[k] = aux[i++]; } } /** * Returns a permutation that gives the elements in the array in ascending order. * @param a the array * @return a permutation {@code p[]} such that {@code a[p[0]]}, {@code a[p[1]]}, * ..., {@code a[p[n-1]]} are in ascending order */ public static int[] indexSort(Comparable[] a) { int n = a.length; int[] index = new int[n]; for (int i = 0; i < n; i++) index[i] = i; int[] aux = new int[n]; sort(a, index, aux, 0, n-1); return index; } // mergesort a[lo..hi] using auxiliary array aux[lo..hi] private static void sort(Comparable[] a, int[] index, int[] aux, int lo, int hi) { if (hi <= lo) return; int mid = lo + (hi - lo) / 2; sort(a, index, aux, lo, mid); sort(a, index, aux, mid + 1, hi); merge(a, index, aux, lo, mid, hi); } // print array to standard output private static void show(Comparable[] a) { for (int i = 0; i < a.length; i++) { StdOut.println(a[i]); } } /** * Reads in a sequence of strings from standard input; mergesorts them; * and prints them to standard output in ascending order. * * @param args the command-line arguments */ public static void main(String[] args) { String[] a = StdIn.readAllStrings(); Merge.sort(a); show(a); } }
[]
{ "number": "2.2.9", "code_execution": true, "url": "https://algs4.cs.princeton.edu/22mergesort/Merge.java", "params": [ "< tiny.txt", "< words3.txt" ], "dependencies": [ "StdOut.java", "StdIn.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Improvements. Write a program MergeX.java that implements the three improvements to mergesort that are described in the text: add a cutoff from small subarrays, test whether the array is already in order, and avoid the copy by switching arguments in the recursive code
/****************************************************************************** * Compilation: javac MergeX.java * Execution: java MergeX < input.txt * Dependencies: StdOut.java StdIn.java * Data files: https://algs4.cs.princeton.edu/22mergesort/tiny.txt * https://algs4.cs.princeton.edu/22mergesort/words3.txt * * Sorts a sequence of strings from standard input using an * optimized version of mergesort. * * % more tiny.txt * S O R T E X A M P L E * * % java MergeX < tiny.txt * A E E L M O P R S T X [ one string per line ] * * % more words3.txt * bed bug dad yes zoo ... all bad yet * * % java MergeX < words3.txt * all bad bed bug dad ... yes yet zoo [ one string per line ] * ******************************************************************************/ import java.util.Comparator; /** * The {@code MergeX} class provides static methods for sorting an * array using an optimized version of mergesort. * <p> * In the worst case, this implementation takes * &Theta;(<em>n</em> log <em>n</em>) time to sort an array of * length <em>n</em> (assuming comparisons take constant time). * <p> * This sorting algorithm is stable. * It uses &Theta;(<em>n</em>) extra memory (not including the input array). * <p> * For additional documentation, see * <a href="https://algs4.cs.princeton.edu/22mergesort">Section 2.2</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class MergeX { private static final int CUTOFF = 7; // cutoff to insertion sort // This class should not be instantiated. private MergeX() { } private static void merge(Comparable[] src, Comparable[] dst, int lo, int mid, int hi) { // precondition: src[lo .. mid] and src[mid+1 .. hi] are sorted subarrays assert isSorted(src, lo, mid); assert isSorted(src, mid+1, hi); int i = lo, j = mid+1; for (int k = lo; k <= hi; k++) { if (i > mid) dst[k] = src[j++]; else if (j > hi) dst[k] = src[i++]; else if (less(src[j], src[i])) dst[k] = src[j++]; // to ensure stability else dst[k] = src[i++]; } // postcondition: dst[lo .. hi] is sorted subarray assert isSorted(dst, lo, hi); } private static void sort(Comparable[] src, Comparable[] dst, int lo, int hi) { // if (hi <= lo) return; if (hi <= lo + CUTOFF) { insertionSort(dst, lo, hi); return; } int mid = lo + (hi - lo) / 2; sort(dst, src, lo, mid); sort(dst, src, mid+1, hi); // if (!less(src[mid+1], src[mid])) { // for (int i = lo; i <= hi; i++) dst[i] = src[i]; // return; // } // using System.arraycopy() is a bit faster than the above loop if (!less(src[mid+1], src[mid])) { System.arraycopy(src, lo, dst, lo, hi - lo + 1); return; } merge(src, dst, lo, mid, hi); } /** * Rearranges the array in ascending order, using the natural order. * @param a the array to be sorted */ public static void sort(Comparable[] a) { Comparable[] aux = a.clone(); sort(aux, a, 0, a.length-1); assert isSorted(a); } // sort from a[lo] to a[hi] using insertion sort private static void insertionSort(Comparable[] a, int lo, int hi) { for (int i = lo; i <= hi; i++) for (int j = i; j > lo && less(a[j], a[j-1]); j--) exch(a, j, j-1); } /******************************************************************* * Utility methods. *******************************************************************/ // exchange a[i] and a[j] private static void exch(Object[] a, int i, int j) { Object swap = a[i]; a[i] = a[j]; a[j] = swap; } // is a[i] < a[j]? private static boolean less(Comparable a, Comparable b) { return a.compareTo(b) < 0; } // is a[i] < a[j]? private static boolean less(Object a, Object b, Comparator comparator) { return comparator.compare(a, b) < 0; } /******************************************************************* * Version that takes Comparator as argument. *******************************************************************/ /** * Rearranges the array in ascending order, using the provided order. * * @param a the array to be sorted * @param comparator the comparator that defines the total order */ public static void sort(Object[] a, Comparator comparator) { Object[] aux = a.clone(); sort(aux, a, 0, a.length-1, comparator); assert isSorted(a, comparator); } private static void merge(Object[] src, Object[] dst, int lo, int mid, int hi, Comparator comparator) { // precondition: src[lo .. mid] and src[mid+1 .. hi] are sorted subarrays assert isSorted(src, lo, mid, comparator); assert isSorted(src, mid+1, hi, comparator); int i = lo, j = mid+1; for (int k = lo; k <= hi; k++) { if (i > mid) dst[k] = src[j++]; else if (j > hi) dst[k] = src[i++]; else if (less(src[j], src[i], comparator)) dst[k] = src[j++]; else dst[k] = src[i++]; } // postcondition: dst[lo .. hi] is sorted subarray assert isSorted(dst, lo, hi, comparator); } private static void sort(Object[] src, Object[] dst, int lo, int hi, Comparator comparator) { // if (hi <= lo) return; if (hi <= lo + CUTOFF) { insertionSort(dst, lo, hi, comparator); return; } int mid = lo + (hi - lo) / 2; sort(dst, src, lo, mid, comparator); sort(dst, src, mid+1, hi, comparator); // using System.arraycopy() is a bit faster than the above loop if (!less(src[mid+1], src[mid], comparator)) { System.arraycopy(src, lo, dst, lo, hi - lo + 1); return; } merge(src, dst, lo, mid, hi, comparator); } // sort from a[lo] to a[hi] using insertion sort private static void insertionSort(Object[] a, int lo, int hi, Comparator comparator) { for (int i = lo; i <= hi; i++) for (int j = i; j > lo && less(a[j], a[j-1], comparator); j--) exch(a, j, j-1); } /*************************************************************************** * Check if array is sorted - useful for debugging. ***************************************************************************/ private static boolean isSorted(Comparable[] a) { return isSorted(a, 0, a.length - 1); } private static boolean isSorted(Comparable[] a, int lo, int hi) { for (int i = lo + 1; i <= hi; i++) if (less(a[i], a[i-1])) return false; return true; } private static boolean isSorted(Object[] a, Comparator comparator) { return isSorted(a, 0, a.length - 1, comparator); } private static boolean isSorted(Object[] a, int lo, int hi, Comparator comparator) { for (int i = lo + 1; i <= hi; i++) if (less(a[i], a[i-1], comparator)) return false; return true; } // print array to standard output private static void show(Object[] a) { for (int i = 0; i < a.length; i++) { StdOut.println(a[i]); } } /** * Reads in a sequence of strings from standard input; mergesorts them * (using an optimized version of mergesort); * and prints them to standard output in ascending order. * * @param args the command-line arguments */ public static void main(String[] args) { String[] a = StdIn.readAllStrings(); MergeX.sort(a); show(a); } }
[]
{ "number": "2.2.11", "code_execution": true, "url": "https://algs4.cs.princeton.edu/22mergesort/MergeX.java", "params": [ "< tiny.txt", "< words3.txt" ], "dependencies": [ "StdOut.java", "StdIn.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Inversions. Develop and implement a linearithmic algorithm Inversions.java for computing the number of inversions in a given array (the number of exchanges that would be performed by insertion sort for that array—see Section 2.1). This quantity is related to the Kendall tau distance
/****************************************************************************** * Compilation: javac Inversions.java * Execution: java Inversions < input.txt * Dependencies: StdIn.java StdOut.java * * Read array of n integers and count number of inversions in n log n time. * ******************************************************************************/ /** * The {@code Inversions} class provides static methods to count the * number of <em>inversions</em> in either an array of integers or comparables. * An inversion in an array {@code a[]} is a pair of indicies {@code i} and * {@code j} such that {@code i < j} and {@code a[i] > a[j]}. * <p> * This implementation uses a generalization of mergesort. The <em>count</em> * operation takes &Theta;(<em>n</em> log <em>n</em>) time to count the * number of inversions in any array of length <em>n</em> (assuming * comparisons take constant time). * <p> * For additional documentation, see * <a href="https://algs4.cs.princeton.edu/22mergesort">Section 2.2</a> * of <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class Inversions { // do not instantiate private Inversions() { } // merge and count private static long merge(int[] a, int[] aux, int lo, int mid, int hi) { long inversions = 0; // copy to aux[] for (int k = lo; k <= hi; k++) { aux[k] = a[k]; } // merge back to a[] int i = lo, j = mid+1; for (int k = lo; k <= hi; k++) { if (i > mid) a[k] = aux[j++]; else if (j > hi) a[k] = aux[i++]; else if (aux[j] < aux[i]) { a[k] = aux[j++]; inversions += (mid - i + 1); } else a[k] = aux[i++]; } return inversions; } // return the number of inversions in the subarray b[lo..hi] // side effect b[lo..hi] is rearranged in ascending order private static long count(int[] a, int[] b, int[] aux, int lo, int hi) { long inversions = 0; if (hi <= lo) return 0; int mid = lo + (hi - lo) / 2; inversions += count(a, b, aux, lo, mid); inversions += count(a, b, aux, mid+1, hi); inversions += merge(b, aux, lo, mid, hi); assert inversions == brute(a, lo, hi); return inversions; } /** * Returns the number of inversions in the integer array. * The argument array is not modified. * @param a the array * @return the number of inversions in the array. An inversion is a pair of * indicies {@code i} and {@code j} such that {@code i < j} * and {@code a[i] > a[j]}. */ public static long count(int[] a) { int[] b = new int[a.length]; int[] aux = new int[a.length]; for (int i = 0; i < a.length; i++) b[i] = a[i]; long inversions = count(a, b, aux, 0, a.length - 1); return inversions; } // merge and count (Comparable version) private static <Key extends Comparable<Key>> long merge(Key[] a, Key[] aux, int lo, int mid, int hi) { long inversions = 0; // copy to aux[] for (int k = lo; k <= hi; k++) { aux[k] = a[k]; } // merge back to a[] int i = lo, j = mid+1; for (int k = lo; k <= hi; k++) { if (i > mid) a[k] = aux[j++]; else if (j > hi) a[k] = aux[i++]; else if (less(aux[j], aux[i])) { a[k] = aux[j++]; inversions += (mid - i + 1); } else a[k] = aux[i++]; } return inversions; } // return the number of inversions in the subarray b[lo..hi] // side effect b[lo..hi] is rearranged in ascending order private static <Key extends Comparable<Key>> long count(Key[] a, Key[] b, Key[] aux, int lo, int hi) { long inversions = 0; if (hi <= lo) return 0; int mid = lo + (hi - lo) / 2; inversions += count(a, b, aux, lo, mid); inversions += count(a, b, aux, mid+1, hi); inversions += merge(b, aux, lo, mid, hi); assert inversions == brute(a, lo, hi); return inversions; } /** * Returns the number of inversions in the comparable array. * The argument array is not modified. * @param a the array * @param <Key> the inferred type of the elements in the array * @return the number of inversions in the array. An inversion is a pair of * indicies {@code i} and {@code j} such that {@code i < j} * and {@code a[i].compareTo(a[j]) > 0}. */ public static <Key extends Comparable<Key>> long count(Key[] a) { Key[] b = a.clone(); Key[] aux = a.clone(); long inversions = count(a, b, aux, 0, a.length - 1); return inversions; } // is v < w ? private static <Key extends Comparable<Key>> boolean less(Key v, Key w) { return (v.compareTo(w) < 0); } // count number of inversions in a[lo..hi] via brute force (for debugging only) private static <Key extends Comparable<Key>> long brute(Key[] a, int lo, int hi) { long inversions = 0; for (int i = lo; i <= hi; i++) for (int j = i + 1; j <= hi; j++) if (less(a[j], a[i])) inversions++; return inversions; } // count number of inversions in a[lo..hi] via brute force (for debugging only) private static long brute(int[] a, int lo, int hi) { long inversions = 0; for (int i = lo; i <= hi; i++) for (int j = i + 1; j <= hi; j++) if (a[j] < a[i]) inversions++; return inversions; } /** * Reads a sequence of integers from standard input and * prints the number of inversions to standard output. * * @param args the command-line arguments */ public static void main(String[] args) { int[] a = StdIn.readAllInts(); int n = a.length; Integer[] b = new Integer[n]; for (int i = 0; i < n; i++) b[i] = a[i]; StdOut.println(Inversions.count(a)); StdOut.println(Inversions.count(b)); } }
[]
{ "number": "2.2.19", "code_execution": true, "url": "https://algs4.cs.princeton.edu/22mergesort/Inversions.java", "params": [ "< 1Kints.txt", "< 2Kints.txt", "< 4Kints.txt", "< 8Kints.txt", "< 16Kints.txt", "< 32Kints.txt" ], "dependencies": [ "StdIn.java", "StdOut.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Index sort. Develop a version of Merge.java that does not rearrange the array, but returns an int[] perm such that perm[i] is the index of the ith smallest entry in the array.
/****************************************************************************** * Compilation: javac Merge.java * Execution: java Merge < input.txt * Dependencies: StdOut.java StdIn.java * Data files: https://algs4.cs.princeton.edu/22mergesort/tiny.txt * https://algs4.cs.princeton.edu/22mergesort/words3.txt * * Sorts a sequence of strings from standard input using mergesort. * * % more tiny.txt * S O R T E X A M P L E * * % java Merge < tiny.txt * A E E L M O P R S T X [ one string per line ] * * % more words3.txt * bed bug dad yes zoo ... all bad yet * * % java Merge < words3.txt * all bad bed bug dad ... yes yet zoo [ one string per line ] * ******************************************************************************/ /** * The {@code Merge} class provides static methods for sorting an * array using a top-down, recursive version of <em>mergesort</em>. * <p> * This implementation takes &Theta;(<em>n</em> log <em>n</em>) time * to sort any array of length <em>n</em> (assuming comparisons * take constant time). It makes between * ~ &frac12; <em>n</em> log<sub>2</sub> <em>n</em> and * ~ 1 <em>n</em> log<sub>2</sub> <em>n</em> compares. * <p> * This sorting algorithm is stable. * It uses &Theta;(<em>n</em>) extra memory (not including the input array). * <p> * For additional documentation, see * <a href="https://algs4.cs.princeton.edu/22mergesort">Section 2.2</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * For an optimized version, see {@link MergeX}. * * @author Robert Sedgewick * @author Kevin Wayne */ public class Merge { // This class should not be instantiated. private Merge() { } // stably merge a[lo .. mid] with a[mid+1 ..hi] using aux[lo .. hi] private static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) { // precondition: a[lo .. mid] and a[mid+1 .. hi] are sorted subarrays assert isSorted(a, lo, mid); assert isSorted(a, mid+1, hi); // copy to aux[] for (int k = lo; k <= hi; k++) { aux[k] = a[k]; } // merge back to a[] int i = lo, j = mid+1; for (int k = lo; k <= hi; k++) { if (i > mid) a[k] = aux[j++]; else if (j > hi) a[k] = aux[i++]; else if (less(aux[j], aux[i])) a[k] = aux[j++]; else a[k] = aux[i++]; } // postcondition: a[lo .. hi] is sorted assert isSorted(a, lo, hi); } // mergesort a[lo..hi] using auxiliary array aux[lo..hi] private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) { if (hi <= lo) return; int mid = lo + (hi - lo) / 2; sort(a, aux, lo, mid); sort(a, aux, mid + 1, hi); merge(a, aux, lo, mid, hi); } /** * Rearranges the array in ascending order, using the natural order. * @param a the array to be sorted */ public static void sort(Comparable[] a) { Comparable[] aux = new Comparable[a.length]; sort(a, aux, 0, a.length-1); assert isSorted(a); } /*************************************************************************** * Helper sorting function. ***************************************************************************/ // is v < w ? private static boolean less(Comparable v, Comparable w) { return v.compareTo(w) < 0; } /*************************************************************************** * Check if array is sorted - useful for debugging. ***************************************************************************/ private static boolean isSorted(Comparable[] a) { return isSorted(a, 0, a.length - 1); } private static boolean isSorted(Comparable[] a, int lo, int hi) { for (int i = lo + 1; i <= hi; i++) if (less(a[i], a[i-1])) return false; return true; } /*************************************************************************** * Index mergesort. ***************************************************************************/ // stably merge a[lo .. mid] with a[mid+1 .. hi] using aux[lo .. hi] private static void merge(Comparable[] a, int[] index, int[] aux, int lo, int mid, int hi) { // copy to aux[] for (int k = lo; k <= hi; k++) { aux[k] = index[k]; } // merge back to a[] int i = lo, j = mid+1; for (int k = lo; k <= hi; k++) { if (i > mid) index[k] = aux[j++]; else if (j > hi) index[k] = aux[i++]; else if (less(a[aux[j]], a[aux[i]])) index[k] = aux[j++]; else index[k] = aux[i++]; } } /** * Returns a permutation that gives the elements in the array in ascending order. * @param a the array * @return a permutation {@code p[]} such that {@code a[p[0]]}, {@code a[p[1]]}, * ..., {@code a[p[n-1]]} are in ascending order */ public static int[] indexSort(Comparable[] a) { int n = a.length; int[] index = new int[n]; for (int i = 0; i < n; i++) index[i] = i; int[] aux = new int[n]; sort(a, index, aux, 0, n-1); return index; } // mergesort a[lo..hi] using auxiliary array aux[lo..hi] private static void sort(Comparable[] a, int[] index, int[] aux, int lo, int hi) { if (hi <= lo) return; int mid = lo + (hi - lo) / 2; sort(a, index, aux, lo, mid); sort(a, index, aux, mid + 1, hi); merge(a, index, aux, lo, mid, hi); } // print array to standard output private static void show(Comparable[] a) { for (int i = 0; i < a.length; i++) { StdOut.println(a[i]); } } /** * Reads in a sequence of strings from standard input; mergesorts them; * and prints them to standard output in ascending order. * * @param args the command-line arguments */ public static void main(String[] args) { String[] a = StdIn.readAllStrings(); Merge.sort(a); show(a); } }
[]
{ "number": "2.2.20", "code_execution": true, "url": "https://algs4.cs.princeton.edu/22mergesort/Merge.java", "params": [ "< tiny.txt", "< words3.txt" ], "dependencies": [ "StdOut.java", "StdIn.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Write a program Sort2distinct.java that sorts an array that is known to contain just two distinct key values.
/****************************************************************************** * Compilation: javac Sort2distinct.java * Execution: java Sort2distinct binary-string * Dependencies: StdOut.java * * Partitions the array of specified as the command-line. * Assumes there are at most 2 distinct elements. * ******************************************************************************/ public class Sort2distinct { // rearranges a[] in ascending order assuming a[] has at most 3 distinct values public static void sort(Comparable[] a) { int lt = 0, gt = a.length - 1; int i = 0; while (i <= gt) { int cmp = a[i].compareTo(a[lt]); if (cmp < 0) exch(a, lt++, i++); else if (cmp > 0) exch(a, i, gt--); else i++; } } // exchange a[i] and a[j] private static void exch(Comparable[] a, int i, int j) { Comparable swap = a[i]; a[i] = a[j]; a[j] = swap; } // test client public static void main(String[] args) { // parse command-line argument as an array of 1-character strings String s = args[0]; int n = s.length(); String[] a = new String[n]; for (int i = 0; i < n; i++) a[i] = s.substring(i, i+1); // sort a print results sort(a); for (int i = 0; i < n; i++) StdOut.print(a[i]); StdOut.println(); } }
[]
{ "number": "2.3.5", "code_execution": true, "url": "https://algs4.cs.princeton.edu/23quicksort/Sort2distinct.java", "params": [ "01001111011100111011011101001100", "10110111001101111100001011011011", "10110100010000111011000111110000", "01110100010010011010011111001001", "11000101001001011100011011010111" ], "dependencies": [ "StdOut.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Best case. Write a program QuickBest.java that produces a best-case array (with no duplicates) for Quick.sort(): an array of N distinct keys with the property that every partition will produce subarrays that differ in size by at most 1 (the same subarray sizes that would happen for an array of N equal keys). For the purposes of this exercise, ignore the initial shuffle.
/****************************************************************************** * Compilation: javac QuickBest.java * Execution: java QuickBest n * Dependencies: StdOut.java * * Generate a best-case input of size n for standard quicksort. * * % java QuickBest 3 * BAC * * % java QuickBest 7 * DACBFEG * * % java QuickBest 15 * HACBFEGDLIKJNMO * ******************************************************************************/ public class QuickBest { // postcondition: a[lo..hi] is best-case input for quicksorting that subarray private static void best(int[] a, int lo, int hi) { // precondition: a[lo..hi] contains keys lo to hi, in order for (int i = lo; i <= hi; i++) assert a[i] == i; if (hi <= lo) return; int mid = lo + (hi - lo) / 2; best(a, lo, mid-1); best(a, mid+1, hi); exch(a, lo, mid); } public static int[] best(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = i; best(a, 0, n-1); return a; } // exchange a[i] and a[j] private static void exch(int[] a, int i, int j) { int swap = a[i]; a[i] = a[j]; a[j] = swap; } public static void main(String[] args) { String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; int n = Integer.parseInt(args[0]); int[] a = best(n); for (int i = 0; i < n; i++) // StdOut.println(a[i]); StdOut.print(alphabet.charAt(a[i])); StdOut.println(); } }
[]
{ "number": "2.3.16", "code_execution": true, "url": "https://algs4.cs.princeton.edu/23quicksort/QuickBest.java", "params": [ "3", "7", "15" ], "dependencies": [ "StdOut.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Fast three-way partitioning. (J. Bentley and D. McIlroy). Implement an entropy-optimal sort QuickBentleyMcIlroy.java based on keeping equal keys at both the left and right ends of the subarray. Maintain indices p and q such that a[lo..p-1] that a[q+1..hi] are all equal to a[lo], an index i such that a[p..i-1] are all less than a[lo] and an index j such that a[j+1..q] are all greater than a[lo]. Add to the inner partitioning loop code to swap a[i] with a[p] (and increment p) if it is equal to v and to swap a[j] with a[q] (and decrement q) if it is equal to v before the usual comparisons of a[i] and a[j] with v. After the partitioning loop has terminated, add code to swap the equal keys into position
/****************************************************************************** * Compilation: javac QuickX.java * Execution: java QuickX < input.txt * Dependencies: StdOut.java StdIn.java * Data files: https://algs4.cs.princeton.edu/23quicksort/tiny.txt * https://algs4.cs.princeton.edu/23quicksort/words3.txt * * Uses the Hoare's 2-way partitioning scheme, chooses the partitioning * element using median-of-3, and cuts off to insertion sort. * ******************************************************************************/ /** * The {@code QuickX} class provides static methods for sorting an array * using an optimized version of quicksort (using Hoare's 2-way partitioning * algorithm, median-of-3 to choose the partitioning element, and cutoff * to insertion sort). * <p> * For additional documentation, see * <a href="https://algs4.cs.princeton.edu/23quicksort">Section 2.3</a> * of <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class QuickX { // cutoff to insertion sort, must be >= 1 private static final int INSERTION_SORT_CUTOFF = 8; // This class should not be instantiated. private QuickX() { } /** * Rearranges the array in ascending order, using the natural order. * @param a the array to be sorted */ public static void sort(Comparable[] a) { // StdRandom.shuffle(a); sort(a, 0, a.length - 1); assert isSorted(a); } // quicksort the subarray from a[lo] to a[hi] private static void sort(Comparable[] a, int lo, int hi) { if (hi <= lo) return; // cutoff to insertion sort (Insertion.sort() uses half-open intervals) int n = hi - lo + 1; if (n <= INSERTION_SORT_CUTOFF) { Insertion.sort(a, lo, hi + 1); return; } int j = partition(a, lo, hi); sort(a, lo, j-1); sort(a, j+1, hi); } // partition the subarray a[lo..hi] so that a[lo..j-1] <= a[j] <= a[j+1..hi] // and return the index j. private static int partition(Comparable[] a, int lo, int hi) { int n = hi - lo + 1; int m = median3(a, lo, lo + n/2, hi); exch(a, m, lo); int i = lo; int j = hi + 1; Comparable v = a[lo]; // a[lo] is unique largest element while (less(a[++i], v)) { if (i == hi) { exch(a, lo, hi); return hi; } } // a[lo] is unique smallest element while (less(v, a[--j])) { if (j == lo + 1) return lo; } // the main loop while (i < j) { exch(a, i, j); while (less(a[++i], v)) ; while (less(v, a[--j])) ; } // put partitioning item v at a[j] exch(a, lo, j); // now, a[lo .. j-1] <= a[j] <= a[j+1 .. hi] return j; } // return the index of the median element among a[i], a[j], and a[k] private static int median3(Comparable[] a, int i, int j, int k) { return (less(a[i], a[j]) ? (less(a[j], a[k]) ? j : less(a[i], a[k]) ? k : i) : (less(a[k], a[j]) ? j : less(a[k], a[i]) ? k : i)); } /*************************************************************************** * Helper sorting functions. ***************************************************************************/ // is v < w ? private static boolean less(Comparable v, Comparable w) { return v.compareTo(w) < 0; } // exchange a[i] and a[j] private static void exch(Object[] a, int i, int j) { Object swap = a[i]; a[i] = a[j]; a[j] = swap; } /*************************************************************************** * Check if array is sorted - useful for debugging. ***************************************************************************/ private static boolean isSorted(Comparable[] a) { for (int i = 1; i < a.length; i++) if (less(a[i], a[i-1])) return false; return true; } // print array to standard output private static void show(Comparable[] a) { for (int i = 0; i < a.length; i++) { StdOut.println(a[i]); } } /** * Reads in a sequence of strings from standard input; quicksorts them * (using an optimized version of 2-way quicksort); * and prints them to standard output in ascending order. * * @param args the command-line arguments */ public static void main(String[] args) { String[] a = StdIn.readAllStrings(); QuickX.sort(a); assert isSorted(a); show(a); } }
[]
{ "number": "2.3.22", "code_execution": true, "url": "https://algs4.cs.princeton.edu/23quicksort/QuickX.java", "params": [ "< tiny.txt", "< words3.txt" ], "dependencies": [ "StdOut.java", "StdIn.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Design a linear-time certification algorithm to check whether an array pq[] is a min-oriented heap.
/****************************************************************************** * Compilation: javac MaxPQ.java * Execution: java MaxPQ < input.txt * Dependencies: StdIn.java StdOut.java * Data files: https://algs4.cs.princeton.edu/24pq/tinyPQ.txt * * Generic max priority queue implementation with a binary heap. * Can be used with a comparator instead of the natural order, * but the generic Key type must still be Comparable. * * % java MaxPQ < tinyPQ.txt * Q X P (6 left on pq) * * We use a one-based array to simplify parent and child calculations. * * Can be optimized by replacing full exchanges with half exchanges * (ala insertion sort). * ******************************************************************************/ import java.util.Comparator; import java.util.Iterator; import java.util.NoSuchElementException; /** * The {@code MaxPQ} class represents a priority queue of generic keys. * It supports the usual <em>insert</em> and <em>delete-the-maximum</em> * operations, along with methods for peeking at the maximum key, * testing if the priority queue is empty, and iterating through * the keys. * <p> * This implementation uses a <em>binary heap</em>. * The <em>insert</em> and <em>delete-the-maximum</em> operations take * &Theta;(log <em>n</em>) amortized time, where <em>n</em> is the number * of elements in the priority queue. This is an amortized bound * (and not a worst-case bound) because of array resizing operations. * The <em>min</em>, <em>size</em>, and <em>is-empty</em> operations take * &Theta;(1) time in the worst case. * Construction takes time proportional to the specified capacity or the * number of items used to initialize the data structure. * <p> * For additional documentation, see * <a href="https://algs4.cs.princeton.edu/24pq">Section 2.4</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne * * @param <Key> the generic type of key on this priority queue */ public class MaxPQ<Key> implements Iterable<Key> { private Key[] pq; // store items at indices 1 to n private int n; // number of items on priority queue private Comparator<Key> comparator; // optional comparator /** * Initializes an empty priority queue with the given initial capacity. * * @param initCapacity the initial capacity of this priority queue */ public MaxPQ(int initCapacity) { pq = (Key[]) new Object[initCapacity + 1]; n = 0; } /** * Initializes an empty priority queue. */ public MaxPQ() { this(1); } /** * Initializes an empty priority queue with the given initial capacity, * using the given comparator. * * @param initCapacity the initial capacity of this priority queue * @param comparator the order in which to compare the keys */ public MaxPQ(int initCapacity, Comparator<Key> comparator) { this.comparator = comparator; pq = (Key[]) new Object[initCapacity + 1]; n = 0; } /** * Initializes an empty priority queue using the given comparator. * * @param comparator the order in which to compare the keys */ public MaxPQ(Comparator<Key> comparator) { this(1, comparator); } /** * Initializes a priority queue from the array of keys. * Takes time proportional to the number of keys, using sink-based heap construction. * * @param keys the array of keys */ public MaxPQ(Key[] keys) { n = keys.length; pq = (Key[]) new Object[keys.length + 1]; for (int i = 0; i < n; i++) pq[i+1] = keys[i]; for (int k = n/2; k >= 1; k--) sink(k); assert isMaxHeap(); } /** * Returns true if this priority queue is empty. * * @return {@code true} if this priority queue is empty; * {@code false} otherwise */ public boolean isEmpty() { return n == 0; } /** * Returns the number of keys on this priority queue. * * @return the number of keys on this priority queue */ public int size() { return n; } /** * Returns a largest key on this priority queue. * * @return a largest key on this priority queue * @throws NoSuchElementException if this priority queue is empty */ public Key max() { if (isEmpty()) throw new NoSuchElementException("Priority queue underflow"); return pq[1]; } // resize the underlying array to have the given capacity private void resize(int capacity) { assert capacity > n; Key[] temp = (Key[]) new Object[capacity]; for (int i = 1; i <= n; i++) { temp[i] = pq[i]; } pq = temp; } /** * Adds a new key to this priority queue. * * @param x the new key to add to this priority queue */ public void insert(Key x) { // double size of array if necessary if (n == pq.length - 1) resize(2 * pq.length); // add x, and percolate it up to maintain heap invariant pq[++n] = x; swim(n); assert isMaxHeap(); } /** * Removes and returns a largest key on this priority queue. * * @return a largest key on this priority queue * @throws NoSuchElementException if this priority queue is empty */ public Key delMax() { if (isEmpty()) throw new NoSuchElementException("Priority queue underflow"); Key max = pq[1]; exch(1, n--); sink(1); pq[n+1] = null; // to avoid loitering and help with garbage collection if ((n > 0) && (n == (pq.length - 1) / 4)) resize(pq.length / 2); assert isMaxHeap(); return max; } /*************************************************************************** * Helper functions to restore the heap invariant. ***************************************************************************/ private void swim(int k) { while (k > 1 && less(k/2, k)) { exch(k/2, k); k = k/2; } } private void sink(int k) { while (2*k <= n) { int j = 2*k; if (j < n && less(j, j+1)) j++; if (!less(k, j)) break; exch(k, j); k = j; } } /*************************************************************************** * Helper functions for compares and swaps. ***************************************************************************/ private boolean less(int i, int j) { if (comparator == null) { return ((Comparable<Key>) pq[i]).compareTo(pq[j]) < 0; } else { return comparator.compare(pq[i], pq[j]) < 0; } } private void exch(int i, int j) { Key swap = pq[i]; pq[i] = pq[j]; pq[j] = swap; } // is pq[1..n] a max heap? private boolean isMaxHeap() { for (int i = 1; i <= n; i++) { if (pq[i] == null) return false; } for (int i = n+1; i < pq.length; i++) { if (pq[i] != null) return false; } if (pq[0] != null) return false; return isMaxHeapOrdered(1); } // is subtree of pq[1..n] rooted at k a max heap? private boolean isMaxHeapOrdered(int k) { if (k > n) return true; int left = 2*k; int right = 2*k + 1; if (left <= n && less(k, left)) return false; if (right <= n && less(k, right)) return false; return isMaxHeapOrdered(left) && isMaxHeapOrdered(right); } /*************************************************************************** * Iterator. ***************************************************************************/ /** * Returns an iterator that iterates over the keys on this priority queue * in descending order. * The iterator doesn't implement {@code remove()} since it's optional. * * @return an iterator that iterates over the keys in descending order */ public Iterator<Key> iterator() { return new HeapIterator(); } private class HeapIterator implements Iterator<Key> { // create a new pq private MaxPQ<Key> copy; // add all items to copy of heap // takes linear time since already in heap order so no keys move public HeapIterator() { if (comparator == null) copy = new MaxPQ<Key>(size()); else copy = new MaxPQ<Key>(size(), comparator); for (int i = 1; i <= n; i++) copy.insert(pq[i]); } public boolean hasNext() { return !copy.isEmpty(); } public void remove() { throw new UnsupportedOperationException(); } public Key next() { if (!hasNext()) throw new NoSuchElementException(); return copy.delMax(); } } /** * Unit tests the {@code MaxPQ} data type. * * @param args the command-line arguments */ public static void main(String[] args) { MaxPQ<String> pq = new MaxPQ<String>(); while (!StdIn.isEmpty()) { String item = StdIn.readString(); if (!item.equals("-")) pq.insert(item); else if (!pq.isEmpty()) StdOut.print(pq.delMax() + " "); } StdOut.println("(" + pq.size() + " left on pq)"); } }
[]
{ "number": "2.4.15", "code_execution": true, "url": "https://algs4.cs.princeton.edu/24pq/MaxPQ.java", "params": [ "< tinyPQ.txt" ], "dependencies": [ "StdIn.java", "StdOut.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Computational number theory. Write a program CubeSum.java that prints out all integers of the form \(a^3 + b^3\) where \(a\) and \(b\) are integers between 0 and \(n<\) in sorted order, without using excessive space. That is, instead of computing an array of the \(n^2\) sums and sorting them, build a minimum-oriented priority queue, initially containing \((0^3, 0, 0), (1^3 + 1^3, 1, 1), (2^3 + 2^3, 2, 2), \ldots, (n^3 + n^3, n, n)\). Then, while the priority queue is nonempty, remove the smallest item \(i^3 + j^3,\; i, \; j)\), print it, and then, if \(j < n\), insert the item \((i^3 + (j+1)^3,\; i,\; j+1)\). Use this program to find all distinct integers \(a, b, c\), and \(d\) between 0 and \(10^6\) such that \(a^3 + b^3 = c^3 + d^3\), such as \(1729 = 9^3 + 10^3 = 1^3 + 12^3\).
/****************************************************************************** * Compilation: javac CubeSum.java * Execution: java CubeSum n * Dependencies: MinPQ.java * * Print out integers of the form a^3 + b^3 in sorted order, where * 0 <= a <= b <= n. * * % java CubeSum 12 * 0 = 0^3 + 0^3 * 1 = 0^3 + 1^3 * 2 = 1^3 + 1^3 * 8 = 0^3 + 2^3 * 9 = 1^3 + 2^3 * ... * 1729 = 9^3 + 10^3 * 1729 = 1^3 + 12^3 * ... * 3456 = 12^3 + 12^3 * * Remarks * ------- * - Easily extends to handle sums of the form f(a) + g(b) * - Prints out a sum more than once if it can be obtained * in more than one way, e.g., 1729 = 9^3 + 10^3 = 1^3 + 12^3 * ******************************************************************************/ public class CubeSum implements Comparable<CubeSum> { private final int sum; private final int i; private final int j; public CubeSum(int i, int j) { this.sum = i*i*i + j*j*j; this.i = i; this.j = j; } public int compareTo(CubeSum that) { if (this.sum < that.sum) return -1; if (this.sum > that.sum) return +1; return 0; } public String toString() { return sum + " = " + i + "^3" + " + " + j + "^3"; } public static void main(String[] args) { int n = Integer.parseInt(args[0]); // initialize priority queue MinPQ<CubeSum> pq = new MinPQ<CubeSum>(); for (int i = 0; i <= n; i++) { pq.insert(new CubeSum(i, i)); } // find smallest sum, print it out, and update while (!pq.isEmpty()) { CubeSum s = pq.delMin(); StdOut.println(s); if (s.j < n) pq.insert(new CubeSum(s.i, s.j + 1)); } } }
[]
{ "number": "2.4.25", "code_execution": true, "url": "https://algs4.cs.princeton.edu/24pq/CubeSum.java", "params": [ "4", "12" ], "dependencies": [ "MinPQ.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Interval 1D data type. Write three static comparators for Interval1D.java, one that compares intervals by their left endpoing, one that compares intervals by their right endpoint, and one that compares intervals by their length.
/****************************************************************************** * Compilation: javac Insertion.java * Execution: java Insertion < input.txt * Dependencies: StdOut.java StdIn.java * Data files: https://algs4.cs.princeton.edu/21elementary/tiny.txt * https://algs4.cs.princeton.edu/21elementary/words3.txt * * Sorts a sequence of strings from standard input using insertion sort. * * % more tiny.txt * S O R T E X A M P L E * * % java Insertion < tiny.txt * A E E L M O P R S T X [ one string per line ] * * % more words3.txt * bed bug dad yes zoo ... all bad yet * * % java Insertion < words3.txt * all bad bed bug dad ... yes yet zoo [ one string per line ] * ******************************************************************************/ import java.util.Comparator; /** * The {@code Insertion} class provides static methods for sorting an * array using insertion sort. * <p> * In the worst case, this implementation makes ~ &frac12; <em>n</em><sup>2</sup> * compares and ~ &frac12; <em>n</em><sup>2</sup> exchanges to sort an array * of length <em>n</em>. So, it is not suitable for sorting large arbitrary * arrays. More precisely, the number of exchanges is exactly equal to the * number of inversions. So, for example, it sorts a partially-sorted array * in linear time. * <p> * This sorting algorithm is stable. * It uses &Theta;(1) extra memory (not including the input array). * <p> * See <a href="https://algs4.cs.princeton.edu/21elementary/InsertionPedantic.java.html">InsertionPedantic.java</a> * for a version that eliminates the compiler warning. * <p> * For additional documentation, see <a href="https://algs4.cs.princeton.edu/21elementary">Section 2.1</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class Insertion { // This class should not be instantiated. private Insertion() { } /** * Rearranges the array in ascending order, using the natural order. * @param a the array to be sorted */ public static void sort(Comparable[] a) { int n = a.length; for (int i = 1; i < n; i++) { for (int j = i; j > 0 && less(a[j], a[j-1]); j--) { exch(a, j, j-1); } assert isSorted(a, 0, i); } assert isSorted(a); } /** * Rearranges the subarray a[lo..hi) in ascending order, using the natural order. * @param a the array to be sorted * @param lo left endpoint (inclusive) * @param hi right endpoint (exclusive) */ public static void sort(Comparable[] a, int lo, int hi) { for (int i = lo + 1; i < hi; i++) { for (int j = i; j > lo && less(a[j], a[j-1]); j--) { exch(a, j, j-1); } } assert isSorted(a, lo, hi); } /** * Rearranges the array in ascending order, using a comparator. * @param a the array * @param comparator the comparator specifying the order */ public static void sort(Object[] a, Comparator comparator) { int n = a.length; for (int i = 1; i < n; i++) { for (int j = i; j > 0 && less(a[j], a[j-1], comparator); j--) { exch(a, j, j-1); } assert isSorted(a, 0, i, comparator); } assert isSorted(a, comparator); } /** * Rearranges the subarray a[lo..hi) in ascending order, using a comparator. * @param a the array * @param lo left endpoint (inclusive) * @param hi right endpoint (exclusive) * @param comparator the comparator specifying the order */ public static void sort(Object[] a, int lo, int hi, Comparator comparator) { for (int i = lo + 1; i < hi; i++) { for (int j = i; j > lo && less(a[j], a[j-1], comparator); j--) { exch(a, j, j-1); } } assert isSorted(a, lo, hi, comparator); } // return a permutation that gives the elements in a[] in ascending order // do not change the original array a[] /** * Returns a permutation that gives the elements in the array in ascending order. * @param a the array * @return a permutation {@code p[]} such that {@code a[p[0]]}, {@code a[p[1]]}, * ..., {@code a[p[n-1]]} are in ascending order */ public static int[] indexSort(Comparable[] a) { int n = a.length; int[] index = new int[n]; for (int i = 0; i < n; i++) index[i] = i; for (int i = 1; i < n; i++) for (int j = i; j > 0 && less(a[index[j]], a[index[j-1]]); j--) exch(index, j, j-1); return index; } /*************************************************************************** * Helper sorting functions. ***************************************************************************/ // is v < w ? private static boolean less(Comparable v, Comparable w) { return v.compareTo(w) < 0; } // is v < w ? private static boolean less(Object v, Object w, Comparator comparator) { return comparator.compare(v, w) < 0; } // exchange a[i] and a[j] private static void exch(Object[] a, int i, int j) { Object swap = a[i]; a[i] = a[j]; a[j] = swap; } // exchange a[i] and a[j] (for indirect sort) private static void exch(int[] a, int i, int j) { int swap = a[i]; a[i] = a[j]; a[j] = swap; } /*************************************************************************** * Check if array is sorted - useful for debugging. ***************************************************************************/ private static boolean isSorted(Comparable[] a) { return isSorted(a, 0, a.length); } // is the array a[lo..hi) sorted private static boolean isSorted(Comparable[] a, int lo, int hi) { for (int i = lo + 1; i < hi; i++) if (less(a[i], a[i-1])) return false; return true; } private static boolean isSorted(Object[] a, Comparator comparator) { return isSorted(a, 0, a.length, comparator); } // is the array a[lo..hi) sorted private static boolean isSorted(Object[] a, int lo, int hi, Comparator comparator) { for (int i = lo + 1; i < hi; i++) if (less(a[i], a[i-1], comparator)) return false; return true; } // print array to standard output private static void show(Comparable[] a) { for (int i = 0; i < a.length; i++) { StdOut.println(a[i]); } } /** * Reads in a sequence of strings from standard input; insertion sorts them; * and prints them to standard output in ascending order. * * @param args the command-line arguments */ public static void main(String[] args) { String[] a = StdIn.readAllStrings(); Insertion.sort(a); show(a); } }
[ "https://algs4.cs.princeton.edu/21elementary/words3.txt", "https://algs4.cs.princeton.edu/21elementary/tiny.txt" ]
{ "number": "2.5.27", "code_execution": true, "url": "https://algs4.cs.princeton.edu/25applications/Insertion.java", "params": [ "< tiny.txt", "< words3.txt" ], "dependencies": [ "StdOut.java", "StdIn.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Sort files by name. Write a program FileSorter.java that takes the name of a directory as a command line input and prints out all of the files in the current directory, sorted by filename. Hint: use the java.io.File data type.
/****************************************************************************** * Compilation: javac FileSorter.java * Execution: java FileSorter directory-name * Dependencies: StdOut.java * * Prints out all of the files in the given directory in * sorted order. * * % java FileSorter . * ******************************************************************************/ import java.io.File; import java.util.Arrays; public class FileSorter { public static void main(String[] args) { File directory = new File(args[0]); // root directory if (!directory.exists()) { StdOut.println(args[0] + " does not exist"); return; } if (!directory.isDirectory()) { StdOut.println(args[0] + " is not a directory"); return; } File[] files = directory.listFiles(); if (files == null) { StdOut.println("could not read files"); return; } Arrays.sort(files); for (int i = 0; i < files.length; i++) StdOut.println(files[i].getName()); } }
[]
{ "number": "2.5.28", "code_execution": true, "url": "https://algs4.cs.princeton.edu/25applications/FileSorter.java", "params": [ "java FileSorter ." ], "dependencies": [ "StdOut.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Write a client program GPA.java that creates a symbol table mapping letter grades to numerical scores, as in the table below, then reads from standard input a list of letter grades and computes and prints the GPA (the average of the numerical scores of the corresponding grades). A+ A A- B+ B B- C+ C C- D F 4.33 4.00 3.67 3.33 3.00 2.67 2.33 2.00 1.67 1.00 0.00
/****************************************************************************** * Compilation: javac GPA.java * Execution: java GPA < input.txt * Dependencies: ST.java * * Create a symbol table mapping letter grades to numerical * scores, then read a list of letter grades from standard input, * and print the GPA. * * % java GPA * A- B+ B+ B- * GPA = 3.25 * ******************************************************************************/ public class GPA { public static void main(String[] args) { // create symbol table of grades and values ST<String, Double> grades = new ST<String, Double>(); grades.put("A", 4.00); grades.put("B", 3.00); grades.put("C", 2.00); grades.put("D", 1.00); grades.put("F", 0.00); grades.put("A+", 4.33); grades.put("B+", 3.33); grades.put("C+", 2.33); grades.put("A-", 3.67); grades.put("B-", 2.67); // read grades from standard input and compute gpa int n = 0; double total = 0.0; for (n = 0; !StdIn.isEmpty(); n++) { String grade = StdIn.readString(); double value = grades.get(grade); total += value; } double gpa = total / n; StdOut.println("GPA = " + gpa); } }
[]
{ "number": "3.1.1", "code_execution": true, "url": "https://algs4.cs.princeton.edu/31elementary/GPA.java", "params": [ "<<EOF\nA- B+ B+ B-\nEOF" ], "dependencies": [ "ST.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Develop a symbol-table implementation ArrayST.java that uses an (unordered) array as the underlying data structure to implement our basic symbol table API.
/****************************************************************************** * Compilation: javac ArrayST.java * Execution: java ArrayST < input.txt * Dependencies: StdIn.java StdOut.java * Data files: https://algs4.cs.princeton.edu/31elementary/tinyST.txt * * * Symbol table implementation with unordered array. Uses repeated * doubling to resize the array. * * % java ArrayST < tinyST.txt * S 0 * H 5 * X 7 * R 3 * C 4 * L 11 * A 8 * M 9 * P 10 * E 12 * ******************************************************************************/ public class ArrayST<Key, Value> { private static final int INIT_SIZE = 8; private Value[] vals; // symbol table values private Key[] keys; // symbol table keys private int n = 0; // number of elements in symbol table public ArrayST() { keys = (Key[]) new Object[INIT_SIZE]; vals = (Value[]) new Object[INIT_SIZE]; } // return the number of key-value pairs in the symbol table public int size() { return n; } // is the symbol table empty? public boolean isEmpty() { return size() == 0; } // resize the parallel arrays to the given capacity private void resize(int capacity) { Key[] tempk = (Key[]) new Object[capacity]; Value[] tempv = (Value[]) new Object[capacity]; for (int i = 0; i < n; i++) tempk[i] = keys[i]; for (int i = 0; i < n; i++) tempv[i] = vals[i]; keys = tempk; vals = tempv; } // insert the key-value pair into the symbol table public void put(Key key, Value val) { // to deal with duplicates delete(key); // double size of arrays if necessary if (n >= vals.length) resize(2*n); // add new key and value at the end of array vals[n] = val; keys[n] = key; n++; } public Value get(Key key) { for (int i = 0; i < n; i++) if (keys[i].equals(key)) return vals[i]; return null; } public Iterable<Key> keys() { Queue<Key> queue = new Queue<Key>(); for (int i = 0; i < n; i++) queue.enqueue(keys[i]); return queue; } // remove given key (and associated value) public void delete(Key key) { for (int i = 0; i < n; i++) { if (key.equals(keys[i])) { keys[i] = keys[n-1]; vals[i] = vals[n-1]; keys[n-1] = null; vals[n-1] = null; n--; if (n > 0 && n == keys.length/4) resize(keys.length/2); return; } } } /*************************************************************************** * Test routine. ***************************************************************************/ public static void main(String[] args) { ArrayST<String, Integer> st = new ArrayST<String, Integer>(); for (int i = 0; !StdIn.isEmpty(); i++) { String key = StdIn.readString(); st.put(key, i); } for (String s : st.keys()) StdOut.println(s + " " + st.get(s)); } }
[ "https://algs4.cs.princeton.edu/31elementary/tinyST.txt" ]
{ "number": "3.1.2", "code_execution": true, "url": "https://algs4.cs.princeton.edu/31elementary/ArrayST.java", "params": [ "< tinyST.txt" ], "dependencies": [ "StdIn.java", "StdOut.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Implement size(), delete(), and keys() for SequentialSearchST.java.
/****************************************************************************** * Compilation: javac SequentialSearchST.java * Execution: java SequentialSearchST * Dependencies: StdIn.java StdOut.java * Data files: https://algs4.cs.princeton.edu/31elementary/tinyST.txt * * Symbol table implementation with sequential search in an * unordered linked list of key-value pairs. * * % more tinyST.txt * S E A R C H E X A M P L E * * % java SequentialSearchST < tinyST.txt * L 11 * P 10 * M 9 * X 7 * H 5 * C 4 * R 3 * A 8 * E 12 * S 0 * ******************************************************************************/ /** * The {@code SequentialSearchST} class represents an (unordered) * symbol table of generic key-value pairs. * It supports the usual <em>put</em>, <em>get</em>, <em>contains</em>, * <em>delete</em>, <em>size</em>, and <em>is-empty</em> methods. * It also provides a <em>keys</em> method for iterating over all of the keys. * A symbol table implements the <em>associative array</em> abstraction: * when associating a value with a key that is already in the symbol table, * the convention is to replace the old value with the new value. * The class also uses the convention that values cannot be {@code null}. Setting the * value associated with a key to {@code null} is equivalent to deleting the key * from the symbol table. * <p> * It relies on the {@code equals()} method to test whether two keys * are equal. It does not call either the {@code compareTo()} or * {@code hashCode()} method. * <p> * This implementation uses a <em>singly linked list</em> and * <em>sequential search</em>. * The <em>put</em> and <em>delete</em> operations take &Theta;(<em>n</em>). * The <em>get</em> and <em>contains</em> operations takes &Theta;(<em>n</em>) * time in the worst case. * The <em>size</em>, and <em>is-empty</em> operations take &Theta;(1) time. * Construction takes &Theta;(1) time. * <p> * For additional documentation, see * <a href="https://algs4.cs.princeton.edu/31elementary">Section 3.1</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class SequentialSearchST<Key, Value> { private int n; // number of key-value pairs private Node first; // the linked list of key-value pairs // a helper linked list data type private class Node { private Key key; private Value val; private Node next; public Node(Key key, Value val, Node next) { this.key = key; this.val = val; this.next = next; } } /** * Initializes an empty symbol table. */ public SequentialSearchST() { } /** * Returns the number of key-value pairs in this symbol table. * * @return the number of key-value pairs in this symbol table */ public int size() { return n; } /** * Returns true if this symbol table is empty. * * @return {@code true} if this symbol table is empty; * {@code false} otherwise */ public boolean isEmpty() { return size() == 0; } /** * Returns true if this symbol table contains the specified key. * * @param key the key * @return {@code true} if this symbol table contains {@code key}; * {@code false} otherwise * @throws IllegalArgumentException if {@code key} is {@code null} */ public boolean contains(Key key) { if (key == null) throw new IllegalArgumentException("argument to contains() is null"); return get(key) != null; } /** * Returns the value associated with the given key in this symbol table. * * @param key the key * @return the value associated with the given key if the key is in the symbol table * and {@code null} if the key is not in the symbol table * @throws IllegalArgumentException if {@code key} is {@code null} */ public Value get(Key key) { if (key == null) throw new IllegalArgumentException("argument to get() is null"); for (Node x = first; x != null; x = x.next) { if (key.equals(x.key)) return x.val; } return null; } /** * Inserts the specified key-value pair into the symbol table, overwriting the old * value with the new value if the symbol table already contains the specified key. * Deletes the specified key (and its associated value) from this symbol table * if the specified value is {@code null}. * * @param key the key * @param val the value * @throws IllegalArgumentException if {@code key} is {@code null} */ public void put(Key key, Value val) { if (key == null) throw new IllegalArgumentException("first argument to put() is null"); if (val == null) { delete(key); return; } for (Node x = first; x != null; x = x.next) { if (key.equals(x.key)) { x.val = val; return; } } first = new Node(key, val, first); n++; } /** * Removes the specified key and its associated value from this symbol table * (if the key is in this symbol table). * * @param key the key * @throws IllegalArgumentException if {@code key} is {@code null} */ public void delete(Key key) { if (key == null) throw new IllegalArgumentException("argument to delete() is null"); first = delete(first, key); } // delete key in linked list beginning at Node x // warning: function call stack too large if table is large private Node delete(Node x, Key key) { if (x == null) return null; if (key.equals(x.key)) { n--; return x.next; } x.next = delete(x.next, key); return x; } /** * Returns all keys in the symbol table as an {@code Iterable}. * To iterate over all of the keys in the symbol table named {@code st}, * use the foreach notation: {@code for (Key key : st.keys())}. * * @return all keys in the symbol table */ public Iterable<Key> keys() { Queue<Key> queue = new Queue<Key>(); for (Node x = first; x != null; x = x.next) queue.enqueue(x.key); return queue; } /** * Unit tests the {@code SequentialSearchST} data type. * * @param args the command-line arguments */ public static void main(String[] args) { SequentialSearchST<String, Integer> st = new SequentialSearchST<String, Integer>(); for (int i = 0; !StdIn.isEmpty(); i++) { String key = StdIn.readString(); st.put(key, i); } for (String s : st.keys()) StdOut.println(s + " " + st.get(s)); } }
[ "https://algs4.cs.princeton.edu/31elementary/tinyST.txt" ]
{ "number": "3.1.5", "code_execution": true, "url": "https://algs4.cs.princeton.edu/31elementary/SequentialSearchST.java", "params": [ "< tinyST.txt" ], "dependencies": [ "StdIn.java", "StdOut.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Implement the delete() method for BinarySearchST.java.
/****************************************************************************** * Compilation: javac BinarySearchST.java * Execution: java BinarySearchST * Dependencies: StdIn.java StdOut.java * Data files: https://algs4.cs.princeton.edu/31elementary/tinyST.txt * * Symbol table implementation with binary search in an ordered array. * * % more tinyST.txt * S E A R C H E X A M P L E * * % java BinarySearchST < tinyST.txt * A 8 * C 4 * E 12 * H 5 * L 11 * M 9 * P 10 * R 3 * S 0 * X 7 * ******************************************************************************/ import java.util.NoSuchElementException; /** * The {@code BST} class represents an ordered symbol table of generic * key-value pairs. * It supports the usual <em>put</em>, <em>get</em>, <em>contains</em>, * <em>delete</em>, <em>size</em>, and <em>is-empty</em> methods. * It also provides ordered methods for finding the <em>minimum</em>, * <em>maximum</em>, <em>floor</em>, <em>select</em>, and <em>ceiling</em>. * It also provides a <em>keys</em> method for iterating over all of the keys. * A symbol table implements the <em>associative array</em> abstraction: * when associating a value with a key that is already in the symbol table, * the convention is to replace the old value with the new value. * Unlike {@link java.util.Map}, this class uses the convention that * values cannot be {@code null}—setting the * value associated with a key to {@code null} is equivalent to deleting the key * from the symbol table. * <p> * It requires that * the key type implements the {@code Comparable} interface and calls the * {@code compareTo()} and method to compare two keys. It does not call either * {@code equals()} or {@code hashCode()}. * <p> * This implementation uses a <em>sorted array</em>. * The <em>put</em> and <em>remove</em> operations take &Theta;(<em>n</em>) * time in the worst case. * The <em>contains</em>, <em>ceiling</em>, <em>floor</em>, * and <em>rank</em> operations take &Theta;(log <em>n</em>) time in the worst * case. * The <em>size</em>, <em>is-empty</em>, <em>minimum</em>, <em>maximum</em>, * and <em>select</em> operations take &Theta;(1) time. * Construction takes &Theta;(1) time. * <p> * For alternative implementations of the symbol table API, * see {@link ST}, {@link BST}, {@link SequentialSearchST}, {@link RedBlackBST}, * {@link SeparateChainingHashST}, and {@link LinearProbingHashST}, * For additional documentation, * see <a href="https://algs4.cs.princeton.edu/31elementary">Section 3.1</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. */ public class BinarySearchST<Key extends Comparable<Key>, Value> { private static final int INIT_CAPACITY = 2; private Key[] keys; private Value[] vals; private int n = 0; /** * Initializes an empty symbol table. */ public BinarySearchST() { this(INIT_CAPACITY); } /** * Initializes an empty symbol table with the specified initial capacity. * @param capacity the maximum capacity */ public BinarySearchST(int capacity) { keys = (Key[]) new Comparable[capacity]; vals = (Value[]) new Object[capacity]; } // resize the underlying arrays private void resize(int capacity) { assert capacity >= n; Key[] tempk = (Key[]) new Comparable[capacity]; Value[] tempv = (Value[]) new Object[capacity]; for (int i = 0; i < n; i++) { tempk[i] = keys[i]; tempv[i] = vals[i]; } vals = tempv; keys = tempk; } /** * Returns the number of key-value pairs in this symbol table. * * @return the number of key-value pairs in this symbol table */ public int size() { return n; } /** * Returns true if this symbol table is empty. * * @return {@code true} if this symbol table is empty; * {@code false} otherwise */ public boolean isEmpty() { return size() == 0; } /** * Does this symbol table contain the given key? * * @param key the key * @return {@code true} if this symbol table contains {@code key} and * {@code false} otherwise * @throws IllegalArgumentException if {@code key} is {@code null} */ public boolean contains(Key key) { if (key == null) throw new IllegalArgumentException("argument to contains() is null"); return get(key) != null; } /** * Returns the value associated with the given key in this symbol table. * * @param key the key * @return the value associated with the given key if the key is in the symbol table * and {@code null} if the key is not in the symbol table * @throws IllegalArgumentException if {@code key} is {@code null} */ public Value get(Key key) { if (key == null) throw new IllegalArgumentException("argument to get() is null"); if (isEmpty()) return null; int i = rank(key); if (i < n && keys[i].compareTo(key) == 0) return vals[i]; return null; } /** * Returns the number of keys in this symbol table strictly less than {@code key}. * * @param key the key * @return the number of keys in the symbol table strictly less than {@code key} * @throws IllegalArgumentException if {@code key} is {@code null} */ public int rank(Key key) { if (key == null) throw new IllegalArgumentException("argument to rank() is null"); int lo = 0, hi = n-1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; int cmp = key.compareTo(keys[mid]); if (cmp < 0) hi = mid - 1; else if (cmp > 0) lo = mid + 1; else return mid; } return lo; } /** * Inserts the specified key-value pair into the symbol table, overwriting the old * value with the new value if the symbol table already contains the specified key. * Deletes the specified key (and its associated value) from this symbol table * if the specified value is {@code null}. * * @param key the key * @param val the value * @throws IllegalArgumentException if {@code key} is {@code null} */ public void put(Key key, Value val) { if (key == null) throw new IllegalArgumentException("first argument to put() is null"); if (val == null) { delete(key); return; } int i = rank(key); // key is already in table if (i < n && keys[i].compareTo(key) == 0) { vals[i] = val; return; } // insert new key-value pair if (n == keys.length) resize(2*keys.length); for (int j = n; j > i; j--) { keys[j] = keys[j-1]; vals[j] = vals[j-1]; } keys[i] = key; vals[i] = val; n++; assert check(); } /** * Removes the specified key and associated value from this symbol table * (if the key is in the symbol table). * * @param key the key * @throws IllegalArgumentException if {@code key} is {@code null} */ public void delete(Key key) { if (key == null) throw new IllegalArgumentException("argument to delete() is null"); if (isEmpty()) return; // compute rank int i = rank(key); // key not in table if (i == n || keys[i].compareTo(key) != 0) { return; } for (int j = i; j < n-1; j++) { keys[j] = keys[j+1]; vals[j] = vals[j+1]; } n--; keys[n] = null; // to avoid loitering vals[n] = null; // resize if 1/4 full if (n > 0 && n == keys.length/4) resize(keys.length/2); assert check(); } /** * Removes the smallest key and associated value from this symbol table. * * @throws NoSuchElementException if the symbol table is empty */ public void deleteMin() { if (isEmpty()) throw new NoSuchElementException("Symbol table underflow error"); delete(min()); } /** * Removes the largest key and associated value from this symbol table. * * @throws NoSuchElementException if the symbol table is empty */ public void deleteMax() { if (isEmpty()) throw new NoSuchElementException("Symbol table underflow error"); delete(max()); } /*************************************************************************** * Ordered symbol table methods. ***************************************************************************/ /** * Returns the smallest key in this symbol table. * * @return the smallest key in this symbol table * @throws NoSuchElementException if this symbol table is empty */ public Key min() { if (isEmpty()) throw new NoSuchElementException("called min() with empty symbol table"); return keys[0]; } /** * Returns the largest key in this symbol table. * * @return the largest key in this symbol table * @throws NoSuchElementException if this symbol table is empty */ public Key max() { if (isEmpty()) throw new NoSuchElementException("called max() with empty symbol table"); return keys[n-1]; } /** * Return the kth smallest key in this symbol table. * * @param k the order statistic * @return the {@code k}th smallest key in this symbol table * @throws IllegalArgumentException unless {@code k} is between 0 and * <em>n</em>–1 */ public Key select(int k) { if (k < 0 || k >= size()) { throw new IllegalArgumentException("called select() with invalid argument: " + k); } return keys[k]; } /** * Returns the largest key in this symbol table less than or equal to {@code key}. * * @param key the key * @return the largest key in this symbol table less than or equal to {@code key} * @throws NoSuchElementException if there is no such key * @throws IllegalArgumentException if {@code key} is {@code null} */ public Key floor(Key key) { if (key == null) throw new IllegalArgumentException("argument to floor() is null"); int i = rank(key); if (i < n && key.compareTo(keys[i]) == 0) return keys[i]; if (i == 0) throw new NoSuchElementException("argument to floor() is too small"); else return keys[i-1]; } /** * Returns the smallest key in this symbol table greater than or equal to {@code key}. * * @param key the key * @return the smallest key in this symbol table greater than or equal to {@code key} * @throws NoSuchElementException if there is no such key * @throws IllegalArgumentException if {@code key} is {@code null} */ public Key ceiling(Key key) { if (key == null) throw new IllegalArgumentException("argument to ceiling() is null"); int i = rank(key); if (i == n) throw new NoSuchElementException("argument to ceiling() is too large"); else return keys[i]; } /** * Returns the number of keys in this symbol table in the specified range. * * @param lo minimum endpoint * @param hi maximum endpoint * @return the number of keys in this symbol table between {@code lo} * (inclusive) and {@code hi} (inclusive) * @throws IllegalArgumentException if either {@code lo} or {@code hi} * is {@code null} */ public int size(Key lo, Key hi) { if (lo == null) throw new IllegalArgumentException("first argument to size() is null"); if (hi == null) throw new IllegalArgumentException("second argument to size() is null"); if (lo.compareTo(hi) > 0) return 0; if (contains(hi)) return rank(hi) - rank(lo) + 1; else return rank(hi) - rank(lo); } /** * Returns all keys in this symbol table as an {@code Iterable}. * To iterate over all of the keys in the symbol table named {@code st}, * use the foreach notation: {@code for (Key key : st.keys())}. * * @return all keys in this symbol table */ public Iterable<Key> keys() { return keys(min(), max()); } /** * Returns all keys in this symbol table in the given range, * as an {@code Iterable}. * * @param lo minimum endpoint * @param hi maximum endpoint * @return all keys in this symbol table between {@code lo} * (inclusive) and {@code hi} (inclusive) * @throws IllegalArgumentException if either {@code lo} or {@code hi} * is {@code null} */ public Iterable<Key> keys(Key lo, Key hi) { if (lo == null) throw new IllegalArgumentException("first argument to keys() is null"); if (hi == null) throw new IllegalArgumentException("second argument to keys() is null"); Queue<Key> queue = new Queue<Key>(); if (lo.compareTo(hi) > 0) return queue; for (int i = rank(lo); i < rank(hi); i++) queue.enqueue(keys[i]); if (contains(hi)) queue.enqueue(keys[rank(hi)]); return queue; } /*************************************************************************** * Check internal invariants. ***************************************************************************/ private boolean check() { return isSorted() && rankCheck(); } // are the items in the array in ascending order? private boolean isSorted() { for (int i = 1; i < size(); i++) if (keys[i].compareTo(keys[i-1]) < 0) return false; return true; } // check that rank(select(i)) = i private boolean rankCheck() { for (int i = 0; i < size(); i++) if (i != rank(select(i))) return false; for (int i = 0; i < size(); i++) if (keys[i].compareTo(select(rank(keys[i]))) != 0) return false; return true; } /** * Unit tests the {@code BinarySearchST} data type. * * @param args the command-line arguments */ public static void main(String[] args) { BinarySearchST<String, Integer> st = new BinarySearchST<String, Integer>(); for (int i = 0; !StdIn.isEmpty(); i++) { String key = StdIn.readString(); st.put(key, i); } for (String s : st.keys()) StdOut.println(s + " " + st.get(s)); } }
[ "https://algs4.cs.princeton.edu/31elementary/tinyST.txt" ]
{ "number": "3.1.16", "code_execution": true, "url": "https://algs4.cs.princeton.edu/31elementary/BinarySearchST.java", "params": [ "< tinyST.txt" ], "dependencies": [ "StdIn.java", "StdOut.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Implement the floor() method for BinarySearchST.java .
/****************************************************************************** * Compilation: javac BinarySearchST.java * Execution: java BinarySearchST * Dependencies: StdIn.java StdOut.java * Data files: https://algs4.cs.princeton.edu/31elementary/tinyST.txt * * Symbol table implementation with binary search in an ordered array. * * % more tinyST.txt * S E A R C H E X A M P L E * * % java BinarySearchST < tinyST.txt * A 8 * C 4 * E 12 * H 5 * L 11 * M 9 * P 10 * R 3 * S 0 * X 7 * ******************************************************************************/ import java.util.NoSuchElementException; /** * The {@code BST} class represents an ordered symbol table of generic * key-value pairs. * It supports the usual <em>put</em>, <em>get</em>, <em>contains</em>, * <em>delete</em>, <em>size</em>, and <em>is-empty</em> methods. * It also provides ordered methods for finding the <em>minimum</em>, * <em>maximum</em>, <em>floor</em>, <em>select</em>, and <em>ceiling</em>. * It also provides a <em>keys</em> method for iterating over all of the keys. * A symbol table implements the <em>associative array</em> abstraction: * when associating a value with a key that is already in the symbol table, * the convention is to replace the old value with the new value. * Unlike {@link java.util.Map}, this class uses the convention that * values cannot be {@code null}—setting the * value associated with a key to {@code null} is equivalent to deleting the key * from the symbol table. * <p> * It requires that * the key type implements the {@code Comparable} interface and calls the * {@code compareTo()} and method to compare two keys. It does not call either * {@code equals()} or {@code hashCode()}. * <p> * This implementation uses a <em>sorted array</em>. * The <em>put</em> and <em>remove</em> operations take &Theta;(<em>n</em>) * time in the worst case. * The <em>contains</em>, <em>ceiling</em>, <em>floor</em>, * and <em>rank</em> operations take &Theta;(log <em>n</em>) time in the worst * case. * The <em>size</em>, <em>is-empty</em>, <em>minimum</em>, <em>maximum</em>, * and <em>select</em> operations take &Theta;(1) time. * Construction takes &Theta;(1) time. * <p> * For alternative implementations of the symbol table API, * see {@link ST}, {@link BST}, {@link SequentialSearchST}, {@link RedBlackBST}, * {@link SeparateChainingHashST}, and {@link LinearProbingHashST}, * For additional documentation, * see <a href="https://algs4.cs.princeton.edu/31elementary">Section 3.1</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. */ public class BinarySearchST<Key extends Comparable<Key>, Value> { private static final int INIT_CAPACITY = 2; private Key[] keys; private Value[] vals; private int n = 0; /** * Initializes an empty symbol table. */ public BinarySearchST() { this(INIT_CAPACITY); } /** * Initializes an empty symbol table with the specified initial capacity. * @param capacity the maximum capacity */ public BinarySearchST(int capacity) { keys = (Key[]) new Comparable[capacity]; vals = (Value[]) new Object[capacity]; } // resize the underlying arrays private void resize(int capacity) { assert capacity >= n; Key[] tempk = (Key[]) new Comparable[capacity]; Value[] tempv = (Value[]) new Object[capacity]; for (int i = 0; i < n; i++) { tempk[i] = keys[i]; tempv[i] = vals[i]; } vals = tempv; keys = tempk; } /** * Returns the number of key-value pairs in this symbol table. * * @return the number of key-value pairs in this symbol table */ public int size() { return n; } /** * Returns true if this symbol table is empty. * * @return {@code true} if this symbol table is empty; * {@code false} otherwise */ public boolean isEmpty() { return size() == 0; } /** * Does this symbol table contain the given key? * * @param key the key * @return {@code true} if this symbol table contains {@code key} and * {@code false} otherwise * @throws IllegalArgumentException if {@code key} is {@code null} */ public boolean contains(Key key) { if (key == null) throw new IllegalArgumentException("argument to contains() is null"); return get(key) != null; } /** * Returns the value associated with the given key in this symbol table. * * @param key the key * @return the value associated with the given key if the key is in the symbol table * and {@code null} if the key is not in the symbol table * @throws IllegalArgumentException if {@code key} is {@code null} */ public Value get(Key key) { if (key == null) throw new IllegalArgumentException("argument to get() is null"); if (isEmpty()) return null; int i = rank(key); if (i < n && keys[i].compareTo(key) == 0) return vals[i]; return null; } /** * Returns the number of keys in this symbol table strictly less than {@code key}. * * @param key the key * @return the number of keys in the symbol table strictly less than {@code key} * @throws IllegalArgumentException if {@code key} is {@code null} */ public int rank(Key key) { if (key == null) throw new IllegalArgumentException("argument to rank() is null"); int lo = 0, hi = n-1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; int cmp = key.compareTo(keys[mid]); if (cmp < 0) hi = mid - 1; else if (cmp > 0) lo = mid + 1; else return mid; } return lo; } /** * Inserts the specified key-value pair into the symbol table, overwriting the old * value with the new value if the symbol table already contains the specified key. * Deletes the specified key (and its associated value) from this symbol table * if the specified value is {@code null}. * * @param key the key * @param val the value * @throws IllegalArgumentException if {@code key} is {@code null} */ public void put(Key key, Value val) { if (key == null) throw new IllegalArgumentException("first argument to put() is null"); if (val == null) { delete(key); return; } int i = rank(key); // key is already in table if (i < n && keys[i].compareTo(key) == 0) { vals[i] = val; return; } // insert new key-value pair if (n == keys.length) resize(2*keys.length); for (int j = n; j > i; j--) { keys[j] = keys[j-1]; vals[j] = vals[j-1]; } keys[i] = key; vals[i] = val; n++; assert check(); } /** * Removes the specified key and associated value from this symbol table * (if the key is in the symbol table). * * @param key the key * @throws IllegalArgumentException if {@code key} is {@code null} */ public void delete(Key key) { if (key == null) throw new IllegalArgumentException("argument to delete() is null"); if (isEmpty()) return; // compute rank int i = rank(key); // key not in table if (i == n || keys[i].compareTo(key) != 0) { return; } for (int j = i; j < n-1; j++) { keys[j] = keys[j+1]; vals[j] = vals[j+1]; } n--; keys[n] = null; // to avoid loitering vals[n] = null; // resize if 1/4 full if (n > 0 && n == keys.length/4) resize(keys.length/2); assert check(); } /** * Removes the smallest key and associated value from this symbol table. * * @throws NoSuchElementException if the symbol table is empty */ public void deleteMin() { if (isEmpty()) throw new NoSuchElementException("Symbol table underflow error"); delete(min()); } /** * Removes the largest key and associated value from this symbol table. * * @throws NoSuchElementException if the symbol table is empty */ public void deleteMax() { if (isEmpty()) throw new NoSuchElementException("Symbol table underflow error"); delete(max()); } /*************************************************************************** * Ordered symbol table methods. ***************************************************************************/ /** * Returns the smallest key in this symbol table. * * @return the smallest key in this symbol table * @throws NoSuchElementException if this symbol table is empty */ public Key min() { if (isEmpty()) throw new NoSuchElementException("called min() with empty symbol table"); return keys[0]; } /** * Returns the largest key in this symbol table. * * @return the largest key in this symbol table * @throws NoSuchElementException if this symbol table is empty */ public Key max() { if (isEmpty()) throw new NoSuchElementException("called max() with empty symbol table"); return keys[n-1]; } /** * Return the kth smallest key in this symbol table. * * @param k the order statistic * @return the {@code k}th smallest key in this symbol table * @throws IllegalArgumentException unless {@code k} is between 0 and * <em>n</em>–1 */ public Key select(int k) { if (k < 0 || k >= size()) { throw new IllegalArgumentException("called select() with invalid argument: " + k); } return keys[k]; } /** * Returns the largest key in this symbol table less than or equal to {@code key}. * * @param key the key * @return the largest key in this symbol table less than or equal to {@code key} * @throws NoSuchElementException if there is no such key * @throws IllegalArgumentException if {@code key} is {@code null} */ public Key floor(Key key) { if (key == null) throw new IllegalArgumentException("argument to floor() is null"); int i = rank(key); if (i < n && key.compareTo(keys[i]) == 0) return keys[i]; if (i == 0) throw new NoSuchElementException("argument to floor() is too small"); else return keys[i-1]; } /** * Returns the smallest key in this symbol table greater than or equal to {@code key}. * * @param key the key * @return the smallest key in this symbol table greater than or equal to {@code key} * @throws NoSuchElementException if there is no such key * @throws IllegalArgumentException if {@code key} is {@code null} */ public Key ceiling(Key key) { if (key == null) throw new IllegalArgumentException("argument to ceiling() is null"); int i = rank(key); if (i == n) throw new NoSuchElementException("argument to ceiling() is too large"); else return keys[i]; } /** * Returns the number of keys in this symbol table in the specified range. * * @param lo minimum endpoint * @param hi maximum endpoint * @return the number of keys in this symbol table between {@code lo} * (inclusive) and {@code hi} (inclusive) * @throws IllegalArgumentException if either {@code lo} or {@code hi} * is {@code null} */ public int size(Key lo, Key hi) { if (lo == null) throw new IllegalArgumentException("first argument to size() is null"); if (hi == null) throw new IllegalArgumentException("second argument to size() is null"); if (lo.compareTo(hi) > 0) return 0; if (contains(hi)) return rank(hi) - rank(lo) + 1; else return rank(hi) - rank(lo); } /** * Returns all keys in this symbol table as an {@code Iterable}. * To iterate over all of the keys in the symbol table named {@code st}, * use the foreach notation: {@code for (Key key : st.keys())}. * * @return all keys in this symbol table */ public Iterable<Key> keys() { return keys(min(), max()); } /** * Returns all keys in this symbol table in the given range, * as an {@code Iterable}. * * @param lo minimum endpoint * @param hi maximum endpoint * @return all keys in this symbol table between {@code lo} * (inclusive) and {@code hi} (inclusive) * @throws IllegalArgumentException if either {@code lo} or {@code hi} * is {@code null} */ public Iterable<Key> keys(Key lo, Key hi) { if (lo == null) throw new IllegalArgumentException("first argument to keys() is null"); if (hi == null) throw new IllegalArgumentException("second argument to keys() is null"); Queue<Key> queue = new Queue<Key>(); if (lo.compareTo(hi) > 0) return queue; for (int i = rank(lo); i < rank(hi); i++) queue.enqueue(keys[i]); if (contains(hi)) queue.enqueue(keys[rank(hi)]); return queue; } /*************************************************************************** * Check internal invariants. ***************************************************************************/ private boolean check() { return isSorted() && rankCheck(); } // are the items in the array in ascending order? private boolean isSorted() { for (int i = 1; i < size(); i++) if (keys[i].compareTo(keys[i-1]) < 0) return false; return true; } // check that rank(select(i)) = i private boolean rankCheck() { for (int i = 0; i < size(); i++) if (i != rank(select(i))) return false; for (int i = 0; i < size(); i++) if (keys[i].compareTo(select(rank(keys[i]))) != 0) return false; return true; } /** * Unit tests the {@code BinarySearchST} data type. * * @param args the command-line arguments */ public static void main(String[] args) { BinarySearchST<String, Integer> st = new BinarySearchST<String, Integer>(); for (int i = 0; !StdIn.isEmpty(); i++) { String key = StdIn.readString(); st.put(key, i); } for (String s : st.keys()) StdOut.println(s + " " + st.get(s)); } }
[ "https://algs4.cs.princeton.edu/31elementary/tinyST.txt" ]
{ "number": "3.1.17", "code_execution": true, "url": "https://algs4.cs.princeton.edu/31elementary/BinarySearchST.java", "params": [ "< tinyST.txt" ], "dependencies": [ "StdIn.java", "StdOut.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Certification. Add assert statements to BinarySearchST.java to check algorithm invariants and data structure integrity after every insertion and deletion. For example, every index i should always be equal to rank(select(i)) and the array should always be in order.
/****************************************************************************** * Compilation: javac BinarySearchST.java * Execution: java BinarySearchST * Dependencies: StdIn.java StdOut.java * Data files: https://algs4.cs.princeton.edu/31elementary/tinyST.txt * * Symbol table implementation with binary search in an ordered array. * * % more tinyST.txt * S E A R C H E X A M P L E * * % java BinarySearchST < tinyST.txt * A 8 * C 4 * E 12 * H 5 * L 11 * M 9 * P 10 * R 3 * S 0 * X 7 * ******************************************************************************/ import java.util.NoSuchElementException; /** * The {@code BST} class represents an ordered symbol table of generic * key-value pairs. * It supports the usual <em>put</em>, <em>get</em>, <em>contains</em>, * <em>delete</em>, <em>size</em>, and <em>is-empty</em> methods. * It also provides ordered methods for finding the <em>minimum</em>, * <em>maximum</em>, <em>floor</em>, <em>select</em>, and <em>ceiling</em>. * It also provides a <em>keys</em> method for iterating over all of the keys. * A symbol table implements the <em>associative array</em> abstraction: * when associating a value with a key that is already in the symbol table, * the convention is to replace the old value with the new value. * Unlike {@link java.util.Map}, this class uses the convention that * values cannot be {@code null}—setting the * value associated with a key to {@code null} is equivalent to deleting the key * from the symbol table. * <p> * It requires that * the key type implements the {@code Comparable} interface and calls the * {@code compareTo()} and method to compare two keys. It does not call either * {@code equals()} or {@code hashCode()}. * <p> * This implementation uses a <em>sorted array</em>. * The <em>put</em> and <em>remove</em> operations take &Theta;(<em>n</em>) * time in the worst case. * The <em>contains</em>, <em>ceiling</em>, <em>floor</em>, * and <em>rank</em> operations take &Theta;(log <em>n</em>) time in the worst * case. * The <em>size</em>, <em>is-empty</em>, <em>minimum</em>, <em>maximum</em>, * and <em>select</em> operations take &Theta;(1) time. * Construction takes &Theta;(1) time. * <p> * For alternative implementations of the symbol table API, * see {@link ST}, {@link BST}, {@link SequentialSearchST}, {@link RedBlackBST}, * {@link SeparateChainingHashST}, and {@link LinearProbingHashST}, * For additional documentation, * see <a href="https://algs4.cs.princeton.edu/31elementary">Section 3.1</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. */ public class BinarySearchST<Key extends Comparable<Key>, Value> { private static final int INIT_CAPACITY = 2; private Key[] keys; private Value[] vals; private int n = 0; /** * Initializes an empty symbol table. */ public BinarySearchST() { this(INIT_CAPACITY); } /** * Initializes an empty symbol table with the specified initial capacity. * @param capacity the maximum capacity */ public BinarySearchST(int capacity) { keys = (Key[]) new Comparable[capacity]; vals = (Value[]) new Object[capacity]; } // resize the underlying arrays private void resize(int capacity) { assert capacity >= n; Key[] tempk = (Key[]) new Comparable[capacity]; Value[] tempv = (Value[]) new Object[capacity]; for (int i = 0; i < n; i++) { tempk[i] = keys[i]; tempv[i] = vals[i]; } vals = tempv; keys = tempk; } /** * Returns the number of key-value pairs in this symbol table. * * @return the number of key-value pairs in this symbol table */ public int size() { return n; } /** * Returns true if this symbol table is empty. * * @return {@code true} if this symbol table is empty; * {@code false} otherwise */ public boolean isEmpty() { return size() == 0; } /** * Does this symbol table contain the given key? * * @param key the key * @return {@code true} if this symbol table contains {@code key} and * {@code false} otherwise * @throws IllegalArgumentException if {@code key} is {@code null} */ public boolean contains(Key key) { if (key == null) throw new IllegalArgumentException("argument to contains() is null"); return get(key) != null; } /** * Returns the value associated with the given key in this symbol table. * * @param key the key * @return the value associated with the given key if the key is in the symbol table * and {@code null} if the key is not in the symbol table * @throws IllegalArgumentException if {@code key} is {@code null} */ public Value get(Key key) { if (key == null) throw new IllegalArgumentException("argument to get() is null"); if (isEmpty()) return null; int i = rank(key); if (i < n && keys[i].compareTo(key) == 0) return vals[i]; return null; } /** * Returns the number of keys in this symbol table strictly less than {@code key}. * * @param key the key * @return the number of keys in the symbol table strictly less than {@code key} * @throws IllegalArgumentException if {@code key} is {@code null} */ public int rank(Key key) { if (key == null) throw new IllegalArgumentException("argument to rank() is null"); int lo = 0, hi = n-1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; int cmp = key.compareTo(keys[mid]); if (cmp < 0) hi = mid - 1; else if (cmp > 0) lo = mid + 1; else return mid; } return lo; } /** * Inserts the specified key-value pair into the symbol table, overwriting the old * value with the new value if the symbol table already contains the specified key. * Deletes the specified key (and its associated value) from this symbol table * if the specified value is {@code null}. * * @param key the key * @param val the value * @throws IllegalArgumentException if {@code key} is {@code null} */ public void put(Key key, Value val) { if (key == null) throw new IllegalArgumentException("first argument to put() is null"); if (val == null) { delete(key); return; } int i = rank(key); // key is already in table if (i < n && keys[i].compareTo(key) == 0) { vals[i] = val; return; } // insert new key-value pair if (n == keys.length) resize(2*keys.length); for (int j = n; j > i; j--) { keys[j] = keys[j-1]; vals[j] = vals[j-1]; } keys[i] = key; vals[i] = val; n++; assert check(); } /** * Removes the specified key and associated value from this symbol table * (if the key is in the symbol table). * * @param key the key * @throws IllegalArgumentException if {@code key} is {@code null} */ public void delete(Key key) { if (key == null) throw new IllegalArgumentException("argument to delete() is null"); if (isEmpty()) return; // compute rank int i = rank(key); // key not in table if (i == n || keys[i].compareTo(key) != 0) { return; } for (int j = i; j < n-1; j++) { keys[j] = keys[j+1]; vals[j] = vals[j+1]; } n--; keys[n] = null; // to avoid loitering vals[n] = null; // resize if 1/4 full if (n > 0 && n == keys.length/4) resize(keys.length/2); assert check(); } /** * Removes the smallest key and associated value from this symbol table. * * @throws NoSuchElementException if the symbol table is empty */ public void deleteMin() { if (isEmpty()) throw new NoSuchElementException("Symbol table underflow error"); delete(min()); } /** * Removes the largest key and associated value from this symbol table. * * @throws NoSuchElementException if the symbol table is empty */ public void deleteMax() { if (isEmpty()) throw new NoSuchElementException("Symbol table underflow error"); delete(max()); } /*************************************************************************** * Ordered symbol table methods. ***************************************************************************/ /** * Returns the smallest key in this symbol table. * * @return the smallest key in this symbol table * @throws NoSuchElementException if this symbol table is empty */ public Key min() { if (isEmpty()) throw new NoSuchElementException("called min() with empty symbol table"); return keys[0]; } /** * Returns the largest key in this symbol table. * * @return the largest key in this symbol table * @throws NoSuchElementException if this symbol table is empty */ public Key max() { if (isEmpty()) throw new NoSuchElementException("called max() with empty symbol table"); return keys[n-1]; } /** * Return the kth smallest key in this symbol table. * * @param k the order statistic * @return the {@code k}th smallest key in this symbol table * @throws IllegalArgumentException unless {@code k} is between 0 and * <em>n</em>–1 */ public Key select(int k) { if (k < 0 || k >= size()) { throw new IllegalArgumentException("called select() with invalid argument: " + k); } return keys[k]; } /** * Returns the largest key in this symbol table less than or equal to {@code key}. * * @param key the key * @return the largest key in this symbol table less than or equal to {@code key} * @throws NoSuchElementException if there is no such key * @throws IllegalArgumentException if {@code key} is {@code null} */ public Key floor(Key key) { if (key == null) throw new IllegalArgumentException("argument to floor() is null"); int i = rank(key); if (i < n && key.compareTo(keys[i]) == 0) return keys[i]; if (i == 0) throw new NoSuchElementException("argument to floor() is too small"); else return keys[i-1]; } /** * Returns the smallest key in this symbol table greater than or equal to {@code key}. * * @param key the key * @return the smallest key in this symbol table greater than or equal to {@code key} * @throws NoSuchElementException if there is no such key * @throws IllegalArgumentException if {@code key} is {@code null} */ public Key ceiling(Key key) { if (key == null) throw new IllegalArgumentException("argument to ceiling() is null"); int i = rank(key); if (i == n) throw new NoSuchElementException("argument to ceiling() is too large"); else return keys[i]; } /** * Returns the number of keys in this symbol table in the specified range. * * @param lo minimum endpoint * @param hi maximum endpoint * @return the number of keys in this symbol table between {@code lo} * (inclusive) and {@code hi} (inclusive) * @throws IllegalArgumentException if either {@code lo} or {@code hi} * is {@code null} */ public int size(Key lo, Key hi) { if (lo == null) throw new IllegalArgumentException("first argument to size() is null"); if (hi == null) throw new IllegalArgumentException("second argument to size() is null"); if (lo.compareTo(hi) > 0) return 0; if (contains(hi)) return rank(hi) - rank(lo) + 1; else return rank(hi) - rank(lo); } /** * Returns all keys in this symbol table as an {@code Iterable}. * To iterate over all of the keys in the symbol table named {@code st}, * use the foreach notation: {@code for (Key key : st.keys())}. * * @return all keys in this symbol table */ public Iterable<Key> keys() { return keys(min(), max()); } /** * Returns all keys in this symbol table in the given range, * as an {@code Iterable}. * * @param lo minimum endpoint * @param hi maximum endpoint * @return all keys in this symbol table between {@code lo} * (inclusive) and {@code hi} (inclusive) * @throws IllegalArgumentException if either {@code lo} or {@code hi} * is {@code null} */ public Iterable<Key> keys(Key lo, Key hi) { if (lo == null) throw new IllegalArgumentException("first argument to keys() is null"); if (hi == null) throw new IllegalArgumentException("second argument to keys() is null"); Queue<Key> queue = new Queue<Key>(); if (lo.compareTo(hi) > 0) return queue; for (int i = rank(lo); i < rank(hi); i++) queue.enqueue(keys[i]); if (contains(hi)) queue.enqueue(keys[rank(hi)]); return queue; } /*************************************************************************** * Check internal invariants. ***************************************************************************/ private boolean check() { return isSorted() && rankCheck(); } // are the items in the array in ascending order? private boolean isSorted() { for (int i = 1; i < size(); i++) if (keys[i].compareTo(keys[i-1]) < 0) return false; return true; } // check that rank(select(i)) = i private boolean rankCheck() { for (int i = 0; i < size(); i++) if (i != rank(select(i))) return false; for (int i = 0; i < size(); i++) if (keys[i].compareTo(select(rank(keys[i]))) != 0) return false; return true; } /** * Unit tests the {@code BinarySearchST} data type. * * @param args the command-line arguments */ public static void main(String[] args) { BinarySearchST<String, Integer> st = new BinarySearchST<String, Integer>(); for (int i = 0; !StdIn.isEmpty(); i++) { String key = StdIn.readString(); st.put(key, i); } for (String s : st.keys()) StdOut.println(s + " " + st.get(s)); } }
[ "https://algs4.cs.princeton.edu/31elementary/tinyST.txt" ]
{ "number": "3.1.30", "code_execution": true, "url": "https://algs4.cs.princeton.edu/31elementary/BinarySearchST.java", "params": [ "< tinyST.txt" ], "dependencies": [ "StdIn.java", "StdOut.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Add to BST.java a method height() that computes the height of the tree. Develop two implementations: a recursive method (which takes linear time and space proportional to the height), and method like size() that adds a field to each node in the tree (and takes linear space and constant time per query).
/****************************************************************************** * Compilation: javac BST.java * Execution: java BST * Dependencies: StdIn.java StdOut.java Queue.java * Data files: https://algs4.cs.princeton.edu/32bst/tinyST.txt * * A symbol table implemented with a binary search tree. * * % more tinyST.txt * S E A R C H E X A M P L E * * % java BST < tinyST.txt * A 8 * C 4 * E 12 * H 5 * L 11 * M 9 * P 10 * R 3 * S 0 * X 7 * ******************************************************************************/ import java.util.NoSuchElementException; /** * The {@code BST} class represents an ordered symbol table of generic * key-value pairs. * It supports the usual <em>put</em>, <em>get</em>, <em>contains</em>, * <em>delete</em>, <em>size</em>, and <em>is-empty</em> methods. * It also provides ordered methods for finding the <em>minimum</em>, * <em>maximum</em>, <em>floor</em>, <em>select</em>, <em>ceiling</em>. * It also provides a <em>keys</em> method for iterating over all of the keys. * A symbol table implements the <em>associative array</em> abstraction: * when associating a value with a key that is already in the symbol table, * the convention is to replace the old value with the new value. * Unlike {@link java.util.Map}, this class uses the convention that * values cannot be {@code null}—setting the * value associated with a key to {@code null} is equivalent to deleting the key * from the symbol table. * <p> * It requires that * the key type implements the {@code Comparable} interface and calls the * {@code compareTo()} and method to compare two keys. It does not call either * {@code equals()} or {@code hashCode()}. * <p> * This implementation uses an (unbalanced) <em>binary search tree</em>. * The <em>put</em>, <em>contains</em>, <em>remove</em>, <em>minimum</em>, * <em>maximum</em>, <em>ceiling</em>, <em>floor</em>, <em>select</em>, and * <em>rank</em> operations each take &Theta;(<em>n</em>) time in the worst * case, where <em>n</em> is the number of key-value pairs. * The <em>size</em> and <em>is-empty</em> operations take &Theta;(1) time. * The keys method takes &Theta;(<em>n</em>) time in the worst case. * Construction takes &Theta;(1) time. * <p> * For alternative implementations of the symbol table API, see {@link ST}, * {@link BinarySearchST}, {@link SequentialSearchST}, {@link RedBlackBST}, * {@link SeparateChainingHashST}, and {@link LinearProbingHashST}, * For additional documentation, see * <a href="https://algs4.cs.princeton.edu/32bst">Section 3.2</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class BST<Key extends Comparable<Key>, Value> { private Node root; // root of BST private class Node { private Key key; // sorted by key private Value val; // associated data private Node left, right; // left and right subtrees private int size; // number of nodes in subtree public Node(Key key, Value val, int size) { this.key = key; this.val = val; this.size = size; } } /** * Initializes an empty symbol table. */ public BST() { } /** * Returns true if this symbol table is empty. * @return {@code true} if this symbol table is empty; {@code false} otherwise */ public boolean isEmpty() { return size() == 0; } /** * Returns the number of key-value pairs in this symbol table. * @return the number of key-value pairs in this symbol table */ public int size() { return size(root); } // return number of key-value pairs in BST rooted at x private int size(Node node) { if (node == null) return 0; else return node.size; } /** * Does this symbol table contain the given key? * * @param key the key * @return {@code true} if this symbol table contains {@code key} and * {@code false} otherwise * @throws IllegalArgumentException if {@code key} is {@code null} */ public boolean contains(Key key) { if (key == null) throw new IllegalArgumentException("argument to contains() is null"); return get(key) != null; } /** * Returns the value associated with the given key. * * @param key the key * @return the value associated with the given key if the key is in the symbol table * and {@code null} if the key is not in the symbol table * @throws IllegalArgumentException if {@code key} is {@code null} */ public Value get(Key key) { return get(root, key); } private Value get(Node node, Key key) { if (key == null) throw new IllegalArgumentException("calls get() with a null key"); if (node == null) return null; int cmp = key.compareTo(node.key); if (cmp < 0) return get(node.left, key); else if (cmp > 0) return get(node.right, key); else return node.val; } /** * Inserts the specified key-value pair into the symbol table, overwriting the old * value with the new value if the symbol table already contains the specified key. * Deletes the specified key (and its associated value) from this symbol table * if the specified value is {@code null}. * * @param key the key * @param val the value * @throws IllegalArgumentException if {@code key} is {@code null} */ public void put(Key key, Value val) { if (key == null) throw new IllegalArgumentException("calls put() with a null key"); if (val == null) { delete(key); return; } root = put(root, key, val); assert check(); } private Node put(Node node, Key key, Value val) { if (node == null) return new Node(key, val, 1); int cmp = key.compareTo(node.key); if (cmp < 0) node.left = put(node.left, key, val); else if (cmp > 0) node.right = put(node.right, key, val); else node.val = val; node.size = 1 + size(node.left) + size(node.right); return node; } /** * Removes the smallest key and associated value from the symbol table. * * @throws NoSuchElementException if the symbol table is empty */ public void deleteMin() { if (isEmpty()) throw new NoSuchElementException("Symbol table underflow"); root = deleteMin(root); assert check(); } private Node deleteMin(Node node) { if (node.left == null) return node.right; node.left = deleteMin(node.left); node.size = size(node.left) + size(node.right) + 1; return node; } /** * Removes the largest key and associated value from the symbol table. * * @throws NoSuchElementException if the symbol table is empty */ public void deleteMax() { if (isEmpty()) throw new NoSuchElementException("Symbol table underflow"); root = deleteMax(root); assert check(); } private Node deleteMax(Node node) { if (node.right == null) return node.left; node.right = deleteMax(node.right); node.size = size(node.left) + size(node.right) + 1; return node; } /** * Removes the specified key and its associated value from this symbol table * (if the key is in this symbol table). * * @param key the key * @throws IllegalArgumentException if {@code key} is {@code null} */ public void delete(Key key) { if (key == null) throw new IllegalArgumentException("calls delete() with a null key"); root = delete(root, key); assert check(); } private Node delete(Node node, Key key) { if (node == null) return null; int cmp = key.compareTo(node.key); if (cmp < 0) node.left = delete(node.left, key); else if (cmp > 0) node.right = delete(node.right, key); else { if (node.right == null) return node.left; if (node.left == null) return node.right; Node temp = node; node = min(temp.right); node.right = deleteMin(temp.right); node.left = temp.left; } node.size = size(node.left) + size(node.right) + 1; return node; } /** * Returns the smallest key in the symbol table. * * @return the smallest key in the symbol table * @throws NoSuchElementException if the symbol table is empty */ public Key min() { if (isEmpty()) throw new NoSuchElementException("calls min() with empty symbol table"); return min(root).key; } private Node min(Node node) { if (node.left == null) return node; else return min(node.left); } /** * Returns the largest key in the symbol table. * * @return the largest key in the symbol table * @throws NoSuchElementException if the symbol table is empty */ public Key max() { if (isEmpty()) throw new NoSuchElementException("calls max() with empty symbol table"); return max(root).key; } private Node max(Node node) { if (node.right == null) return node; else return max(node.right); } /** * Returns the largest key in the symbol table less than or equal to {@code key}. * * @param key the key * @return the largest key in the symbol table less than or equal to {@code key} * @throws NoSuchElementException if there is no such key * @throws IllegalArgumentException if {@code key} is {@code null} */ public Key floor(Key key) { if (key == null) throw new IllegalArgumentException("argument to floor() is null"); if (isEmpty()) throw new NoSuchElementException("calls floor() with empty symbol table"); Node node = floor(root, key); if (node == null) throw new NoSuchElementException("argument to floor() is too small"); else return node.key; } private Node floor(Node node, Key key) { if (node == null) return null; int cmp = key.compareTo(node.key); if (cmp == 0) return node; if (cmp < 0) return floor(node.left, key); Node t = floor(node.right, key); if (t != null) return t; else return node; } public Key floor2(Key key) { Key floor = floor2(root, key, null); if (floor == null) throw new NoSuchElementException("argument to floor() is too small"); else return floor; } private Key floor2(Node node, Key key, Key champ) { if (node == null) return champ; int cmp = key.compareTo(node.key); if (cmp < 0) return floor2(node.left, key, champ); else if (cmp > 0) return floor2(node.right, key, node.key); else return node.key; } /** * Returns the smallest key in the symbol table greater than or equal to {@code key}. * * @param key the key * @return the smallest key in the symbol table greater than or equal to {@code key} * @throws NoSuchElementException if there is no such key * @throws IllegalArgumentException if {@code key} is {@code null} */ public Key ceiling(Key key) { if (key == null) throw new IllegalArgumentException("argument to ceiling() is null"); if (isEmpty()) throw new NoSuchElementException("calls ceiling() with empty symbol table"); Node node = ceiling(root, key); if (node == null) throw new NoSuchElementException("argument to ceiling() is too large"); else return node.key; } private Node ceiling(Node node, Key key) { if (node == null) return null; int cmp = key.compareTo(node.key); if (cmp == 0) return node; if (cmp < 0) { Node t = ceiling(node.left, key); if (t != null) return t; else return node; } return ceiling(node.right, key); } /** * Return the key in the symbol table of a given {@code rank}. * This key has the property that there are {@code rank} keys in * the symbol table that are smaller. In other words, this key is the * ({@code rank}+1)st smallest key in the symbol table. * * @param rank the order statistic * @return the key in the symbol table of given {@code rank} * @throws IllegalArgumentException unless {@code rank} is between 0 and * <em>n</em>–1 */ public Key select(int rank) { if (rank < 0 || rank >= size()) { throw new IllegalArgumentException("argument to select() is invalid: " + rank); } return select(root, rank); } // Return key in BST rooted at x of given rank. // Precondition: rank is in legal range. private Key select(Node node, int rank) { if (node == null) return null; int leftSize = size(node.left); if (leftSize > rank) return select(node.left, rank); else if (leftSize < rank) return select(node.right, rank - leftSize - 1); else return node.key; } /** * Return the number of keys in the symbol table strictly less than {@code key}. * * @param key the key * @return the number of keys in the symbol table strictly less than {@code key} * @throws IllegalArgumentException if {@code key} is {@code null} */ public int rank(Key key) { if (key == null) throw new IllegalArgumentException("argument to rank() is null"); return rank(key, root); } // Number of keys in the subtree less than key. private int rank(Key key, Node node) { if (node == null) return 0; int cmp = key.compareTo(node.key); if (cmp < 0) return rank(key, node.left); else if (cmp > 0) return 1 + size(node.left) + rank(key, node.right); else return size(node.left); } /** * Returns all keys in the symbol table in ascending order, * as an {@code Iterable}. * To iterate over all of the keys in the symbol table named {@code st}, * use the foreach notation: {@code for (Key key : st.keys())}. * * @return all keys in the symbol table in ascending order */ public Iterable<Key> keys() { if (isEmpty()) return new Queue<Key>(); return keys(min(), max()); } /** * Returns all keys in the symbol table in the given range * in ascending order, as an {@code Iterable}. * * @param lo minimum endpoint * @param hi maximum endpoint * @return all keys in the symbol table between {@code lo} * (inclusive) and {@code hi} (inclusive) in ascending order * @throws IllegalArgumentException if either {@code lo} or {@code hi} * is {@code null} */ public Iterable<Key> keys(Key lo, Key hi) { if (lo == null) throw new IllegalArgumentException("first argument to keys() is null"); if (hi == null) throw new IllegalArgumentException("second argument to keys() is null"); Queue<Key> queue = new Queue<Key>(); keys(root, queue, lo, hi); return queue; } private void keys(Node node, Queue<Key> queue, Key lo, Key hi) { if (node == null) return; int cmplo = lo.compareTo(node.key); int cmphi = hi.compareTo(node.key); if (cmplo < 0) keys(node.left, queue, lo, hi); if (cmplo <= 0 && cmphi >= 0) queue.enqueue(node.key); if (cmphi > 0) keys(node.right, queue, lo, hi); } /** * Returns the number of keys in the symbol table in the given range. * * @param lo minimum endpoint * @param hi maximum endpoint * @return the number of keys in the symbol table between {@code lo} * (inclusive) and {@code hi} (inclusive) * @throws IllegalArgumentException if either {@code lo} or {@code hi} * is {@code null} */ public int size(Key lo, Key hi) { if (lo == null) throw new IllegalArgumentException("first argument to size() is null"); if (hi == null) throw new IllegalArgumentException("second argument to size() is null"); if (lo.compareTo(hi) > 0) return 0; if (contains(hi)) return rank(hi) - rank(lo) + 1; else return rank(hi) - rank(lo); } /** * Returns the height of the BST (for debugging). * * @return the height of the BST (a 1-node tree has height 0) */ public int height() { return height(root); } private int height(Node node) { if (node == null) return -1; return 1 + Math.max(height(node.left), height(node.right)); } /** * Returns the keys in the BST in level order (for debugging). * * @return the keys in the BST in level order traversal */ public Iterable<Key> levelOrder() { Queue<Key> keys = new Queue<Key>(); Queue<Node> queue = new Queue<Node>(); queue.enqueue(root); while (!queue.isEmpty()) { Node node = queue.dequeue(); if (node == null) continue; keys.enqueue(node.key); queue.enqueue(node.left); queue.enqueue(node.right); } return keys; } /************************************************************************* * Check integrity of BST data structure. ***************************************************************************/ private boolean check() { if (!isBST()) StdOut.println("Not in symmetric order"); if (!isSizeConsistent()) StdOut.println("Subtree counts not consistent"); if (!isRankConsistent()) StdOut.println("Ranks not consistent"); return isBST() && isSizeConsistent() && isRankConsistent(); } // does this binary tree satisfy symmetric order? // Note: this test also ensures that data structure is a binary tree since order is strict private boolean isBST() { return isBST(root, null, null); } // is the tree rooted at x a BST with all keys strictly between min and max // (if min or max is null, treat as empty constraint) // Credit: elegant solution due to Bob Dondero private boolean isBST(Node node, Key min, Key max) { if (node == null) return true; if (min != null && node.key.compareTo(min) <= 0) return false; if (max != null && node.key.compareTo(max) >= 0) return false; return isBST(node.left, min, node.key) && isBST(node.right, node.key, max); } // are the size fields correct? private boolean isSizeConsistent() { return isSizeConsistent(root); } private boolean isSizeConsistent(Node node) { if (node == null) return true; if (node.size != size(node.left) + size(node.right) + 1) return false; return isSizeConsistent(node.left) && isSizeConsistent(node.right); } // check that ranks are consistent private boolean isRankConsistent() { for (int i = 0; i < size(); i++) if (i != rank(select(i))) return false; for (Key key : keys()) if (key.compareTo(select(rank(key))) != 0) return false; return true; } /** * Unit tests the {@code BST} data type. * * @param args the command-line arguments */ public static void main(String[] args) { BST<String, Integer> st = new BST<String, Integer>(); for (int i = 0; !StdIn.isEmpty(); i++) { String key = StdIn.readString(); st.put(key, i); } for (String s : st.levelOrder()) StdOut.println(s + " " + st.get(s)); StdOut.println(); for (String s : st.keys()) StdOut.println(s + " " + st.get(s)); } }
[ "https://algs4.cs.princeton.edu/32bst/tinyST.txt" ]
{ "number": "3.2.6", "code_execution": true, "url": "https://algs4.cs.princeton.edu/32bst/BST.java", "params": [ "< tinyST.txt" ], "dependencies": [ "StdIn.java", "StdOut.java", "Queue.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Give nonrecursive implementations of get() , put() , and keys() for BST.
/****************************************************************************** * Compilation: javac NonrecursiveBST.java * Execution: java NonrecursiveBST < input.txt * Dependencies: StdOut.java StdIn.java * * A symbol table implemented with a binary search tree using * iteration instead of recursion for put(), get(), and keys(). * * % more tinyST.txt * S E A R C H E X A M P L E * * % java NonrecursiveBST < tinyST.txt * A 8 * C 4 * E 12 * H 5 * L 11 * M 9 * P 10 * R 3 * S 0 * X 7 * ******************************************************************************/ public class NonrecursiveBST<Key extends Comparable<Key>, Value> { // root of BST private Node root; private class Node { private Key key; // sorted by key private Value val; // associated value private Node left, right; // left and right subtrees public Node(Key key, Value val) { this.key = key; this.val = val; } } /*************************************************************************** * Insert key-value pair into symbol table (nonrecursive version). ***************************************************************************/ public void put(Key key, Value val) { Node z = new Node(key, val); if (root == null) { root = z; return; } Node parent = null, x = root; while (x != null) { parent = x; int cmp = key.compareTo(x.key); if (cmp < 0) x = x.left; else if (cmp > 0) x = x.right; else { x.val = val; return; } } int cmp = key.compareTo(parent.key); if (cmp < 0) parent.left = z; else parent.right = z; } /*************************************************************************** * Search BST for given key, nonrecursive version. ***************************************************************************/ Value get(Key key) { Node x = root; while (x != null) { int cmp = key.compareTo(x.key); if (cmp < 0) x = x.left; else if (cmp > 0) x = x.right; else return x.val; } return null; } /*************************************************************************** * Inorder traversal. ***************************************************************************/ public Iterable<Key> keys() { Stack<Node> stack = new Stack<Node>(); Queue<Key> queue = new Queue<Key>(); Node x = root; while (x != null || !stack.isEmpty()) { if (x != null) { stack.push(x); x = x.left; } else { x = stack.pop(); queue.enqueue(x.key); x = x.right; } } return queue; } /*************************************************************************** * Test client. ***************************************************************************/ public static void main(String[] args) { String[] a = StdIn.readAllStrings(); int n = a.length; NonrecursiveBST<String, Integer> st = new NonrecursiveBST<String, Integer>(); for (int i = 0; i < n; i++) st.put(a[i], i); for (String s : st.keys()) StdOut.println(s + " " + st.get(s)); } }
[]
{ "number": "3.2.13", "code_execution": true, "url": "https://algs4.cs.princeton.edu/32bst/NonrecursiveBST.java", "params": [ "< tinyST.txt" ], "dependencies": [ "StdOut.java", "StdIn.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Perfect balance. Write a program PerfectBalance.java that inserts a set of keys into an initially empty BST such that the tree produced is equivalent to binary search, in the sense that the sequence of compares done in the search for any key in the BST is the same as the sequence of compares used by binary search for the same set of keys. Hint: Put the median at the root and recursively build the left and right subtree.
/****************************************************************************** * Compilation: javac PerfectBalance.java * Execution: java PerfectBalance < input.txt * Dependencies: StdOut.java * * Read sequence of strings from standard input (no duplicates), * and insert into a BST so that BST is perfectly balanced. * * % java PerfectBalance * P E R F C T B I N A R Y S R H * N E B A C H F I R R P R T S Y * ******************************************************************************/ import java.util.Arrays; public class PerfectBalance { // precondition: a[] has no duplicates private static void perfect(BST bst, String[] a) { Arrays.sort(a); perfect(bst, a, 0, a.length - 1); StdOut.println(); } // precondition: a[lo..hi] is sorted private static void perfect(BST bst, String[] a, int lo, int hi) { if (hi < lo) return; int mid = lo + (hi - lo) / 2; bst.put(a[mid], mid); StdOut.print(a[mid] + " "); perfect(bst, a, lo, mid-1); perfect(bst, a, mid+1, hi); } public static void main(String[] args) { String[] words = StdIn.readAllStrings(); BST<String, Integer> bst = new BST<String, Integer>(); perfect(bst, words); } }
[]
{ "number": "3.2.25", "code_execution": true, "url": "https://algs4.cs.princeton.edu/32bst/PerfectBalance.java", "params": [ "<<EOF\nP E R F C T B I N A R Y S R H\nEOF" ], "dependencies": [ "StdOut.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Subtree count check. Write a recursive method isSizeConsistent() in BST.java that takes a Node as argument and returns true if the subtree count field N is consistent in the data structure rooted at that node, false otherwise.
/****************************************************************************** * Compilation: javac BST.java * Execution: java BST * Dependencies: StdIn.java StdOut.java Queue.java * Data files: https://algs4.cs.princeton.edu/32bst/tinyST.txt * * A symbol table implemented with a binary search tree. * * % more tinyST.txt * S E A R C H E X A M P L E * * % java BST < tinyST.txt * A 8 * C 4 * E 12 * H 5 * L 11 * M 9 * P 10 * R 3 * S 0 * X 7 * ******************************************************************************/ import java.util.NoSuchElementException; /** * The {@code BST} class represents an ordered symbol table of generic * key-value pairs. * It supports the usual <em>put</em>, <em>get</em>, <em>contains</em>, * <em>delete</em>, <em>size</em>, and <em>is-empty</em> methods. * It also provides ordered methods for finding the <em>minimum</em>, * <em>maximum</em>, <em>floor</em>, <em>select</em>, <em>ceiling</em>. * It also provides a <em>keys</em> method for iterating over all of the keys. * A symbol table implements the <em>associative array</em> abstraction: * when associating a value with a key that is already in the symbol table, * the convention is to replace the old value with the new value. * Unlike {@link java.util.Map}, this class uses the convention that * values cannot be {@code null}—setting the * value associated with a key to {@code null} is equivalent to deleting the key * from the symbol table. * <p> * It requires that * the key type implements the {@code Comparable} interface and calls the * {@code compareTo()} and method to compare two keys. It does not call either * {@code equals()} or {@code hashCode()}. * <p> * This implementation uses an (unbalanced) <em>binary search tree</em>. * The <em>put</em>, <em>contains</em>, <em>remove</em>, <em>minimum</em>, * <em>maximum</em>, <em>ceiling</em>, <em>floor</em>, <em>select</em>, and * <em>rank</em> operations each take &Theta;(<em>n</em>) time in the worst * case, where <em>n</em> is the number of key-value pairs. * The <em>size</em> and <em>is-empty</em> operations take &Theta;(1) time. * The keys method takes &Theta;(<em>n</em>) time in the worst case. * Construction takes &Theta;(1) time. * <p> * For alternative implementations of the symbol table API, see {@link ST}, * {@link BinarySearchST}, {@link SequentialSearchST}, {@link RedBlackBST}, * {@link SeparateChainingHashST}, and {@link LinearProbingHashST}, * For additional documentation, see * <a href="https://algs4.cs.princeton.edu/32bst">Section 3.2</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class BST<Key extends Comparable<Key>, Value> { private Node root; // root of BST private class Node { private Key key; // sorted by key private Value val; // associated data private Node left, right; // left and right subtrees private int size; // number of nodes in subtree public Node(Key key, Value val, int size) { this.key = key; this.val = val; this.size = size; } } /** * Initializes an empty symbol table. */ public BST() { } /** * Returns true if this symbol table is empty. * @return {@code true} if this symbol table is empty; {@code false} otherwise */ public boolean isEmpty() { return size() == 0; } /** * Returns the number of key-value pairs in this symbol table. * @return the number of key-value pairs in this symbol table */ public int size() { return size(root); } // return number of key-value pairs in BST rooted at x private int size(Node node) { if (node == null) return 0; else return node.size; } /** * Does this symbol table contain the given key? * * @param key the key * @return {@code true} if this symbol table contains {@code key} and * {@code false} otherwise * @throws IllegalArgumentException if {@code key} is {@code null} */ public boolean contains(Key key) { if (key == null) throw new IllegalArgumentException("argument to contains() is null"); return get(key) != null; } /** * Returns the value associated with the given key. * * @param key the key * @return the value associated with the given key if the key is in the symbol table * and {@code null} if the key is not in the symbol table * @throws IllegalArgumentException if {@code key} is {@code null} */ public Value get(Key key) { return get(root, key); } private Value get(Node node, Key key) { if (key == null) throw new IllegalArgumentException("calls get() with a null key"); if (node == null) return null; int cmp = key.compareTo(node.key); if (cmp < 0) return get(node.left, key); else if (cmp > 0) return get(node.right, key); else return node.val; } /** * Inserts the specified key-value pair into the symbol table, overwriting the old * value with the new value if the symbol table already contains the specified key. * Deletes the specified key (and its associated value) from this symbol table * if the specified value is {@code null}. * * @param key the key * @param val the value * @throws IllegalArgumentException if {@code key} is {@code null} */ public void put(Key key, Value val) { if (key == null) throw new IllegalArgumentException("calls put() with a null key"); if (val == null) { delete(key); return; } root = put(root, key, val); assert check(); } private Node put(Node node, Key key, Value val) { if (node == null) return new Node(key, val, 1); int cmp = key.compareTo(node.key); if (cmp < 0) node.left = put(node.left, key, val); else if (cmp > 0) node.right = put(node.right, key, val); else node.val = val; node.size = 1 + size(node.left) + size(node.right); return node; } /** * Removes the smallest key and associated value from the symbol table. * * @throws NoSuchElementException if the symbol table is empty */ public void deleteMin() { if (isEmpty()) throw new NoSuchElementException("Symbol table underflow"); root = deleteMin(root); assert check(); } private Node deleteMin(Node node) { if (node.left == null) return node.right; node.left = deleteMin(node.left); node.size = size(node.left) + size(node.right) + 1; return node; } /** * Removes the largest key and associated value from the symbol table. * * @throws NoSuchElementException if the symbol table is empty */ public void deleteMax() { if (isEmpty()) throw new NoSuchElementException("Symbol table underflow"); root = deleteMax(root); assert check(); } private Node deleteMax(Node node) { if (node.right == null) return node.left; node.right = deleteMax(node.right); node.size = size(node.left) + size(node.right) + 1; return node; } /** * Removes the specified key and its associated value from this symbol table * (if the key is in this symbol table). * * @param key the key * @throws IllegalArgumentException if {@code key} is {@code null} */ public void delete(Key key) { if (key == null) throw new IllegalArgumentException("calls delete() with a null key"); root = delete(root, key); assert check(); } private Node delete(Node node, Key key) { if (node == null) return null; int cmp = key.compareTo(node.key); if (cmp < 0) node.left = delete(node.left, key); else if (cmp > 0) node.right = delete(node.right, key); else { if (node.right == null) return node.left; if (node.left == null) return node.right; Node temp = node; node = min(temp.right); node.right = deleteMin(temp.right); node.left = temp.left; } node.size = size(node.left) + size(node.right) + 1; return node; } /** * Returns the smallest key in the symbol table. * * @return the smallest key in the symbol table * @throws NoSuchElementException if the symbol table is empty */ public Key min() { if (isEmpty()) throw new NoSuchElementException("calls min() with empty symbol table"); return min(root).key; } private Node min(Node node) { if (node.left == null) return node; else return min(node.left); } /** * Returns the largest key in the symbol table. * * @return the largest key in the symbol table * @throws NoSuchElementException if the symbol table is empty */ public Key max() { if (isEmpty()) throw new NoSuchElementException("calls max() with empty symbol table"); return max(root).key; } private Node max(Node node) { if (node.right == null) return node; else return max(node.right); } /** * Returns the largest key in the symbol table less than or equal to {@code key}. * * @param key the key * @return the largest key in the symbol table less than or equal to {@code key} * @throws NoSuchElementException if there is no such key * @throws IllegalArgumentException if {@code key} is {@code null} */ public Key floor(Key key) { if (key == null) throw new IllegalArgumentException("argument to floor() is null"); if (isEmpty()) throw new NoSuchElementException("calls floor() with empty symbol table"); Node node = floor(root, key); if (node == null) throw new NoSuchElementException("argument to floor() is too small"); else return node.key; } private Node floor(Node node, Key key) { if (node == null) return null; int cmp = key.compareTo(node.key); if (cmp == 0) return node; if (cmp < 0) return floor(node.left, key); Node t = floor(node.right, key); if (t != null) return t; else return node; } public Key floor2(Key key) { Key floor = floor2(root, key, null); if (floor == null) throw new NoSuchElementException("argument to floor() is too small"); else return floor; } private Key floor2(Node node, Key key, Key champ) { if (node == null) return champ; int cmp = key.compareTo(node.key); if (cmp < 0) return floor2(node.left, key, champ); else if (cmp > 0) return floor2(node.right, key, node.key); else return node.key; } /** * Returns the smallest key in the symbol table greater than or equal to {@code key}. * * @param key the key * @return the smallest key in the symbol table greater than or equal to {@code key} * @throws NoSuchElementException if there is no such key * @throws IllegalArgumentException if {@code key} is {@code null} */ public Key ceiling(Key key) { if (key == null) throw new IllegalArgumentException("argument to ceiling() is null"); if (isEmpty()) throw new NoSuchElementException("calls ceiling() with empty symbol table"); Node node = ceiling(root, key); if (node == null) throw new NoSuchElementException("argument to ceiling() is too large"); else return node.key; } private Node ceiling(Node node, Key key) { if (node == null) return null; int cmp = key.compareTo(node.key); if (cmp == 0) return node; if (cmp < 0) { Node t = ceiling(node.left, key); if (t != null) return t; else return node; } return ceiling(node.right, key); } /** * Return the key in the symbol table of a given {@code rank}. * This key has the property that there are {@code rank} keys in * the symbol table that are smaller. In other words, this key is the * ({@code rank}+1)st smallest key in the symbol table. * * @param rank the order statistic * @return the key in the symbol table of given {@code rank} * @throws IllegalArgumentException unless {@code rank} is between 0 and * <em>n</em>–1 */ public Key select(int rank) { if (rank < 0 || rank >= size()) { throw new IllegalArgumentException("argument to select() is invalid: " + rank); } return select(root, rank); } // Return key in BST rooted at x of given rank. // Precondition: rank is in legal range. private Key select(Node node, int rank) { if (node == null) return null; int leftSize = size(node.left); if (leftSize > rank) return select(node.left, rank); else if (leftSize < rank) return select(node.right, rank - leftSize - 1); else return node.key; } /** * Return the number of keys in the symbol table strictly less than {@code key}. * * @param key the key * @return the number of keys in the symbol table strictly less than {@code key} * @throws IllegalArgumentException if {@code key} is {@code null} */ public int rank(Key key) { if (key == null) throw new IllegalArgumentException("argument to rank() is null"); return rank(key, root); } // Number of keys in the subtree less than key. private int rank(Key key, Node node) { if (node == null) return 0; int cmp = key.compareTo(node.key); if (cmp < 0) return rank(key, node.left); else if (cmp > 0) return 1 + size(node.left) + rank(key, node.right); else return size(node.left); } /** * Returns all keys in the symbol table in ascending order, * as an {@code Iterable}. * To iterate over all of the keys in the symbol table named {@code st}, * use the foreach notation: {@code for (Key key : st.keys())}. * * @return all keys in the symbol table in ascending order */ public Iterable<Key> keys() { if (isEmpty()) return new Queue<Key>(); return keys(min(), max()); } /** * Returns all keys in the symbol table in the given range * in ascending order, as an {@code Iterable}. * * @param lo minimum endpoint * @param hi maximum endpoint * @return all keys in the symbol table between {@code lo} * (inclusive) and {@code hi} (inclusive) in ascending order * @throws IllegalArgumentException if either {@code lo} or {@code hi} * is {@code null} */ public Iterable<Key> keys(Key lo, Key hi) { if (lo == null) throw new IllegalArgumentException("first argument to keys() is null"); if (hi == null) throw new IllegalArgumentException("second argument to keys() is null"); Queue<Key> queue = new Queue<Key>(); keys(root, queue, lo, hi); return queue; } private void keys(Node node, Queue<Key> queue, Key lo, Key hi) { if (node == null) return; int cmplo = lo.compareTo(node.key); int cmphi = hi.compareTo(node.key); if (cmplo < 0) keys(node.left, queue, lo, hi); if (cmplo <= 0 && cmphi >= 0) queue.enqueue(node.key); if (cmphi > 0) keys(node.right, queue, lo, hi); } /** * Returns the number of keys in the symbol table in the given range. * * @param lo minimum endpoint * @param hi maximum endpoint * @return the number of keys in the symbol table between {@code lo} * (inclusive) and {@code hi} (inclusive) * @throws IllegalArgumentException if either {@code lo} or {@code hi} * is {@code null} */ public int size(Key lo, Key hi) { if (lo == null) throw new IllegalArgumentException("first argument to size() is null"); if (hi == null) throw new IllegalArgumentException("second argument to size() is null"); if (lo.compareTo(hi) > 0) return 0; if (contains(hi)) return rank(hi) - rank(lo) + 1; else return rank(hi) - rank(lo); } /** * Returns the height of the BST (for debugging). * * @return the height of the BST (a 1-node tree has height 0) */ public int height() { return height(root); } private int height(Node node) { if (node == null) return -1; return 1 + Math.max(height(node.left), height(node.right)); } /** * Returns the keys in the BST in level order (for debugging). * * @return the keys in the BST in level order traversal */ public Iterable<Key> levelOrder() { Queue<Key> keys = new Queue<Key>(); Queue<Node> queue = new Queue<Node>(); queue.enqueue(root); while (!queue.isEmpty()) { Node node = queue.dequeue(); if (node == null) continue; keys.enqueue(node.key); queue.enqueue(node.left); queue.enqueue(node.right); } return keys; } /************************************************************************* * Check integrity of BST data structure. ***************************************************************************/ private boolean check() { if (!isBST()) StdOut.println("Not in symmetric order"); if (!isSizeConsistent()) StdOut.println("Subtree counts not consistent"); if (!isRankConsistent()) StdOut.println("Ranks not consistent"); return isBST() && isSizeConsistent() && isRankConsistent(); } // does this binary tree satisfy symmetric order? // Note: this test also ensures that data structure is a binary tree since order is strict private boolean isBST() { return isBST(root, null, null); } // is the tree rooted at x a BST with all keys strictly between min and max // (if min or max is null, treat as empty constraint) // Credit: elegant solution due to Bob Dondero private boolean isBST(Node node, Key min, Key max) { if (node == null) return true; if (min != null && node.key.compareTo(min) <= 0) return false; if (max != null && node.key.compareTo(max) >= 0) return false; return isBST(node.left, min, node.key) && isBST(node.right, node.key, max); } // are the size fields correct? private boolean isSizeConsistent() { return isSizeConsistent(root); } private boolean isSizeConsistent(Node node) { if (node == null) return true; if (node.size != size(node.left) + size(node.right) + 1) return false; return isSizeConsistent(node.left) && isSizeConsistent(node.right); } // check that ranks are consistent private boolean isRankConsistent() { for (int i = 0; i < size(); i++) if (i != rank(select(i))) return false; for (Key key : keys()) if (key.compareTo(select(rank(key))) != 0) return false; return true; } /** * Unit tests the {@code BST} data type. * * @param args the command-line arguments */ public static void main(String[] args) { BST<String, Integer> st = new BST<String, Integer>(); for (int i = 0; !StdIn.isEmpty(); i++) { String key = StdIn.readString(); st.put(key, i); } for (String s : st.levelOrder()) StdOut.println(s + " " + st.get(s)); StdOut.println(); for (String s : st.keys()) StdOut.println(s + " " + st.get(s)); } }
[ "https://algs4.cs.princeton.edu/32bst/tinyST.txt" ]
{ "number": "3.2.32", "code_execution": true, "url": "https://algs4.cs.princeton.edu/32bst/BST.java", "params": [ "< tinyST.txt" ], "dependencies": [ "StdIn.java", "StdOut.java", "Queue.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Select/rank check. Write a method isRankConsistent() in BST.java that checks, for all i from 0 to size() - 1 , whether i is equal to rank(select(i)) and, for all keys in the BST, whether key is equal to select(rank(key)) .
/****************************************************************************** * Compilation: javac BST.java * Execution: java BST * Dependencies: StdIn.java StdOut.java Queue.java * Data files: https://algs4.cs.princeton.edu/32bst/tinyST.txt * * A symbol table implemented with a binary search tree. * * % more tinyST.txt * S E A R C H E X A M P L E * * % java BST < tinyST.txt * A 8 * C 4 * E 12 * H 5 * L 11 * M 9 * P 10 * R 3 * S 0 * X 7 * ******************************************************************************/ import java.util.NoSuchElementException; /** * The {@code BST} class represents an ordered symbol table of generic * key-value pairs. * It supports the usual <em>put</em>, <em>get</em>, <em>contains</em>, * <em>delete</em>, <em>size</em>, and <em>is-empty</em> methods. * It also provides ordered methods for finding the <em>minimum</em>, * <em>maximum</em>, <em>floor</em>, <em>select</em>, <em>ceiling</em>. * It also provides a <em>keys</em> method for iterating over all of the keys. * A symbol table implements the <em>associative array</em> abstraction: * when associating a value with a key that is already in the symbol table, * the convention is to replace the old value with the new value. * Unlike {@link java.util.Map}, this class uses the convention that * values cannot be {@code null}—setting the * value associated with a key to {@code null} is equivalent to deleting the key * from the symbol table. * <p> * It requires that * the key type implements the {@code Comparable} interface and calls the * {@code compareTo()} and method to compare two keys. It does not call either * {@code equals()} or {@code hashCode()}. * <p> * This implementation uses an (unbalanced) <em>binary search tree</em>. * The <em>put</em>, <em>contains</em>, <em>remove</em>, <em>minimum</em>, * <em>maximum</em>, <em>ceiling</em>, <em>floor</em>, <em>select</em>, and * <em>rank</em> operations each take &Theta;(<em>n</em>) time in the worst * case, where <em>n</em> is the number of key-value pairs. * The <em>size</em> and <em>is-empty</em> operations take &Theta;(1) time. * The keys method takes &Theta;(<em>n</em>) time in the worst case. * Construction takes &Theta;(1) time. * <p> * For alternative implementations of the symbol table API, see {@link ST}, * {@link BinarySearchST}, {@link SequentialSearchST}, {@link RedBlackBST}, * {@link SeparateChainingHashST}, and {@link LinearProbingHashST}, * For additional documentation, see * <a href="https://algs4.cs.princeton.edu/32bst">Section 3.2</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class BST<Key extends Comparable<Key>, Value> { private Node root; // root of BST private class Node { private Key key; // sorted by key private Value val; // associated data private Node left, right; // left and right subtrees private int size; // number of nodes in subtree public Node(Key key, Value val, int size) { this.key = key; this.val = val; this.size = size; } } /** * Initializes an empty symbol table. */ public BST() { } /** * Returns true if this symbol table is empty. * @return {@code true} if this symbol table is empty; {@code false} otherwise */ public boolean isEmpty() { return size() == 0; } /** * Returns the number of key-value pairs in this symbol table. * @return the number of key-value pairs in this symbol table */ public int size() { return size(root); } // return number of key-value pairs in BST rooted at x private int size(Node node) { if (node == null) return 0; else return node.size; } /** * Does this symbol table contain the given key? * * @param key the key * @return {@code true} if this symbol table contains {@code key} and * {@code false} otherwise * @throws IllegalArgumentException if {@code key} is {@code null} */ public boolean contains(Key key) { if (key == null) throw new IllegalArgumentException("argument to contains() is null"); return get(key) != null; } /** * Returns the value associated with the given key. * * @param key the key * @return the value associated with the given key if the key is in the symbol table * and {@code null} if the key is not in the symbol table * @throws IllegalArgumentException if {@code key} is {@code null} */ public Value get(Key key) { return get(root, key); } private Value get(Node node, Key key) { if (key == null) throw new IllegalArgumentException("calls get() with a null key"); if (node == null) return null; int cmp = key.compareTo(node.key); if (cmp < 0) return get(node.left, key); else if (cmp > 0) return get(node.right, key); else return node.val; } /** * Inserts the specified key-value pair into the symbol table, overwriting the old * value with the new value if the symbol table already contains the specified key. * Deletes the specified key (and its associated value) from this symbol table * if the specified value is {@code null}. * * @param key the key * @param val the value * @throws IllegalArgumentException if {@code key} is {@code null} */ public void put(Key key, Value val) { if (key == null) throw new IllegalArgumentException("calls put() with a null key"); if (val == null) { delete(key); return; } root = put(root, key, val); assert check(); } private Node put(Node node, Key key, Value val) { if (node == null) return new Node(key, val, 1); int cmp = key.compareTo(node.key); if (cmp < 0) node.left = put(node.left, key, val); else if (cmp > 0) node.right = put(node.right, key, val); else node.val = val; node.size = 1 + size(node.left) + size(node.right); return node; } /** * Removes the smallest key and associated value from the symbol table. * * @throws NoSuchElementException if the symbol table is empty */ public void deleteMin() { if (isEmpty()) throw new NoSuchElementException("Symbol table underflow"); root = deleteMin(root); assert check(); } private Node deleteMin(Node node) { if (node.left == null) return node.right; node.left = deleteMin(node.left); node.size = size(node.left) + size(node.right) + 1; return node; } /** * Removes the largest key and associated value from the symbol table. * * @throws NoSuchElementException if the symbol table is empty */ public void deleteMax() { if (isEmpty()) throw new NoSuchElementException("Symbol table underflow"); root = deleteMax(root); assert check(); } private Node deleteMax(Node node) { if (node.right == null) return node.left; node.right = deleteMax(node.right); node.size = size(node.left) + size(node.right) + 1; return node; } /** * Removes the specified key and its associated value from this symbol table * (if the key is in this symbol table). * * @param key the key * @throws IllegalArgumentException if {@code key} is {@code null} */ public void delete(Key key) { if (key == null) throw new IllegalArgumentException("calls delete() with a null key"); root = delete(root, key); assert check(); } private Node delete(Node node, Key key) { if (node == null) return null; int cmp = key.compareTo(node.key); if (cmp < 0) node.left = delete(node.left, key); else if (cmp > 0) node.right = delete(node.right, key); else { if (node.right == null) return node.left; if (node.left == null) return node.right; Node temp = node; node = min(temp.right); node.right = deleteMin(temp.right); node.left = temp.left; } node.size = size(node.left) + size(node.right) + 1; return node; } /** * Returns the smallest key in the symbol table. * * @return the smallest key in the symbol table * @throws NoSuchElementException if the symbol table is empty */ public Key min() { if (isEmpty()) throw new NoSuchElementException("calls min() with empty symbol table"); return min(root).key; } private Node min(Node node) { if (node.left == null) return node; else return min(node.left); } /** * Returns the largest key in the symbol table. * * @return the largest key in the symbol table * @throws NoSuchElementException if the symbol table is empty */ public Key max() { if (isEmpty()) throw new NoSuchElementException("calls max() with empty symbol table"); return max(root).key; } private Node max(Node node) { if (node.right == null) return node; else return max(node.right); } /** * Returns the largest key in the symbol table less than or equal to {@code key}. * * @param key the key * @return the largest key in the symbol table less than or equal to {@code key} * @throws NoSuchElementException if there is no such key * @throws IllegalArgumentException if {@code key} is {@code null} */ public Key floor(Key key) { if (key == null) throw new IllegalArgumentException("argument to floor() is null"); if (isEmpty()) throw new NoSuchElementException("calls floor() with empty symbol table"); Node node = floor(root, key); if (node == null) throw new NoSuchElementException("argument to floor() is too small"); else return node.key; } private Node floor(Node node, Key key) { if (node == null) return null; int cmp = key.compareTo(node.key); if (cmp == 0) return node; if (cmp < 0) return floor(node.left, key); Node t = floor(node.right, key); if (t != null) return t; else return node; } public Key floor2(Key key) { Key floor = floor2(root, key, null); if (floor == null) throw new NoSuchElementException("argument to floor() is too small"); else return floor; } private Key floor2(Node node, Key key, Key champ) { if (node == null) return champ; int cmp = key.compareTo(node.key); if (cmp < 0) return floor2(node.left, key, champ); else if (cmp > 0) return floor2(node.right, key, node.key); else return node.key; } /** * Returns the smallest key in the symbol table greater than or equal to {@code key}. * * @param key the key * @return the smallest key in the symbol table greater than or equal to {@code key} * @throws NoSuchElementException if there is no such key * @throws IllegalArgumentException if {@code key} is {@code null} */ public Key ceiling(Key key) { if (key == null) throw new IllegalArgumentException("argument to ceiling() is null"); if (isEmpty()) throw new NoSuchElementException("calls ceiling() with empty symbol table"); Node node = ceiling(root, key); if (node == null) throw new NoSuchElementException("argument to ceiling() is too large"); else return node.key; } private Node ceiling(Node node, Key key) { if (node == null) return null; int cmp = key.compareTo(node.key); if (cmp == 0) return node; if (cmp < 0) { Node t = ceiling(node.left, key); if (t != null) return t; else return node; } return ceiling(node.right, key); } /** * Return the key in the symbol table of a given {@code rank}. * This key has the property that there are {@code rank} keys in * the symbol table that are smaller. In other words, this key is the * ({@code rank}+1)st smallest key in the symbol table. * * @param rank the order statistic * @return the key in the symbol table of given {@code rank} * @throws IllegalArgumentException unless {@code rank} is between 0 and * <em>n</em>–1 */ public Key select(int rank) { if (rank < 0 || rank >= size()) { throw new IllegalArgumentException("argument to select() is invalid: " + rank); } return select(root, rank); } // Return key in BST rooted at x of given rank. // Precondition: rank is in legal range. private Key select(Node node, int rank) { if (node == null) return null; int leftSize = size(node.left); if (leftSize > rank) return select(node.left, rank); else if (leftSize < rank) return select(node.right, rank - leftSize - 1); else return node.key; } /** * Return the number of keys in the symbol table strictly less than {@code key}. * * @param key the key * @return the number of keys in the symbol table strictly less than {@code key} * @throws IllegalArgumentException if {@code key} is {@code null} */ public int rank(Key key) { if (key == null) throw new IllegalArgumentException("argument to rank() is null"); return rank(key, root); } // Number of keys in the subtree less than key. private int rank(Key key, Node node) { if (node == null) return 0; int cmp = key.compareTo(node.key); if (cmp < 0) return rank(key, node.left); else if (cmp > 0) return 1 + size(node.left) + rank(key, node.right); else return size(node.left); } /** * Returns all keys in the symbol table in ascending order, * as an {@code Iterable}. * To iterate over all of the keys in the symbol table named {@code st}, * use the foreach notation: {@code for (Key key : st.keys())}. * * @return all keys in the symbol table in ascending order */ public Iterable<Key> keys() { if (isEmpty()) return new Queue<Key>(); return keys(min(), max()); } /** * Returns all keys in the symbol table in the given range * in ascending order, as an {@code Iterable}. * * @param lo minimum endpoint * @param hi maximum endpoint * @return all keys in the symbol table between {@code lo} * (inclusive) and {@code hi} (inclusive) in ascending order * @throws IllegalArgumentException if either {@code lo} or {@code hi} * is {@code null} */ public Iterable<Key> keys(Key lo, Key hi) { if (lo == null) throw new IllegalArgumentException("first argument to keys() is null"); if (hi == null) throw new IllegalArgumentException("second argument to keys() is null"); Queue<Key> queue = new Queue<Key>(); keys(root, queue, lo, hi); return queue; } private void keys(Node node, Queue<Key> queue, Key lo, Key hi) { if (node == null) return; int cmplo = lo.compareTo(node.key); int cmphi = hi.compareTo(node.key); if (cmplo < 0) keys(node.left, queue, lo, hi); if (cmplo <= 0 && cmphi >= 0) queue.enqueue(node.key); if (cmphi > 0) keys(node.right, queue, lo, hi); } /** * Returns the number of keys in the symbol table in the given range. * * @param lo minimum endpoint * @param hi maximum endpoint * @return the number of keys in the symbol table between {@code lo} * (inclusive) and {@code hi} (inclusive) * @throws IllegalArgumentException if either {@code lo} or {@code hi} * is {@code null} */ public int size(Key lo, Key hi) { if (lo == null) throw new IllegalArgumentException("first argument to size() is null"); if (hi == null) throw new IllegalArgumentException("second argument to size() is null"); if (lo.compareTo(hi) > 0) return 0; if (contains(hi)) return rank(hi) - rank(lo) + 1; else return rank(hi) - rank(lo); } /** * Returns the height of the BST (for debugging). * * @return the height of the BST (a 1-node tree has height 0) */ public int height() { return height(root); } private int height(Node node) { if (node == null) return -1; return 1 + Math.max(height(node.left), height(node.right)); } /** * Returns the keys in the BST in level order (for debugging). * * @return the keys in the BST in level order traversal */ public Iterable<Key> levelOrder() { Queue<Key> keys = new Queue<Key>(); Queue<Node> queue = new Queue<Node>(); queue.enqueue(root); while (!queue.isEmpty()) { Node node = queue.dequeue(); if (node == null) continue; keys.enqueue(node.key); queue.enqueue(node.left); queue.enqueue(node.right); } return keys; } /************************************************************************* * Check integrity of BST data structure. ***************************************************************************/ private boolean check() { if (!isBST()) StdOut.println("Not in symmetric order"); if (!isSizeConsistent()) StdOut.println("Subtree counts not consistent"); if (!isRankConsistent()) StdOut.println("Ranks not consistent"); return isBST() && isSizeConsistent() && isRankConsistent(); } // does this binary tree satisfy symmetric order? // Note: this test also ensures that data structure is a binary tree since order is strict private boolean isBST() { return isBST(root, null, null); } // is the tree rooted at x a BST with all keys strictly between min and max // (if min or max is null, treat as empty constraint) // Credit: elegant solution due to Bob Dondero private boolean isBST(Node node, Key min, Key max) { if (node == null) return true; if (min != null && node.key.compareTo(min) <= 0) return false; if (max != null && node.key.compareTo(max) >= 0) return false; return isBST(node.left, min, node.key) && isBST(node.right, node.key, max); } // are the size fields correct? private boolean isSizeConsistent() { return isSizeConsistent(root); } private boolean isSizeConsistent(Node node) { if (node == null) return true; if (node.size != size(node.left) + size(node.right) + 1) return false; return isSizeConsistent(node.left) && isSizeConsistent(node.right); } // check that ranks are consistent private boolean isRankConsistent() { for (int i = 0; i < size(); i++) if (i != rank(select(i))) return false; for (Key key : keys()) if (key.compareTo(select(rank(key))) != 0) return false; return true; } /** * Unit tests the {@code BST} data type. * * @param args the command-line arguments */ public static void main(String[] args) { BST<String, Integer> st = new BST<String, Integer>(); for (int i = 0; !StdIn.isEmpty(); i++) { String key = StdIn.readString(); st.put(key, i); } for (String s : st.levelOrder()) StdOut.println(s + " " + st.get(s)); StdOut.println(); for (String s : st.keys()) StdOut.println(s + " " + st.get(s)); } }
[ "https://algs4.cs.princeton.edu/32bst/tinyST.txt" ]
{ "number": "3.2.33", "code_execution": true, "url": "https://algs4.cs.princeton.edu/32bst/BST.java", "params": [ "< tinyST.txt" ], "dependencies": [ "StdIn.java", "StdOut.java", "Queue.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Create a copy constructor for Graph.java that takes as input a graph G and creates and initializes a new copy of the graph. Any changes a client makes to G should not affect the newly created graph.
/****************************************************************************** * Compilation: javac Graph.java * Execution: java Graph input.txt * Dependencies: Bag.java Stack.java In.java StdOut.java * Data files: https://algs4.cs.princeton.edu/41graph/tinyG.txt * https://algs4.cs.princeton.edu/41graph/mediumG.txt * https://algs4.cs.princeton.edu/41graph/largeG.txt * * A graph, implemented using an array of sets. * Parallel edges and self-loops allowed. * * % java Graph tinyG.txt * 13 vertices, 13 edges * 0: 6 2 1 5 * 1: 0 * 2: 0 * 3: 5 4 * 4: 5 6 3 * 5: 3 4 0 * 6: 0 4 * 7: 8 * 8: 7 * 9: 11 10 12 * 10: 9 * 11: 9 12 * 12: 11 9 * * % java Graph mediumG.txt * 250 vertices, 1273 edges * 0: 225 222 211 209 204 202 191 176 163 160 149 114 97 80 68 59 58 49 44 24 15 * 1: 220 203 200 194 189 164 150 130 107 72 * 2: 141 110 108 86 79 51 42 18 14 * ... * ******************************************************************************/ import java.util.NoSuchElementException; /** * The {@code Graph} class represents an undirected graph of vertices * named 0 through <em>V</em> – 1. * It supports the following two primary operations: add an edge to the graph, * iterate over all of the vertices adjacent with a given vertex. It also provides * methods for returning the degree of a vertex, the number of vertices * <em>V</em> in the graph, and the number of edges <em>E</em> in the graph. * Parallel edges and self-loops are permitted. * By convention, a self-loop <em>v</em>-<em>v</em> appears in the * adjacency list of <em>v</em> twice and contributes two to the degree * of <em>v</em>. * <p> * This implementation uses an <em>adjacency-lists representation</em>, which * is a vertex-indexed array of {@link Bag} objects. * It uses &Theta;(<em>E</em> + <em>V</em>) space, where <em>E</em> is * the number of edges and <em>V</em> is the number of vertices. * All instance methods take &Theta;(1) time. (Though, iterating over * the vertices returned by {@link #adj(int)} takes time proportional * to the degree of the vertex.) * Constructing an empty graph with <em>V</em> vertices takes * &Theta;(<em>V</em>) time; constructing a graph with <em>E</em> edges * and <em>V</em> vertices takes &Theta;(<em>E</em> + <em>V</em>) time. * <p> * For additional documentation, see * <a href="https://algs4.cs.princeton.edu/41graph">Section 4.1</a> * of <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class Graph { private static final String NEWLINE = System.getProperty("line.separator"); private final int V; private int E; private Bag<Integer>[] adj; /** * Initializes an empty graph with {@code V} vertices and 0 edges. * param V the number of vertices * * @param V number of vertices * @throws IllegalArgumentException if {@code V < 0} */ public Graph(int V) { if (V < 0) throw new IllegalArgumentException("Number of vertices must be non-negative"); this.V = V; this.E = 0; adj = (Bag<Integer>[]) new Bag[V]; for (int v = 0; v < V; v++) { adj[v] = new Bag<Integer>(); } } /** * Initializes a graph from the specified input stream. * The format is the number of vertices <em>V</em>, * followed by the number of edges <em>E</em>, * followed by <em>E</em> pairs of vertices, with each entry separated by whitespace. * * @param in the input stream * @throws IllegalArgumentException if {@code in} is {@code null} * @throws IllegalArgumentException if the endpoints of any edge are not in prescribed range * @throws IllegalArgumentException if the number of vertices or edges is negative * @throws IllegalArgumentException if the input stream is in the wrong format */ public Graph(In in) { if (in == null) throw new IllegalArgumentException("argument is null"); try { this.V = in.readInt(); if (V < 0) throw new IllegalArgumentException("number of vertices in a Graph must be non-negative"); adj = (Bag<Integer>[]) new Bag[V]; for (int v = 0; v < V; v++) { adj[v] = new Bag<Integer>(); } int E = in.readInt(); if (E < 0) throw new IllegalArgumentException("number of edges in a Graph must be non-negative"); for (int i = 0; i < E; i++) { int v = in.readInt(); int w = in.readInt(); validateVertex(v); validateVertex(w); addEdge(v, w); } } catch (NoSuchElementException e) { throw new IllegalArgumentException("invalid input format in Graph constructor", e); } } /** * Initializes a new graph that is a deep copy of {@code graph}. * * @param graph the graph to copy * @throws IllegalArgumentException if {@code graph} is {@code null} */ public Graph(Graph graph) { this.V = graph.V(); this.E = graph.E(); if (V < 0) throw new IllegalArgumentException("Number of vertices must be non-negative"); // update adjacency lists adj = (Bag<Integer>[]) new Bag[V]; for (int v = 0; v < V; v++) { adj[v] = new Bag<Integer>(); } for (int v = 0; v < graph.V(); v++) { // reverse so that adjacency list is in same order as original Stack<Integer> reverse = new Stack<Integer>(); for (int w : graph.adj[v]) { reverse.push(w); } for (int w : reverse) { adj[v].add(w); } } } /** * Returns the number of vertices in this graph. * * @return the number of vertices in this graph */ public int V() { return V; } /** * Returns the number of edges in this graph. * * @return the number of edges in this graph */ public int E() { return E; } // throw an IllegalArgumentException unless {@code 0 <= v < V} private void validateVertex(int v) { if (v < 0 || v >= V) throw new IllegalArgumentException("vertex " + v + " is not between 0 and " + (V-1)); } /** * Adds the undirected edge v-w to this graph. * * @param v one vertex in the edge * @param w the other vertex in the edge * @throws IllegalArgumentException unless both {@code 0 <= v < V} and {@code 0 <= w < V} */ public void addEdge(int v, int w) { validateVertex(v); validateVertex(w); E++; adj[v].add(w); adj[w].add(v); } /** * Returns the vertices adjacent with vertex {@code v}. * * @param v the vertex * @return the vertices adjacent with vertex {@code v}, as an iterable * @throws IllegalArgumentException unless {@code 0 <= v < V} */ public Iterable<Integer> adj(int v) { validateVertex(v); return adj[v]; } /** * Returns the degree of vertex {@code v}. * * @param v the vertex * @return the degree of vertex {@code v} * @throws IllegalArgumentException unless {@code 0 <= v < V} */ public int degree(int v) { validateVertex(v); return adj[v].size(); } /** * Returns a string representation of this graph. * * @return the number of vertices <em>V</em>, followed by the number of edges <em>E</em>, * followed by the <em>V</em> adjacency lists */ public String toString() { StringBuilder s = new StringBuilder(); s.append(V + " vertices, " + E + " edges " + NEWLINE); for (int v = 0; v < V; v++) { s.append(v + ": "); for (int w : adj[v]) { s.append(w + " "); } s.append(NEWLINE); } return s.toString(); } /** * Returns a string representation of this graph in DOT format, * suitable for visualization with Graphviz. * * To visualize the graph, install Graphviz (e.g., "brew install graphviz"). * Then use one of the graph visualization tools * - dot (hierarchical or layer drawing) * - neato (spring model) * - fdp (force-directed placement) * - sfdp (scalable force-directed placement) * - twopi (radial layout) * * For example, the following commands will create graph drawings in SVG * and PDF formats * - dot input.dot -Tsvg -o output.svg * - dot input.dot -Tpdf -o output.pdf * * To change the graph attributes (e.g., vertex and edge shapes, arrows, colors) * in the DOT format, see https://graphviz.org/doc/info/lang.html * * @return a string representation of this graph in DOT format */ public String toDot() { StringBuilder s = new StringBuilder(); s.append("graph {" + NEWLINE); s.append("node[shape=circle, style=filled, fixedsize=true, width=0.3, fontsize=\"10pt\"]" + NEWLINE); int selfLoops = 0; for (int v = 0; v < V; v++) { for (int w : adj[v]) { if (v < w) { s.append(v + " -- " + w + NEWLINE); } else if (v == w) { // include only one copy of each self loop (self loops will be consecutive) if (selfLoops % 2 == 0) { s.append(v + " -- " + w + NEWLINE); } selfLoops++; } } } s.append("}" + NEWLINE); return s.toString(); } /** * Unit tests the {@code Graph} data type. * * @param args the command-line arguments */ public static void main(String[] args) { In in = new In(args[0]); Graph graph = new Graph(in); StdOut.println(graph); } }
[ "https://algs4.cs.princeton.edu/41graph/mediumG.txt", "https://algs4.cs.princeton.edu/41graph/largeG.txt", "https://algs4.cs.princeton.edu/41graph/tinyG.txt" ]
{ "number": "4.1.3", "code_execution": true, "url": "https://algs4.cs.princeton.edu/41graph/Graph.java", "params": [ "mediumG.txt", "tinyG.txt" ], "dependencies": [ "Bag.java", "Stack.java", "In.java", "StdOut.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Add a distTo() method to BreadthFirstPaths.java, which returns the number of edges on the shortest path from the source to a given vertex. A distTo() query should run in constant time.
/****************************************************************************** * Compilation: javac BreadthFirstPaths.java * Execution: java BreadthFirstPaths G s * Dependencies: Graph.java Queue.java Stack.java StdOut.java * Data files: https://algs4.cs.princeton.edu/41graph/tinyCG.txt * https://algs4.cs.princeton.edu/41graph/tinyG.txt * https://algs4.cs.princeton.edu/41graph/mediumG.txt * https://algs4.cs.princeton.edu/41graph/largeG.txt * * Run breadth first search on an undirected graph. * Runs in O(E + V) time. * * % java Graph tinyCG.txt * 6 8 * 0: 2 1 5 * 1: 0 2 * 2: 0 1 3 4 * 3: 5 4 2 * 4: 3 2 * 5: 3 0 * * % java BreadthFirstPaths tinyCG.txt 0 * 0 to 0 (0): 0 * 0 to 1 (1): 0-1 * 0 to 2 (1): 0-2 * 0 to 3 (2): 0-2-3 * 0 to 4 (2): 0-2-4 * 0 to 5 (1): 0-5 * * % java BreadthFirstPaths largeG.txt 0 * 0 to 0 (0): 0 * 0 to 1 (418): 0-932942-474885-82707-879889-971961-... * 0 to 2 (323): 0-460790-53370-594358-780059-287921-... * 0 to 3 (168): 0-713461-75230-953125-568284-350405-... * 0 to 4 (144): 0-460790-53370-310931-440226-380102-... * 0 to 5 (566): 0-932942-474885-82707-879889-971961-... * 0 to 6 (349): 0-932942-474885-82707-879889-971961-... * ******************************************************************************/ /** * The {@code BreadthFirstPaths} class represents a data type for finding * shortest paths (number of edges) from a source vertex <em>s</em> * (or a set of source vertices) * to every other vertex in an undirected graph. * <p> * This implementation uses breadth-first search. * The constructor takes &Theta;(<em>V</em> + <em>E</em>) time in the * worst case, where <em>V</em> is the number of vertices and <em>E</em> * is the number of edges. * Each instance method takes &Theta;(1) time. * It uses &Theta;(<em>V</em>) extra space (not including the graph). * <p> * For additional documentation, * see <a href="https://algs4.cs.princeton.edu/41graph">Section 4.1</a> * of <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class BreadthFirstPaths { private static final int INFINITY = Integer.MAX_VALUE; private boolean[] marked; // marked[v] = is there an s-v path private int[] edgeTo; // edgeTo[v] = previous edge on shortest s-v path private int[] distTo; // distTo[v] = number of edges shortest s-v path /** * Computes the shortest path between the source vertex {@code s} * and every other vertex in the undirected graph {@code graph}. * @param graph the graph * @param s the source vertex * @throws IllegalArgumentException unless {@code 0 <= s < V} */ public BreadthFirstPaths(Graph graph, int s) { marked = new boolean[graph.V()]; distTo = new int[graph.V()]; edgeTo = new int[graph.V()]; validateVertex(s); bfs(graph, s); assert check(graph, s); } /** * Computes the shortest path between any one of the source vertices in {@code sources} * and every other vertex in {@code graph}. * @param graph the graph * @param sources the source vertices * @throws IllegalArgumentException if {@code sources} is {@code null} * @throws IllegalArgumentException if {@code sources} contains no vertices * @throws IllegalArgumentException unless {@code 0 <= s < V} for each vertex * {@code s} in {@code sources} */ public BreadthFirstPaths(Graph graph, Iterable<Integer> sources) { marked = new boolean[graph.V()]; distTo = new int[graph.V()]; edgeTo = new int[graph.V()]; for (int v = 0; v < graph.V(); v++) distTo[v] = INFINITY; validateVertices(sources); bfs(graph, sources); } // breadth-first search from a single source private void bfs(Graph graph, int s) { Queue<Integer> q = new Queue<Integer>(); for (int v = 0; v < graph.V(); v++) distTo[v] = INFINITY; distTo[s] = 0; marked[s] = true; q.enqueue(s); while (!q.isEmpty()) { int v = q.dequeue(); for (int w : graph.adj(v)) { if (!marked[w]) { edgeTo[w] = v; distTo[w] = distTo[v] + 1; marked[w] = true; q.enqueue(w); } } } } // breadth-first search from multiple sources private void bfs(Graph graph, Iterable<Integer> sources) { Queue<Integer> q = new Queue<Integer>(); for (int s : sources) { marked[s] = true; distTo[s] = 0; q.enqueue(s); } while (!q.isEmpty()) { int v = q.dequeue(); for (int w : graph.adj(v)) { if (!marked[w]) { edgeTo[w] = v; distTo[w] = distTo[v] + 1; marked[w] = true; q.enqueue(w); } } } } /** * Is there a path between the source vertex {@code s} (or sources) and vertex {@code v}? * @param v the vertex * @return {@code true} if there is a path, and {@code false} otherwise * @throws IllegalArgumentException unless {@code 0 <= v < V} */ public boolean hasPathTo(int v) { validateVertex(v); return marked[v]; } /** * Returns the number of edges in a shortest path between the source vertex {@code s} * (or sources) and vertex {@code v}? * @param v the vertex * @return the number of edges in such a shortest path * (or {@code Integer.MAX_VALUE} if there is no such path) * @throws IllegalArgumentException unless {@code 0 <= v < V} */ public int distTo(int v) { validateVertex(v); return distTo[v]; } /** * Returns a shortest path between the source vertex {@code s} (or sources) * and {@code v}, or {@code null} if no such path. * @param v the vertex * @return the sequence of vertices on a shortest path, as an Iterable * @throws IllegalArgumentException unless {@code 0 <= v < V} */ public Iterable<Integer> pathTo(int v) { validateVertex(v); if (!hasPathTo(v)) return null; Stack<Integer> path = new Stack<Integer>(); int x; for (x = v; distTo[x] != 0; x = edgeTo[x]) path.push(x); path.push(x); return path; } // check optimality conditions for single source private boolean check(Graph graph, int s) { // check that the distance of s = 0 if (distTo[s] != 0) { StdOut.println("distance of source " + s + " to itself = " + distTo[s]); return false; } // check that for each edge v-w dist[w] <= dist[v] + 1 // provided v is reachable from s for (int v = 0; v < graph.V(); v++) { for (int w : graph.adj(v)) { if (hasPathTo(v) != hasPathTo(w)) { StdOut.println("edge " + v + "-" + w); StdOut.println("hasPathTo(" + v + ") = " + hasPathTo(v)); StdOut.println("hasPathTo(" + w + ") = " + hasPathTo(w)); return false; } if (hasPathTo(v) && (distTo[w] > distTo[v] + 1)) { StdOut.println("edge " + v + "-" + w); StdOut.println("distTo[" + v + "] = " + distTo[v]); StdOut.println("distTo[" + w + "] = " + distTo[w]); return false; } } } // check that v = edgeTo[w] satisfies distTo[w] = distTo[v] + 1 // provided v is reachable from s for (int w = 0; w < graph.V(); w++) { if (!hasPathTo(w) || w == s) continue; int v = edgeTo[w]; if (distTo[w] != distTo[v] + 1) { StdOut.println("shortest path edge " + v + "-" + w); StdOut.println("distTo[" + v + "] = " + distTo[v]); StdOut.println("distTo[" + w + "] = " + distTo[w]); return false; } } return true; } // throw an IllegalArgumentException unless {@code 0 <= v < V} private void validateVertex(int v) { int V = marked.length; if (v < 0 || v >= V) throw new IllegalArgumentException("vertex " + v + " is not between 0 and " + (V-1)); } // throw an IllegalArgumentException if vertices is null, has zero vertices, // or has a vertex not between 0 and V-1 private void validateVertices(Iterable<Integer> vertices) { if (vertices == null) { throw new IllegalArgumentException("argument is null"); } int vertexCount = 0; for (Integer v : vertices) { vertexCount++; if (v == null) { throw new IllegalArgumentException("vertex is null"); } validateVertex(v); } if (vertexCount == 0) { throw new IllegalArgumentException("zero vertices"); } } /** * Unit tests the {@code BreadthFirstPaths} data type. * * @param args the command-line arguments */ public static void main(String[] args) { In in = new In(args[0]); Graph graph = new Graph(in); // StdOut.println(graph); int s = Integer.parseInt(args[1]); BreadthFirstPaths bfs = new BreadthFirstPaths(graph, s); for (int v = 0; v < graph.V(); v++) { if (bfs.hasPathTo(v)) { StdOut.printf("%d to %d (%d): ", s, v, bfs.distTo(v)); for (int x : bfs.pathTo(v)) { if (x == s) StdOut.print(x); else StdOut.print("-" + x); } StdOut.println(); } else { StdOut.printf("%d to %d (-): not connected", s, v); } } } }
[ "https://algs4.cs.princeton.edu/41graph/largeG.txt", "https://algs4.cs.princeton.edu/41graph/mediumG.txt", "https://algs4.cs.princeton.edu/41graph/tinyG.txt", "https://algs4.cs.princeton.edu/41graph/tinyCG.txt" ]
{ "number": "4.1.13", "code_execution": true, "url": "https://algs4.cs.princeton.edu/41graph/BreadthFirstPaths.java", "params": [ "tinyCG.txt 0", "mediumG.txt 0", "tinyG.txt 0" ], "dependencies": [ "Graph.java", "Queue.java", "Stack.java", "StdOut.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Write a program BaconHistogram.java that prints a histogram of Kevin Bacon numbers, indicating how many performers from movies.txt have a Bacon number of 0, 1, 2, 3, ... . Include a category for those who have an infinite number (not connected to Kevin Bacon).
/****************************************************************************** * Compilation: javac BaconHistogram.java * Execution: java BaconHistogram input.txt delimiter actor * Dependencies: SymbolGraph.java Graph.java In.java BreadthFirstPaths.java * Data files: https://algs4.cs.princeton.edu/41graph/movies.txt * * Reads in a data file containing movie records (a movie followed by a list * of actors appearing in that movie), and runs breadth first search to * find the shortest distance from the source (Kevin Bacon) to each other * actor and movie. After computing the Kevin Bacon numbers, the programs * prints a histogram of the number of actors with each Kevin Bacon number. * * * % java BaconHistogram movies.txt "/" "Bacon, Kevin" * 0 1 * 1 1324 * 2 70717 * 3 40862 * 4 1591 * 5 125 * Inf 0 * * Remark: hard to identify actors with infinite bacon numbers because * we can't tell whether an unreachable vertex is an actor or movie. * ******************************************************************************/ public class BaconHistogram { public static void main(String[] args) { String filename = args[0]; String delimiter = args[1]; String source = args[2]; SymbolGraph sg = new SymbolGraph(filename, delimiter); Graph G = sg.graph(); if (!sg.contains(source)) { StdOut.println(source + " not in database."); return; } // run breadth-first search from s int s = sg.indexOf(source); BreadthFirstPaths bfs = new BreadthFirstPaths(G, s); // compute histogram of Kevin Bacon numbers - 100 for infinity int MAX_BACON = 100; int[] hist = new int[MAX_BACON + 1]; for (int v = 0; v < G.V(); v++) { int bacon = Math.min(MAX_BACON, bfs.distTo(v)); hist[bacon]++; // to print actors and movies with large bacon numbers if (bacon/2 >= 7 && bacon < MAX_BACON) StdOut.printf("%d %s", bacon/2, sg.nameOf(v)); } // print out histogram - even indices are actors for (int i = 0; i < MAX_BACON; i += 2) { if (hist[i] == 0) break; StdOut.printf("%3d %8d", i/2, hist[i]); } StdOut.printf("Inf %8d", hist[MAX_BACON]); } }
[ "https://algs4.cs.princeton.edu/41graph/movies.txt" ]
{ "number": "4.1.23", "code_execution": true, "url": "https://algs4.cs.princeton.edu/41graph/BaconHistogram.java", "params": [ "movies.txt \"/\" \"Bacon, Kevin\"" ], "dependencies": [ "SymbolGraph.java", "Graph.java", "In.java", "BreadthFirstPaths.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Create a copy constructor for Digraph that takes as input a digraph G and creates and initializes a new copy of the digraph. Any changes a client makes to G should not affect the newly created digraph.
/****************************************************************************** * Compilation: javac Digraph.java * Execution: java Digraph filename.txt * Dependencies: Bag.java In.java StdOut.java * Data files: https://algs4.cs.princeton.edu/42digraph/tinyDG.txt * https://algs4.cs.princeton.edu/42digraph/mediumDG.txt * https://algs4.cs.princeton.edu/42digraph/largeDG.txt * * A graph, implemented using an array of lists. * Parallel edges and self-loops are permitted. * * % java Digraph tinyDG.txt * 13 vertices, 22 edges * 0: 5 1 * 1: * 2: 0 3 * 3: 5 2 * 4: 3 2 * 5: 4 * 6: 9 4 8 0 * 7: 6 9 * 8: 6 * 9: 11 10 * 10: 12 * 11: 4 12 * 12: 9 * ******************************************************************************/ import java.util.NoSuchElementException; /** * The {@code Digraph} class represents a directed graph of vertices * named 0 through <em>V</em> - 1. * It supports the following two primary operations: add an edge to the digraph, * iterate over all of the vertices adjacent from a given vertex. * It also provides * methods for returning the indegree or outdegree of a vertex, * the number of vertices <em>V</em> in the digraph, * the number of edges <em>E</em> in the digraph, and the reverse digraph. * Parallel edges and self-loops are permitted. * <p> * This implementation uses an <em>adjacency-lists representation</em>, which * is a vertex-indexed array of {@link Bag} objects. * It uses &Theta;(<em>E</em> + <em>V</em>) space, where <em>E</em> is * the number of edges and <em>V</em> is the number of vertices. * The <code>reverse()</code> method takes &Theta;(<em>E</em> + <em>V</em>) time * and space; all other instance methods take &Theta;(1) time. (Though, iterating over * the vertices returned by {@link #adj(int)} takes time proportional * to the outdegree of the vertex.) * Constructing an empty digraph with <em>V</em> vertices takes * &Theta;(<em>V</em>) time; constructing a digraph with <em>E</em> edges * and <em>V</em> vertices takes &Theta;(<em>E</em> + <em>V</em>) time. * <p> * For additional documentation, * see <a href="https://algs4.cs.princeton.edu/42digraph">Section 4.2</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class Digraph { private static final String NEWLINE = System.getProperty("line.separator"); private final int V; // number of vertices in this digraph private int E; // number of edges in this digraph private Bag<Integer>[] adj; // adj[v] = adjacency list for vertex v private int[] indegree; // indegree[v] = indegree of vertex v /** * Initializes an empty digraph with <em>V</em> vertices. * * @param V the number of vertices * @throws IllegalArgumentException if {@code V < 0} */ public Digraph(int V) { if (V < 0) throw new IllegalArgumentException("Number of vertices in a Digraph must be non-negative"); this.V = V; this.E = 0; indegree = new int[V]; adj = (Bag<Integer>[]) new Bag[V]; for (int v = 0; v < V; v++) { adj[v] = new Bag<Integer>(); } } /** * Initializes a digraph from the specified input stream. * The format is the number of vertices <em>V</em>, * followed by the number of edges <em>E</em>, * followed by <em>E</em> pairs of vertices, with each entry separated by whitespace. * * @param in the input stream * @throws IllegalArgumentException if {@code in} is {@code null} * @throws IllegalArgumentException if the endpoints of any edge are not in prescribed range * @throws IllegalArgumentException if the number of vertices or edges is negative * @throws IllegalArgumentException if the input stream is in the wrong format */ public Digraph(In in) { if (in == null) throw new IllegalArgumentException("argument is null"); try { this.V = in.readInt(); if (V < 0) throw new IllegalArgumentException("number of vertices in a Digraph must be non-negative"); indegree = new int[V]; adj = (Bag<Integer>[]) new Bag[V]; for (int v = 0; v < V; v++) { adj[v] = new Bag<Integer>(); } int E = in.readInt(); if (E < 0) throw new IllegalArgumentException("number of edges in a Digraph must be non-negative"); for (int i = 0; i < E; i++) { int v = in.readInt(); int w = in.readInt(); addEdge(v, w); } } catch (NoSuchElementException e) { throw new IllegalArgumentException("invalid input format in Digraph constructor", e); } } /** * Initializes a new digraph that is a deep copy of the specified digraph. * * @param digraph the digraph to copy * @throws IllegalArgumentException if {@code digraph} is {@code null} */ public Digraph(Digraph digraph) { if (digraph == null) throw new IllegalArgumentException("argument is null"); this.V = digraph.V(); this.E = digraph.E(); if (V < 0) throw new IllegalArgumentException("Number of vertices in a Digraph must be non-negative"); // update indegrees indegree = new int[V]; for (int v = 0; v < V; v++) this.indegree[v] = digraph.indegree(v); // update adjacency lists adj = (Bag<Integer>[]) new Bag[V]; for (int v = 0; v < V; v++) { adj[v] = new Bag<Integer>(); } for (int v = 0; v < digraph.V(); v++) { // reverse so that adjacency list is in same order as original Stack<Integer> reverse = new Stack<Integer>(); for (int w : digraph.adj[v]) { reverse.push(w); } for (int w : reverse) { adj[v].add(w); } } } /** * Returns the number of vertices in this digraph. * * @return the number of vertices in this digraph */ public int V() { return V; } /** * Returns the number of edges in this digraph. * * @return the number of edges in this digraph */ public int E() { return E; } // throw an IllegalArgumentException unless {@code 0 <= v < V} private void validateVertex(int v) { if (v < 0 || v >= V) throw new IllegalArgumentException("vertex " + v + " is not between 0 and " + (V-1)); } /** * Adds the directed edge v→w to this digraph. * * @param v the tail vertex * @param w the head vertex * @throws IllegalArgumentException unless both {@code 0 <= v < V} and {@code 0 <= w < V} */ public void addEdge(int v, int w) { validateVertex(v); validateVertex(w); adj[v].add(w); indegree[w]++; E++; } /** * Returns the vertices adjacent from vertex {@code v} in this digraph. * * @param v the vertex * @return the vertices adjacent from vertex {@code v} in this digraph, as an iterable * @throws IllegalArgumentException unless {@code 0 <= v < V} */ public Iterable<Integer> adj(int v) { validateVertex(v); return adj[v]; } /** * Returns the number of directed edges incident from vertex {@code v}. * This is known as the <em>outdegree</em> of vertex {@code v}. * * @param v the vertex * @return the outdegree of vertex {@code v} * @throws IllegalArgumentException unless {@code 0 <= v < V} */ public int outdegree(int v) { validateVertex(v); return adj[v].size(); } /** * Returns the number of directed edges incident to vertex {@code v}. * This is known as the <em>indegree</em> of vertex {@code v}. * * @param v the vertex * @return the indegree of vertex {@code v} * @throws IllegalArgumentException unless {@code 0 <= v < V} */ public int indegree(int v) { validateVertex(v); return indegree[v]; } /** * Returns the reverse of the digraph. * * @return the reverse of the digraph */ public Digraph reverse() { Digraph reverse = new Digraph(V); for (int v = 0; v < V; v++) { for (int w : adj(v)) { reverse.addEdge(w, v); } } return reverse; } /** * Returns a string representation of the graph. * * @return the number of vertices <em>V</em>, followed by the number of edges <em>E</em>, * followed by the <em>V</em> adjacency lists */ public String toString() { StringBuilder s = new StringBuilder(); s.append(V + " vertices, " + E + " edges " + NEWLINE); for (int v = 0; v < V; v++) { s.append(String.format("%d: ", v)); for (int w : adj[v]) { s.append(String.format("%d ", w)); } s.append(NEWLINE); } return s.toString(); } /** * Returns a string representation of this digraph in DOT format, * suitable for visualization with Graphviz. * * To visualize the digraph, install Graphviz (e.g., "brew install graphviz"). * Then use one of the graph visualization tools * - dot (hierarchical or layer drawing) * - neato (spring model) * - fdp (force-directed placement) * - sfdp (scalable force-directed placement) * - twopi (radial layout) * * For example, the following commands will create graph drawings in SVG * and PDF formats * - dot input.dot -Tsvg -o output.svg * - dot input.dot -Tpdf -o output.pdf * * To change the digraph attributes (e.g., vertex and edge shapes, arrows, colors) * in the DOT format, see https://graphviz.org/doc/info/lang.html * * @return a string representation of this digraph in DOT format */ public String toDot() { StringBuilder s = new StringBuilder(); s.append("digraph {" + NEWLINE); s.append("node[shape=circle, style=filled, fixedsize=true, width=0.3, fontsize=\"10pt\"]" + NEWLINE); s.append("edge[arrowhead=normal]" + NEWLINE); for (int v = 0; v < V; v++) { for (int w : adj[v]) { s.append(v + " -> " + w + NEWLINE); } } s.append("}" + NEWLINE); return s.toString(); } /** * Unit tests the {@code Digraph} data type. * * @param args the command-line arguments */ public static void main(String[] args) { In in = new In(args[0]); Digraph graph = new Digraph(in); StdOut.println(graph); } }
[ "https://algs4.cs.princeton.edu/42digraph/largeDG.txt", "https://algs4.cs.princeton.edu/42digraph/tinyDG.txt", "https://algs4.cs.princeton.edu/42digraph/mediumDG.txt" ]
{ "number": "4.2.3", "code_execution": true, "url": "https://algs4.cs.princeton.edu/42digraph/Digraph.java", "params": [ "tinyDG.txt", "mediumDG.txt" ], "dependencies": [ "Bag.java", "In.java", "StdOut.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Implement the constructor for EdgeWeightedGraph.java that reads an edge-weighted graph from an input stream.
/****************************************************************************** * Compilation: javac EdgeWeightedGraph.java * Execution: java EdgeWeightedGraph filename.txt * Dependencies: Bag.java Edge.java In.java StdOut.java * Data files: https://algs4.cs.princeton.edu/43mst/tinyEWG.txt * https://algs4.cs.princeton.edu/43mst/mediumEWG.txt * https://algs4.cs.princeton.edu/43mst/largeEWG.txt * * An edge-weighted undirected graph, implemented using adjacency lists. * Parallel edges and self-loops are permitted. * * % java EdgeWeightedGraph tinyEWG.txt * 8 16 * 0: 6-0 0.58000 0-2 0.26000 0-4 0.38000 0-7 0.16000 * 1: 1-3 0.29000 1-2 0.36000 1-7 0.19000 1-5 0.32000 * 2: 6-2 0.40000 2-7 0.34000 1-2 0.36000 0-2 0.26000 2-3 0.17000 * 3: 3-6 0.52000 1-3 0.29000 2-3 0.17000 * 4: 6-4 0.93000 0-4 0.38000 4-7 0.37000 4-5 0.35000 * 5: 1-5 0.32000 5-7 0.28000 4-5 0.35000 * 6: 6-4 0.93000 6-0 0.58000 3-6 0.52000 6-2 0.40000 * 7: 2-7 0.34000 1-7 0.19000 0-7 0.16000 5-7 0.28000 4-7 0.37000 * ******************************************************************************/ import java.util.NoSuchElementException; /** * The {@code EdgeWeightedGraph} class represents an edge-weighted * graph of vertices named 0 through <em>V</em> – 1, where each * undirected edge is of type {@link Edge} and has a real-valued weight. * It supports the following two primary operations: add an edge to the graph, * iterate over all of the edges incident with a vertex. It also provides * methods for returning the degree of a vertex, the number of vertices * <em>V</em> in the graph, and the number of edges <em>E</em> in the graph. * Parallel edges and self-loops are permitted. * By convention, a self-loop <em>v</em>-<em>v</em> appears in the * adjacency list of <em>v</em> twice and contributes two to the degree * of <em>v</em>. * <p> * This implementation uses an <em>adjacency-lists representation</em>, which * is a vertex-indexed array of {@link Bag} objects. * It uses &Theta;(<em>E</em> + <em>V</em>) space, where <em>E</em> is * the number of edges and <em>V</em> is the number of vertices. * All instance methods take &Theta;(1) time. (Though, iterating over * the edges returned by {@link #adj(int)} takes time proportional * to the degree of the vertex.) * Constructing an empty edge-weighted graph with <em>V</em> vertices takes * &Theta;(<em>V</em>) time; constructing an edge-weighted graph with * <em>E</em> edges and <em>V</em> vertices takes * &Theta;(<em>E</em> + <em>V</em>) time. * <p> * For additional documentation, * see <a href="https://algs4.cs.princeton.edu/43mst">Section 4.3</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class EdgeWeightedGraph { private static final String NEWLINE = System.getProperty("line.separator"); private final int V; private int E; private Bag<Edge>[] adj; /** * Initializes an empty edge-weighted graph with {@code V} vertices and 0 edges. * * @param V the number of vertices * @throws IllegalArgumentException if {@code V < 0} */ public EdgeWeightedGraph(int V) { if (V < 0) throw new IllegalArgumentException("Number of vertices must be non-negative"); this.V = V; this.E = 0; adj = (Bag<Edge>[]) new Bag[V]; for (int v = 0; v < V; v++) { adj[v] = new Bag<Edge>(); } } /** * Initializes a random edge-weighted graph with {@code V} vertices and <em>E</em> edges. * * @param V the number of vertices * @param E the number of edges * @throws IllegalArgumentException if {@code V < 0} * @throws IllegalArgumentException if {@code E < 0} */ public EdgeWeightedGraph(int V, int E) { this(V); if (E < 0) throw new IllegalArgumentException("Number of edges must be non-negative"); for (int i = 0; i < E; i++) { int v = StdRandom.uniformInt(V); int w = StdRandom.uniformInt(V); double weight = 0.01 * StdRandom.uniformInt(0, 100); Edge e = new Edge(v, w, weight); addEdge(e); } } /** * Initializes an edge-weighted graph from an input stream. * The format is the number of vertices <em>V</em>, * followed by the number of edges <em>E</em>, * followed by <em>E</em> pairs of vertices and edge weights, * with each entry separated by whitespace. * * @param in the input stream * @throws IllegalArgumentException if {@code in} is {@code null} * @throws IllegalArgumentException if the endpoints of any edge are not in prescribed range * @throws IllegalArgumentException if the number of vertices or edges is negative */ public EdgeWeightedGraph(In in) { if (in == null) throw new IllegalArgumentException("argument is null"); try { V = in.readInt(); adj = (Bag<Edge>[]) new Bag[V]; for (int v = 0; v < V; v++) { adj[v] = new Bag<Edge>(); } int E = in.readInt(); if (E < 0) throw new IllegalArgumentException("Number of edges must be non-negative"); for (int i = 0; i < E; i++) { int v = in.readInt(); int w = in.readInt(); validateVertex(v); validateVertex(w); double weight = in.readDouble(); Edge e = new Edge(v, w, weight); addEdge(e); } } catch (NoSuchElementException e) { throw new IllegalArgumentException("invalid input format in EdgeWeightedGraph constructor", e); } } /** * Initializes a new edge-weighted graph that is a deep copy of {@code G}. * * @param G the edge-weighted graph to copy */ public EdgeWeightedGraph(EdgeWeightedGraph G) { this(G.V()); this.E = G.E(); for (int v = 0; v < G.V(); v++) { // reverse so that adjacency list is in same order as original Stack<Edge> reverse = new Stack<Edge>(); for (Edge e : G.adj[v]) { reverse.push(e); } for (Edge e : reverse) { adj[v].add(e); } } } /** * Returns the number of vertices in this edge-weighted graph. * * @return the number of vertices in this edge-weighted graph */ public int V() { return V; } /** * Returns the number of edges in this edge-weighted graph. * * @return the number of edges in this edge-weighted graph */ public int E() { return E; } // throw an IllegalArgumentException unless {@code 0 <= v < V} private void validateVertex(int v) { if (v < 0 || v >= V) throw new IllegalArgumentException("vertex " + v + " is not between 0 and " + (V-1)); } /** * Adds the undirected edge {@code e} to this edge-weighted graph. * * @param e the edge * @throws IllegalArgumentException unless both endpoints are between {@code 0} and {@code V-1} */ public void addEdge(Edge e) { int v = e.either(); int w = e.other(v); validateVertex(v); validateVertex(w); adj[v].add(e); adj[w].add(e); E++; } /** * Returns the edges incident with vertex {@code v}. * * @param v the vertex * @return the edges incident with vertex {@code v} as an Iterable * @throws IllegalArgumentException unless {@code 0 <= v < V} */ public Iterable<Edge> adj(int v) { validateVertex(v); return adj[v]; } /** * Returns the degree of vertex {@code v}. * * @param v the vertex * @return the degree of vertex {@code v} * @throws IllegalArgumentException unless {@code 0 <= v < V} */ public int degree(int v) { validateVertex(v); return adj[v].size(); } /** * Returns all edges in this edge-weighted graph. * To iterate over the edges in this edge-weighted graph, use foreach notation: * {@code for (Edge e : G.edges())}. * * @return all edges in this edge-weighted graph, as an iterable */ public Iterable<Edge> edges() { Bag<Edge> list = new Bag<Edge>(); for (int v = 0; v < V; v++) { int selfLoops = 0; for (Edge e : adj(v)) { if (e.other(v) > v) { list.add(e); } // add only one copy of each self loop (self loops will be consecutive) else if (e.other(v) == v) { if (selfLoops % 2 == 0) list.add(e); selfLoops++; } } } return list; } /** * Returns a string representation of the edge-weighted graph. * This method takes time proportional to <em>E</em> + <em>V</em>. * * @return the number of vertices <em>V</em>, followed by the number of edges <em>E</em>, * followed by the <em>V</em> adjacency lists of edges */ public String toString() { StringBuilder s = new StringBuilder(); s.append(V + " " + E + NEWLINE); for (int v = 0; v < V; v++) { s.append(v + ": "); for (Edge e : adj[v]) { s.append(e + " "); } s.append(NEWLINE); } return s.toString(); } /** * Returns a string representation of this edge-weighted graph in DOT format, * suitable for visualization with Graphviz. * * To visualize the graph, install Graphviz (e.g., "brew install graphviz"). * Then use one of the graph visualization tools * - dot (hierarchical or layer drawing) * - neato (spring model) * - fdp (force-directed placement) * - sfdp (scalable force-directed placement) * - twopi (radial layout) * * For example, the following commands will create graph drawings in SVG * and PDF formats * - dot input.dot -Tsvg -o output.svg * - dot input.dot -Tpdf -o output.pdf * * To change the graph attributes (e.g., vertex and edge shapes, arrows, colors) * in the DOT format, see https://graphviz.org/doc/info/lang.html * * @return a string representation of this edge-weighted graph in DOT format */ public String toDot() { StringBuilder s = new StringBuilder(); s.append("graph {" + NEWLINE); s.append("node[shape=circle, style=filled, fixedsize=true, width=0.3, fontsize=\"10pt\"]" + NEWLINE); s.append("edge[arrowhead=normal, fontsize=\"9pt\"]" + NEWLINE); for (Edge e : edges()) { int v = e.either(); int w = e.other(v); s.append(v + " --" + w + " [label=\"" + e.weight() + "\"]" + NEWLINE); } s.append("}" + NEWLINE); return s.toString(); } /** * Unit tests the {@code EdgeWeightedGraph} data type. * * @param args the command-line arguments */ public static void main(String[] args) { In in = new In(args[0]); EdgeWeightedGraph graph = new EdgeWeightedGraph(in); StdOut.println(graph); } }
[ "https://algs4.cs.princeton.edu/43mst/mediumEWG.txt", "https://algs4.cs.princeton.edu/43mst/tinyEWG.txt", "https://algs4.cs.princeton.edu/43mst/largeEWG.txt" ]
{ "number": "4.3.9", "code_execution": true, "url": "https://algs4.cs.princeton.edu/43mst/EdgeWeightedGraph.java", "params": [ "mediumEWG.txt", "tinyEWG.txt" ], "dependencies": [ "Bag.java", "Edge.java", "In.java", "StdOut.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Implement toString() for EdgeWeightedGraph.java.
/****************************************************************************** * Compilation: javac EdgeWeightedGraph.java * Execution: java EdgeWeightedGraph filename.txt * Dependencies: Bag.java Edge.java In.java StdOut.java * Data files: https://algs4.cs.princeton.edu/43mst/tinyEWG.txt * https://algs4.cs.princeton.edu/43mst/mediumEWG.txt * https://algs4.cs.princeton.edu/43mst/largeEWG.txt * * An edge-weighted undirected graph, implemented using adjacency lists. * Parallel edges and self-loops are permitted. * * % java EdgeWeightedGraph tinyEWG.txt * 8 16 * 0: 6-0 0.58000 0-2 0.26000 0-4 0.38000 0-7 0.16000 * 1: 1-3 0.29000 1-2 0.36000 1-7 0.19000 1-5 0.32000 * 2: 6-2 0.40000 2-7 0.34000 1-2 0.36000 0-2 0.26000 2-3 0.17000 * 3: 3-6 0.52000 1-3 0.29000 2-3 0.17000 * 4: 6-4 0.93000 0-4 0.38000 4-7 0.37000 4-5 0.35000 * 5: 1-5 0.32000 5-7 0.28000 4-5 0.35000 * 6: 6-4 0.93000 6-0 0.58000 3-6 0.52000 6-2 0.40000 * 7: 2-7 0.34000 1-7 0.19000 0-7 0.16000 5-7 0.28000 4-7 0.37000 * ******************************************************************************/ import java.util.NoSuchElementException; /** * The {@code EdgeWeightedGraph} class represents an edge-weighted * graph of vertices named 0 through <em>V</em> – 1, where each * undirected edge is of type {@link Edge} and has a real-valued weight. * It supports the following two primary operations: add an edge to the graph, * iterate over all of the edges incident with a vertex. It also provides * methods for returning the degree of a vertex, the number of vertices * <em>V</em> in the graph, and the number of edges <em>E</em> in the graph. * Parallel edges and self-loops are permitted. * By convention, a self-loop <em>v</em>-<em>v</em> appears in the * adjacency list of <em>v</em> twice and contributes two to the degree * of <em>v</em>. * <p> * This implementation uses an <em>adjacency-lists representation</em>, which * is a vertex-indexed array of {@link Bag} objects. * It uses &Theta;(<em>E</em> + <em>V</em>) space, where <em>E</em> is * the number of edges and <em>V</em> is the number of vertices. * All instance methods take &Theta;(1) time. (Though, iterating over * the edges returned by {@link #adj(int)} takes time proportional * to the degree of the vertex.) * Constructing an empty edge-weighted graph with <em>V</em> vertices takes * &Theta;(<em>V</em>) time; constructing an edge-weighted graph with * <em>E</em> edges and <em>V</em> vertices takes * &Theta;(<em>E</em> + <em>V</em>) time. * <p> * For additional documentation, * see <a href="https://algs4.cs.princeton.edu/43mst">Section 4.3</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class EdgeWeightedGraph { private static final String NEWLINE = System.getProperty("line.separator"); private final int V; private int E; private Bag<Edge>[] adj; /** * Initializes an empty edge-weighted graph with {@code V} vertices and 0 edges. * * @param V the number of vertices * @throws IllegalArgumentException if {@code V < 0} */ public EdgeWeightedGraph(int V) { if (V < 0) throw new IllegalArgumentException("Number of vertices must be non-negative"); this.V = V; this.E = 0; adj = (Bag<Edge>[]) new Bag[V]; for (int v = 0; v < V; v++) { adj[v] = new Bag<Edge>(); } } /** * Initializes a random edge-weighted graph with {@code V} vertices and <em>E</em> edges. * * @param V the number of vertices * @param E the number of edges * @throws IllegalArgumentException if {@code V < 0} * @throws IllegalArgumentException if {@code E < 0} */ public EdgeWeightedGraph(int V, int E) { this(V); if (E < 0) throw new IllegalArgumentException("Number of edges must be non-negative"); for (int i = 0; i < E; i++) { int v = StdRandom.uniformInt(V); int w = StdRandom.uniformInt(V); double weight = 0.01 * StdRandom.uniformInt(0, 100); Edge e = new Edge(v, w, weight); addEdge(e); } } /** * Initializes an edge-weighted graph from an input stream. * The format is the number of vertices <em>V</em>, * followed by the number of edges <em>E</em>, * followed by <em>E</em> pairs of vertices and edge weights, * with each entry separated by whitespace. * * @param in the input stream * @throws IllegalArgumentException if {@code in} is {@code null} * @throws IllegalArgumentException if the endpoints of any edge are not in prescribed range * @throws IllegalArgumentException if the number of vertices or edges is negative */ public EdgeWeightedGraph(In in) { if (in == null) throw new IllegalArgumentException("argument is null"); try { V = in.readInt(); adj = (Bag<Edge>[]) new Bag[V]; for (int v = 0; v < V; v++) { adj[v] = new Bag<Edge>(); } int E = in.readInt(); if (E < 0) throw new IllegalArgumentException("Number of edges must be non-negative"); for (int i = 0; i < E; i++) { int v = in.readInt(); int w = in.readInt(); validateVertex(v); validateVertex(w); double weight = in.readDouble(); Edge e = new Edge(v, w, weight); addEdge(e); } } catch (NoSuchElementException e) { throw new IllegalArgumentException("invalid input format in EdgeWeightedGraph constructor", e); } } /** * Initializes a new edge-weighted graph that is a deep copy of {@code G}. * * @param G the edge-weighted graph to copy */ public EdgeWeightedGraph(EdgeWeightedGraph G) { this(G.V()); this.E = G.E(); for (int v = 0; v < G.V(); v++) { // reverse so that adjacency list is in same order as original Stack<Edge> reverse = new Stack<Edge>(); for (Edge e : G.adj[v]) { reverse.push(e); } for (Edge e : reverse) { adj[v].add(e); } } } /** * Returns the number of vertices in this edge-weighted graph. * * @return the number of vertices in this edge-weighted graph */ public int V() { return V; } /** * Returns the number of edges in this edge-weighted graph. * * @return the number of edges in this edge-weighted graph */ public int E() { return E; } // throw an IllegalArgumentException unless {@code 0 <= v < V} private void validateVertex(int v) { if (v < 0 || v >= V) throw new IllegalArgumentException("vertex " + v + " is not between 0 and " + (V-1)); } /** * Adds the undirected edge {@code e} to this edge-weighted graph. * * @param e the edge * @throws IllegalArgumentException unless both endpoints are between {@code 0} and {@code V-1} */ public void addEdge(Edge e) { int v = e.either(); int w = e.other(v); validateVertex(v); validateVertex(w); adj[v].add(e); adj[w].add(e); E++; } /** * Returns the edges incident with vertex {@code v}. * * @param v the vertex * @return the edges incident with vertex {@code v} as an Iterable * @throws IllegalArgumentException unless {@code 0 <= v < V} */ public Iterable<Edge> adj(int v) { validateVertex(v); return adj[v]; } /** * Returns the degree of vertex {@code v}. * * @param v the vertex * @return the degree of vertex {@code v} * @throws IllegalArgumentException unless {@code 0 <= v < V} */ public int degree(int v) { validateVertex(v); return adj[v].size(); } /** * Returns all edges in this edge-weighted graph. * To iterate over the edges in this edge-weighted graph, use foreach notation: * {@code for (Edge e : G.edges())}. * * @return all edges in this edge-weighted graph, as an iterable */ public Iterable<Edge> edges() { Bag<Edge> list = new Bag<Edge>(); for (int v = 0; v < V; v++) { int selfLoops = 0; for (Edge e : adj(v)) { if (e.other(v) > v) { list.add(e); } // add only one copy of each self loop (self loops will be consecutive) else if (e.other(v) == v) { if (selfLoops % 2 == 0) list.add(e); selfLoops++; } } } return list; } /** * Returns a string representation of the edge-weighted graph. * This method takes time proportional to <em>E</em> + <em>V</em>. * * @return the number of vertices <em>V</em>, followed by the number of edges <em>E</em>, * followed by the <em>V</em> adjacency lists of edges */ public String toString() { StringBuilder s = new StringBuilder(); s.append(V + " " + E + NEWLINE); for (int v = 0; v < V; v++) { s.append(v + ": "); for (Edge e : adj[v]) { s.append(e + " "); } s.append(NEWLINE); } return s.toString(); } /** * Returns a string representation of this edge-weighted graph in DOT format, * suitable for visualization with Graphviz. * * To visualize the graph, install Graphviz (e.g., "brew install graphviz"). * Then use one of the graph visualization tools * - dot (hierarchical or layer drawing) * - neato (spring model) * - fdp (force-directed placement) * - sfdp (scalable force-directed placement) * - twopi (radial layout) * * For example, the following commands will create graph drawings in SVG * and PDF formats * - dot input.dot -Tsvg -o output.svg * - dot input.dot -Tpdf -o output.pdf * * To change the graph attributes (e.g., vertex and edge shapes, arrows, colors) * in the DOT format, see https://graphviz.org/doc/info/lang.html * * @return a string representation of this edge-weighted graph in DOT format */ public String toDot() { StringBuilder s = new StringBuilder(); s.append("graph {" + NEWLINE); s.append("node[shape=circle, style=filled, fixedsize=true, width=0.3, fontsize=\"10pt\"]" + NEWLINE); s.append("edge[arrowhead=normal, fontsize=\"9pt\"]" + NEWLINE); for (Edge e : edges()) { int v = e.either(); int w = e.other(v); s.append(v + " --" + w + " [label=\"" + e.weight() + "\"]" + NEWLINE); } s.append("}" + NEWLINE); return s.toString(); } /** * Unit tests the {@code EdgeWeightedGraph} data type. * * @param args the command-line arguments */ public static void main(String[] args) { In in = new In(args[0]); EdgeWeightedGraph graph = new EdgeWeightedGraph(in); StdOut.println(graph); } }
[ "https://algs4.cs.princeton.edu/43mst/mediumEWG.txt", "https://algs4.cs.princeton.edu/43mst/tinyEWG.txt", "https://algs4.cs.princeton.edu/43mst/largeEWG.txt" ]
{ "number": "4.3.17", "code_execution": true, "url": "https://algs4.cs.princeton.edu/43mst/EdgeWeightedGraph.java", "params": [ "mediumEWG.txt", "tinyEWG.txt" ], "dependencies": [ "Bag.java", "Edge.java", "In.java", "StdOut.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Provide an implementation of edges() for PrimMST.java .
/****************************************************************************** * Compilation: javac PrimMST.java * Execution: java PrimMST filename.txt * Dependencies: EdgeWeightedGraph.java Edge.java Queue.java * IndexMinPQ.java UF.java In.java StdOut.java * Data files: https://algs4.cs.princeton.edu/43mst/tinyEWG.txt * https://algs4.cs.princeton.edu/43mst/mediumEWG.txt * https://algs4.cs.princeton.edu/43mst/largeEWG.txt * * Compute a minimum spanning forest using Prim's algorithm. * * % java PrimMST tinyEWG.txt * 1-7 0.19000 * 0-2 0.26000 * 2-3 0.17000 * 4-5 0.35000 * 5-7 0.28000 * 6-2 0.40000 * 0-7 0.16000 * 1.81000 * * % java PrimMST mediumEWG.txt * 1-72 0.06506 * 2-86 0.05980 * 3-67 0.09725 * 4-55 0.06425 * 5-102 0.03834 * 6-129 0.05363 * 7-157 0.00516 * ... * 10.46351 * * % java PrimMST largeEWG.txt * ... * 647.66307 * ******************************************************************************/ /** * The {@code PrimMST} class represents a data type for computing a * <em>minimum spanning tree</em> in an edge-weighted graph. * The edge weights can be positive, zero, or negative and need not * be distinct. If the graph is not connected, it computes a <em>minimum * spanning forest</em>, which is the union of minimum spanning trees * in each connected component. The {@code weight()} method returns the * weight of a minimum spanning tree and the {@code edges()} method * returns its edges. * <p> * This implementation uses <em>Prim's algorithm</em> with an indexed * binary heap. * The constructor takes &Theta;(<em>E</em> log <em>V</em>) time in * the worst case, where <em>V</em> is the number of * vertices and <em>E</em> is the number of edges. * Each instance method takes &Theta;(1) time. * It uses &Theta;(<em>V</em>) extra space (not including the * edge-weighted graph). * <p> * This {@code weight()} method correctly computes the weight of the MST * if all arithmetic performed is without floating-point rounding error * or arithmetic overflow. * This is the case if all edge weights are non-negative integers * and the weight of the MST does not exceed 2<sup>52</sup>. * <p> * For additional documentation, * see <a href="https://algs4.cs.princeton.edu/43mst">Section 4.3</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * For alternate implementations, see {@link LazyPrimMST}, {@link KruskalMST}, * and {@link BoruvkaMST}. * * @author Robert Sedgewick * @author Kevin Wayne */ public class PrimMST { private static final double FLOATING_POINT_EPSILON = 1.0E-12; private Edge[] edgeTo; // edgeTo[v] = shortest edge from tree vertex to non-tree vertex private double[] distTo; // distTo[v] = weight of shortest such edge private boolean[] marked; // marked[v] = true if v on tree, false otherwise private IndexMinPQ<Double> pq; /** * Compute a minimum spanning tree (or forest) of an edge-weighted graph. * @param graph the edge-weighted graph */ public PrimMST(EdgeWeightedGraph graph) { edgeTo = new Edge[graph.V()]; distTo = new double[graph.V()]; marked = new boolean[graph.V()]; pq = new IndexMinPQ<Double>(graph.V()); for (int v = 0; v < graph.V(); v++) distTo[v] = Double.POSITIVE_INFINITY; for (int v = 0; v < graph.V(); v++) // run from each vertex to find if (!marked[v]) prim(graph, v); // minimum spanning forest // check optimality conditions assert check(graph); } // run Prim's algorithm in graph, starting from vertex s private void prim(EdgeWeightedGraph graph, int s) { distTo[s] = 0.0; pq.insert(s, distTo[s]); while (!pq.isEmpty()) { int v = pq.delMin(); scan(graph, v); } } // scan vertex v private void scan(EdgeWeightedGraph graph, int v) { marked[v] = true; for (Edge e : graph.adj(v)) { int w = e.other(v); if (marked[w]) continue; // v-w is obsolete edge if (e.weight() < distTo[w]) { distTo[w] = e.weight(); edgeTo[w] = e; if (pq.contains(w)) pq.decreaseKey(w, distTo[w]); else pq.insert(w, distTo[w]); } } } /** * Returns the edges in a minimum spanning tree (or forest). * @return the edges in a minimum spanning tree (or forest) as * an iterable of edges */ public Iterable<Edge> edges() { Queue<Edge> mst = new Queue<Edge>(); for (int v = 0; v < edgeTo.length; v++) { Edge e = edgeTo[v]; if (e != null) { mst.enqueue(e); } } return mst; } /** * Returns the sum of the edge weights in a minimum spanning tree (or forest). * @return the sum of the edge weights in a minimum spanning tree (or forest) */ public double weight() { double weight = 0.0; for (Edge e : edges()) weight += e.weight(); return weight; } // check optimality conditions (takes time proportional to E V lg* V) private boolean check(EdgeWeightedGraph graph) { // check weight double totalWeight = 0.0; for (Edge e : edges()) { totalWeight += e.weight(); } if (Math.abs(totalWeight - weight()) > FLOATING_POINT_EPSILON) { System.err.printf("Weight of edges does not equal weight(): %f vs. %f", totalWeight, weight()); return false; } // check that it is acyclic UF uf = new UF(graph.V()); for (Edge e : edges()) { int v = e.either(), w = e.other(v); if (uf.find(v) == uf.find(w)) { System.err.println("Not a forest"); return false; } uf.union(v, w); } // check that it is a spanning forest for (Edge e : graph.edges()) { int v = e.either(), w = e.other(v); if (uf.find(v) != uf.find(w)) { System.err.println("Not a spanning forest"); return false; } } // check that it is a minimal spanning forest (cut optimality conditions) for (Edge e : edges()) { // all edges in MST except e uf = new UF(graph.V()); for (Edge f : edges()) { int x = f.either(), y = f.other(x); if (f != e) uf.union(x, y); } // check that e is min weight edge in crossing cut for (Edge f : graph.edges()) { int x = f.either(), y = f.other(x); if (uf.find(x) != uf.find(y)) { if (f.weight() < e.weight()) { System.err.println("Edge " + f + " violates cut optimality conditions"); return false; } } } } return true; } /** * Unit tests the {@code PrimMST} data type. * * @param args the command-line arguments */ public static void main(String[] args) { In in = new In(args[0]); EdgeWeightedGraph graph = new EdgeWeightedGraph(in); PrimMST mst = new PrimMST(graph); for (Edge e : mst.edges()) { StdOut.println(e); } StdOut.printf("%.5f", mst.weight()); } }
[ "https://algs4.cs.princeton.edu/43mst/mediumEWG.txt", "https://algs4.cs.princeton.edu/43mst/tinyEWG.txt", "https://algs4.cs.princeton.edu/43mst/largeEWG.txt" ]
{ "number": "4.3.21", "code_execution": true, "url": "https://algs4.cs.princeton.edu/43mst/PrimMST.java", "params": [ "tinyEWG.txt", "mediumEWG.txt" ], "dependencies": [ "EdgeWeightedGraph.java", "Edge.java", "Queue.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Minimum spanning forest. Develop versions of Prim's algorithms that compute the minimum spanning forest of an edge-weighted graph that is not necessarily connected.
/****************************************************************************** * Compilation: javac PrimMST.java * Execution: java PrimMST filename.txt * Dependencies: EdgeWeightedGraph.java Edge.java Queue.java * IndexMinPQ.java UF.java In.java StdOut.java * Data files: https://algs4.cs.princeton.edu/43mst/tinyEWG.txt * https://algs4.cs.princeton.edu/43mst/mediumEWG.txt * https://algs4.cs.princeton.edu/43mst/largeEWG.txt * * Compute a minimum spanning forest using Prim's algorithm. * * % java PrimMST tinyEWG.txt * 1-7 0.19000 * 0-2 0.26000 * 2-3 0.17000 * 4-5 0.35000 * 5-7 0.28000 * 6-2 0.40000 * 0-7 0.16000 * 1.81000 * * % java PrimMST mediumEWG.txt * 1-72 0.06506 * 2-86 0.05980 * 3-67 0.09725 * 4-55 0.06425 * 5-102 0.03834 * 6-129 0.05363 * 7-157 0.00516 * ... * 10.46351 * * % java PrimMST largeEWG.txt * ... * 647.66307 * ******************************************************************************/ /** * The {@code PrimMST} class represents a data type for computing a * <em>minimum spanning tree</em> in an edge-weighted graph. * The edge weights can be positive, zero, or negative and need not * be distinct. If the graph is not connected, it computes a <em>minimum * spanning forest</em>, which is the union of minimum spanning trees * in each connected component. The {@code weight()} method returns the * weight of a minimum spanning tree and the {@code edges()} method * returns its edges. * <p> * This implementation uses <em>Prim's algorithm</em> with an indexed * binary heap. * The constructor takes &Theta;(<em>E</em> log <em>V</em>) time in * the worst case, where <em>V</em> is the number of * vertices and <em>E</em> is the number of edges. * Each instance method takes &Theta;(1) time. * It uses &Theta;(<em>V</em>) extra space (not including the * edge-weighted graph). * <p> * This {@code weight()} method correctly computes the weight of the MST * if all arithmetic performed is without floating-point rounding error * or arithmetic overflow. * This is the case if all edge weights are non-negative integers * and the weight of the MST does not exceed 2<sup>52</sup>. * <p> * For additional documentation, * see <a href="https://algs4.cs.princeton.edu/43mst">Section 4.3</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * For alternate implementations, see {@link LazyPrimMST}, {@link KruskalMST}, * and {@link BoruvkaMST}. * * @author Robert Sedgewick * @author Kevin Wayne */ public class PrimMST { private static final double FLOATING_POINT_EPSILON = 1.0E-12; private Edge[] edgeTo; // edgeTo[v] = shortest edge from tree vertex to non-tree vertex private double[] distTo; // distTo[v] = weight of shortest such edge private boolean[] marked; // marked[v] = true if v on tree, false otherwise private IndexMinPQ<Double> pq; /** * Compute a minimum spanning tree (or forest) of an edge-weighted graph. * @param graph the edge-weighted graph */ public PrimMST(EdgeWeightedGraph graph) { edgeTo = new Edge[graph.V()]; distTo = new double[graph.V()]; marked = new boolean[graph.V()]; pq = new IndexMinPQ<Double>(graph.V()); for (int v = 0; v < graph.V(); v++) distTo[v] = Double.POSITIVE_INFINITY; for (int v = 0; v < graph.V(); v++) // run from each vertex to find if (!marked[v]) prim(graph, v); // minimum spanning forest // check optimality conditions assert check(graph); } // run Prim's algorithm in graph, starting from vertex s private void prim(EdgeWeightedGraph graph, int s) { distTo[s] = 0.0; pq.insert(s, distTo[s]); while (!pq.isEmpty()) { int v = pq.delMin(); scan(graph, v); } } // scan vertex v private void scan(EdgeWeightedGraph graph, int v) { marked[v] = true; for (Edge e : graph.adj(v)) { int w = e.other(v); if (marked[w]) continue; // v-w is obsolete edge if (e.weight() < distTo[w]) { distTo[w] = e.weight(); edgeTo[w] = e; if (pq.contains(w)) pq.decreaseKey(w, distTo[w]); else pq.insert(w, distTo[w]); } } } /** * Returns the edges in a minimum spanning tree (or forest). * @return the edges in a minimum spanning tree (or forest) as * an iterable of edges */ public Iterable<Edge> edges() { Queue<Edge> mst = new Queue<Edge>(); for (int v = 0; v < edgeTo.length; v++) { Edge e = edgeTo[v]; if (e != null) { mst.enqueue(e); } } return mst; } /** * Returns the sum of the edge weights in a minimum spanning tree (or forest). * @return the sum of the edge weights in a minimum spanning tree (or forest) */ public double weight() { double weight = 0.0; for (Edge e : edges()) weight += e.weight(); return weight; } // check optimality conditions (takes time proportional to E V lg* V) private boolean check(EdgeWeightedGraph graph) { // check weight double totalWeight = 0.0; for (Edge e : edges()) { totalWeight += e.weight(); } if (Math.abs(totalWeight - weight()) > FLOATING_POINT_EPSILON) { System.err.printf("Weight of edges does not equal weight(): %f vs. %f", totalWeight, weight()); return false; } // check that it is acyclic UF uf = new UF(graph.V()); for (Edge e : edges()) { int v = e.either(), w = e.other(v); if (uf.find(v) == uf.find(w)) { System.err.println("Not a forest"); return false; } uf.union(v, w); } // check that it is a spanning forest for (Edge e : graph.edges()) { int v = e.either(), w = e.other(v); if (uf.find(v) != uf.find(w)) { System.err.println("Not a spanning forest"); return false; } } // check that it is a minimal spanning forest (cut optimality conditions) for (Edge e : edges()) { // all edges in MST except e uf = new UF(graph.V()); for (Edge f : edges()) { int x = f.either(), y = f.other(x); if (f != e) uf.union(x, y); } // check that e is min weight edge in crossing cut for (Edge f : graph.edges()) { int x = f.either(), y = f.other(x); if (uf.find(x) != uf.find(y)) { if (f.weight() < e.weight()) { System.err.println("Edge " + f + " violates cut optimality conditions"); return false; } } } } return true; } /** * Unit tests the {@code PrimMST} data type. * * @param args the command-line arguments */ public static void main(String[] args) { In in = new In(args[0]); EdgeWeightedGraph graph = new EdgeWeightedGraph(in); PrimMST mst = new PrimMST(graph); for (Edge e : mst.edges()) { StdOut.println(e); } StdOut.printf("%.5f", mst.weight()); } }
[ "https://algs4.cs.princeton.edu/43mst/mediumEWG.txt", "https://algs4.cs.princeton.edu/43mst/tinyEWG.txt", "https://algs4.cs.princeton.edu/43mst/largeEWG.txt" ]
{ "number": "4.3.22", "code_execution": true, "url": "https://algs4.cs.princeton.edu/43mst/PrimMST.java", "params": [ "tinyEWG.txt", "mediumEWG.txt" ], "dependencies": [ "EdgeWeightedGraph.java", "Edge.java", "Queue.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Minimum spanning forest. Develop versions of Kruskal's algorithms that compute the minimum spanning forest of an edge-weighted graph that is not necessarily connected.
/****************************************************************************** * Compilation: javac KruskalMST.java * Execution: java KruskalMST filename.txt * Dependencies: EdgeWeightedGraph.java Edge.java Queue.java MinPQ.java * UF.java In.java StdOut.java * Data files: https://algs4.cs.princeton.edu/43mst/tinyEWG.txt * https://algs4.cs.princeton.edu/43mst/mediumEWG.txt * https://algs4.cs.princeton.edu/43mst/largeEWG.txt * * Compute a minimum spanning forest using Kruskal's algorithm. * * % java KruskalMST tinyEWG.txt * 0-7 0.16000 * 2-3 0.17000 * 1-7 0.19000 * 0-2 0.26000 * 5-7 0.28000 * 4-5 0.35000 * 6-2 0.40000 * 1.81000 * * % java KruskalMST mediumEWG.txt * 168-231 0.00268 * 151-208 0.00391 * 7-157 0.00516 * 122-205 0.00647 * 8-152 0.00702 * 156-219 0.00745 * 28-198 0.00775 * 38-126 0.00845 * 10-123 0.00886 * ... * 10.46351 * ******************************************************************************/ import java.util.Arrays; /** * The {@code KruskalMST} class represents a data type for computing a * <em>minimum spanning tree</em> in an edge-weighted graph. * The edge weights can be positive, zero, or negative and need not * be distinct. If the graph is not connected, it computes a <em>minimum * spanning forest</em>, which is the union of minimum spanning trees * in each connected component. The {@code weight()} method returns the * weight of a minimum spanning tree and the {@code edges()} method * returns its edges. * <p> * This implementation uses <em>Kruskal's algorithm</em> and the * union-find data type. * The constructor takes &Theta;(<em>E</em> log <em>E</em>) time in * the worst case. * Each instance method takes &Theta;(1) time. * It uses &Theta;(<em>E</em>) extra space (not including the graph). * <p> * This {@code weight()} method correctly computes the weight of the MST * if all arithmetic performed is without floating-point rounding error * or arithmetic overflow. * This is the case if all edge weights are non-negative integers * and the weight of the MST does not exceed 2<sup>52</sup>. * <p> * For additional documentation, * see <a href="https://algs4.cs.princeton.edu/43mst">Section 4.3</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * For alternate implementations, see {@link LazyPrimMST}, {@link PrimMST}, * and {@link BoruvkaMST}. * * @author Robert Sedgewick * @author Kevin Wayne */ public class KruskalMST { private static final double FLOATING_POINT_EPSILON = 1.0E-12; private double weight; // weight of MST private Queue<Edge> mst = new Queue<Edge>(); // edges in MST /** * Compute a minimum spanning tree (or forest) of an edge-weighted graph. * @param graph the edge-weighted graph */ public KruskalMST(EdgeWeightedGraph graph) { // create array of edges, sorted by weight Edge[] edges = new Edge[graph.E()]; int t = 0; for (Edge e: graph.edges()) { edges[t++] = e; } Arrays.sort(edges); // run greedy algorithm UF uf = new UF(graph.V()); for (int i = 0; i < graph.E() && mst.size() < graph.V() - 1; i++) { Edge e = edges[i]; int v = e.either(); int w = e.other(v); // v-w does not create a cycle if (uf.find(v) != uf.find(w)) { uf.union(v, w); // merge v and w components mst.enqueue(e); // add edge e to mst weight += e.weight(); } } // check optimality conditions assert check(graph); } /** * Returns the edges in a minimum spanning tree (or forest). * @return the edges in a minimum spanning tree (or forest) as * an iterable of edges */ public Iterable<Edge> edges() { return mst; } /** * Returns the sum of the edge weights in a minimum spanning tree (or forest). * @return the sum of the edge weights in a minimum spanning tree (or forest) */ public double weight() { return weight; } // check optimality conditions (takes time proportional to E V lg* V) private boolean check(EdgeWeightedGraph graph) { // check total weight double total = 0.0; for (Edge e : edges()) { total += e.weight(); } if (Math.abs(total - weight()) > FLOATING_POINT_EPSILON) { System.err.printf("Weight of edges does not equal weight(): %f vs. %f", total, weight()); return false; } // check that it is acyclic UF uf = new UF(graph.V()); for (Edge e : edges()) { int v = e.either(), w = e.other(v); if (uf.find(v) == uf.find(w)) { System.err.println("Not a forest"); return false; } uf.union(v, w); } // check that it is a spanning forest for (Edge e : graph.edges()) { int v = e.either(), w = e.other(v); if (uf.find(v) != uf.find(w)) { System.err.println("Not a spanning forest"); return false; } } // check that it is a minimal spanning forest (cut optimality conditions) for (Edge e : edges()) { // all edges in MST except e uf = new UF(graph.V()); for (Edge f : mst) { int x = f.either(), y = f.other(x); if (f != e) uf.union(x, y); } // check that e is min weight edge in crossing cut for (Edge f : graph.edges()) { int x = f.either(), y = f.other(x); if (uf.find(x) != uf.find(y)) { if (f.weight() < e.weight()) { System.err.println("Edge " + f + " violates cut optimality conditions"); return false; } } } } return true; } /** * Unit tests the {@code KruskalMST} data type. * * @param args the command-line arguments */ public static void main(String[] args) { In in = new In(args[0]); EdgeWeightedGraph G = new EdgeWeightedGraph(in); KruskalMST mst = new KruskalMST(G); for (Edge e : mst.edges()) { StdOut.println(e); } StdOut.printf("%.5f", mst.weight()); } }
[ "https://algs4.cs.princeton.edu/43mst/mediumEWG.txt", "https://algs4.cs.princeton.edu/43mst/tinyEWG.txt", "https://algs4.cs.princeton.edu/43mst/largeEWG.txt" ]
{ "number": "4.3.22", "code_execution": true, "url": "https://algs4.cs.princeton.edu/43mst/KruskalMST.java", "params": [ "mediumEWG.txt", "tinyEWG.txt" ], "dependencies": [ "EdgeWeightedGraph.java", "Edge.java", "Queue.java", "MinPQ.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Certification. Write a method check() that uses the following cut optimality conditions to verify that a proposed set of edges is in fact an MST: A set of edges is an MST if it is a spanning tree and every edge is a minimum-weight edge in the cut defined by removing that edge from the tree. What is the order of growth of the running time of your method?
/****************************************************************************** * Compilation: javac KruskalMST.java * Execution: java KruskalMST filename.txt * Dependencies: EdgeWeightedGraph.java Edge.java Queue.java MinPQ.java * UF.java In.java StdOut.java * Data files: https://algs4.cs.princeton.edu/43mst/tinyEWG.txt * https://algs4.cs.princeton.edu/43mst/mediumEWG.txt * https://algs4.cs.princeton.edu/43mst/largeEWG.txt * * Compute a minimum spanning forest using Kruskal's algorithm. * * % java KruskalMST tinyEWG.txt * 0-7 0.16000 * 2-3 0.17000 * 1-7 0.19000 * 0-2 0.26000 * 5-7 0.28000 * 4-5 0.35000 * 6-2 0.40000 * 1.81000 * * % java KruskalMST mediumEWG.txt * 168-231 0.00268 * 151-208 0.00391 * 7-157 0.00516 * 122-205 0.00647 * 8-152 0.00702 * 156-219 0.00745 * 28-198 0.00775 * 38-126 0.00845 * 10-123 0.00886 * ... * 10.46351 * ******************************************************************************/ import java.util.Arrays; /** * The {@code KruskalMST} class represents a data type for computing a * <em>minimum spanning tree</em> in an edge-weighted graph. * The edge weights can be positive, zero, or negative and need not * be distinct. If the graph is not connected, it computes a <em>minimum * spanning forest</em>, which is the union of minimum spanning trees * in each connected component. The {@code weight()} method returns the * weight of a minimum spanning tree and the {@code edges()} method * returns its edges. * <p> * This implementation uses <em>Kruskal's algorithm</em> and the * union-find data type. * The constructor takes &Theta;(<em>E</em> log <em>E</em>) time in * the worst case. * Each instance method takes &Theta;(1) time. * It uses &Theta;(<em>E</em>) extra space (not including the graph). * <p> * This {@code weight()} method correctly computes the weight of the MST * if all arithmetic performed is without floating-point rounding error * or arithmetic overflow. * This is the case if all edge weights are non-negative integers * and the weight of the MST does not exceed 2<sup>52</sup>. * <p> * For additional documentation, * see <a href="https://algs4.cs.princeton.edu/43mst">Section 4.3</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * For alternate implementations, see {@link LazyPrimMST}, {@link PrimMST}, * and {@link BoruvkaMST}. * * @author Robert Sedgewick * @author Kevin Wayne */ public class KruskalMST { private static final double FLOATING_POINT_EPSILON = 1.0E-12; private double weight; // weight of MST private Queue<Edge> mst = new Queue<Edge>(); // edges in MST /** * Compute a minimum spanning tree (or forest) of an edge-weighted graph. * @param graph the edge-weighted graph */ public KruskalMST(EdgeWeightedGraph graph) { // create array of edges, sorted by weight Edge[] edges = new Edge[graph.E()]; int t = 0; for (Edge e: graph.edges()) { edges[t++] = e; } Arrays.sort(edges); // run greedy algorithm UF uf = new UF(graph.V()); for (int i = 0; i < graph.E() && mst.size() < graph.V() - 1; i++) { Edge e = edges[i]; int v = e.either(); int w = e.other(v); // v-w does not create a cycle if (uf.find(v) != uf.find(w)) { uf.union(v, w); // merge v and w components mst.enqueue(e); // add edge e to mst weight += e.weight(); } } // check optimality conditions assert check(graph); } /** * Returns the edges in a minimum spanning tree (or forest). * @return the edges in a minimum spanning tree (or forest) as * an iterable of edges */ public Iterable<Edge> edges() { return mst; } /** * Returns the sum of the edge weights in a minimum spanning tree (or forest). * @return the sum of the edge weights in a minimum spanning tree (or forest) */ public double weight() { return weight; } // check optimality conditions (takes time proportional to E V lg* V) private boolean check(EdgeWeightedGraph graph) { // check total weight double total = 0.0; for (Edge e : edges()) { total += e.weight(); } if (Math.abs(total - weight()) > FLOATING_POINT_EPSILON) { System.err.printf("Weight of edges does not equal weight(): %f vs. %f", total, weight()); return false; } // check that it is acyclic UF uf = new UF(graph.V()); for (Edge e : edges()) { int v = e.either(), w = e.other(v); if (uf.find(v) == uf.find(w)) { System.err.println("Not a forest"); return false; } uf.union(v, w); } // check that it is a spanning forest for (Edge e : graph.edges()) { int v = e.either(), w = e.other(v); if (uf.find(v) != uf.find(w)) { System.err.println("Not a spanning forest"); return false; } } // check that it is a minimal spanning forest (cut optimality conditions) for (Edge e : edges()) { // all edges in MST except e uf = new UF(graph.V()); for (Edge f : mst) { int x = f.either(), y = f.other(x); if (f != e) uf.union(x, y); } // check that e is min weight edge in crossing cut for (Edge f : graph.edges()) { int x = f.either(), y = f.other(x); if (uf.find(x) != uf.find(y)) { if (f.weight() < e.weight()) { System.err.println("Edge " + f + " violates cut optimality conditions"); return false; } } } } return true; } /** * Unit tests the {@code KruskalMST} data type. * * @param args the command-line arguments */ public static void main(String[] args) { In in = new In(args[0]); EdgeWeightedGraph G = new EdgeWeightedGraph(in); KruskalMST mst = new KruskalMST(G); for (Edge e : mst.edges()) { StdOut.println(e); } StdOut.printf("%.5f", mst.weight()); } }
[ "https://algs4.cs.princeton.edu/43mst/mediumEWG.txt", "https://algs4.cs.princeton.edu/43mst/tinyEWG.txt", "https://algs4.cs.princeton.edu/43mst/largeEWG.txt" ]
{ "number": "4.3.33", "code_execution": true, "url": "https://algs4.cs.princeton.edu/43mst/KruskalMST.java", "params": [ "mediumEWG.txt", "tinyEWG.txt" ], "dependencies": [ "EdgeWeightedGraph.java", "Edge.java", "Queue.java", "MinPQ.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Boruvka's algorithm. Develop an implementation BoruvkaMST.java of Boruvka's algorithm: Build an MST by adding edges to a growing forest of trees, as in Kruskal's algorithm, but in stages. At each stage, find the minimum-weight edge that connects each tree to a different one, then add all such edges to the MST. Assume that the edge weights are all different, to avoid cycles. Hint: Maintain in a vertex-indexed array to identify the edge that connects each component to its nearest neighbor, and use the union-find data structure. Remark. There are a most log V phases since number of trees decreases by at least a factor of 2 in each phase. Attractive because it is efficient and can be run in parallel.
/****************************************************************************** * Compilation: javac BoruvkaMST.java * Execution: java BoruvkaMST filename.txt * Dependencies: EdgeWeightedGraph.java Edge.java Bag.java * UF.java In.java StdOut.java * Data files: https://algs4.cs.princeton.edu/43mst/tinyEWG.txt * https://algs4.cs.princeton.edu/43mst/mediumEWG.txt * https://algs4.cs.princeton.edu/43mst/largeEWG.txt * * Compute a minimum spanning forest using Boruvka's algorithm. * * % java BoruvkaMST tinyEWG.txt * 0-2 0.26000 * 6-2 0.40000 * 5-7 0.28000 * 4-5 0.35000 * 2-3 0.17000 * 1-7 0.19000 * 0-7 0.16000 * 1.81000 * ******************************************************************************/ /** * The {@code BoruvkaMST} class represents a data type for computing a * <em>minimum spanning tree</em> in an edge-weighted graph. * The edge weights can be positive, zero, or negative and need not * be distinct. If the graph is not connected, it computes a <em>minimum * spanning forest</em>, which is the union of minimum spanning trees * in each connected component. The {@code weight()} method returns the * weight of a minimum spanning tree and the {@code edges()} method * returns its edges. * <p> * This implementation uses <em>Boruvka's algorithm</em> and the union-find * data type. * The constructor takes &Theta;(<em>E</em> log <em>V</em>) time in * the worst case, where <em>V</em> is the number of vertices and * <em>E</em> is the number of edges. * Each instance method takes &Theta;(1) time. * It uses &Theta;(<em>V</em>) extra space (not including the * edge-weighted graph). * <p> * This {@code weight()} method correctly computes the weight of the MST * if all arithmetic performed is without floating-point rounding error * or arithmetic overflow. * This is the case if all edge weights are non-negative integers * and the weight of the MST does not exceed 2<sup>52</sup>. * <p> * For additional documentation, * see <a href="https://algs4.cs.princeton.edu/43mst">Section 4.3</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * For alternate implementations, see {@link LazyPrimMST}, {@link PrimMST}, * and {@link KruskalMST}. * * @author Robert Sedgewick * @author Kevin Wayne */ public class BoruvkaMST { private static final double FLOATING_POINT_EPSILON = 1.0E-12; private Bag<Edge> mst = new Bag<Edge>(); // edges in MST private double weight; // weight of MST /** * Compute a minimum spanning tree (or forest) of an edge-weighted graph. * @param graph the edge-weighted graph */ public BoruvkaMST(EdgeWeightedGraph graph) { UF uf = new UF(graph.V()); // repeat at most log V times or until we have V-1 edges for (int t = 1; t < graph.V() && mst.size() < graph.V() - 1; t = t + t) { // foreach tree in forest, find closest edge // if edge weights are equal, ties are broken in favor of first edge in graph.edges() Edge[] closest = new Edge[graph.V()]; for (Edge e : graph.edges()) { int v = e.either(), w = e.other(v); int i = uf.find(v), j = uf.find(w); if (i == j) continue; // same tree if (closest[i] == null || less(e, closest[i])) closest[i] = e; if (closest[j] == null || less(e, closest[j])) closest[j] = e; } // add newly discovered edges to MST for (int i = 0; i < graph.V(); i++) { Edge e = closest[i]; if (e != null) { int v = e.either(), w = e.other(v); // don't add the same edge twice if (uf.find(v) != uf.find(w)) { mst.add(e); weight += e.weight(); uf.union(v, w); } } } } // check optimality conditions assert check(graph); } /** * Returns the edges in a minimum spanning tree (or forest). * @return the edges in a minimum spanning tree (or forest) as * an iterable of edges */ public Iterable<Edge> edges() { return mst; } /** * Returns the sum of the edge weights in a minimum spanning tree (or forest). * @return the sum of the edge weights in a minimum spanning tree (or forest) */ public double weight() { return weight; } // is the weight of edge e strictly less than that of edge f? private static boolean less(Edge e, Edge f) { return e.compareTo(f) < 0; } // check optimality conditions (takes time proportional to E V lg* V) private boolean check(EdgeWeightedGraph graph) { // check weight double totalWeight = 0.0; for (Edge e : edges()) { totalWeight += e.weight(); } if (Math.abs(totalWeight - weight()) > FLOATING_POINT_EPSILON) { System.err.printf("Weight of edges does not equal weight(): %f vs. %f", totalWeight, weight()); return false; } // check that it is acyclic UF uf = new UF(graph.V()); for (Edge e : edges()) { int v = e.either(), w = e.other(v); if (uf.find(v) == uf.find(w)) { System.err.println("Not a forest"); return false; } uf.union(v, w); } // check that it is a spanning forest for (Edge e : graph.edges()) { int v = e.either(), w = e.other(v); if (uf.find(v) != uf.find(w)) { System.err.println("Not a spanning forest"); return false; } } // check that it is a minimal spanning forest (cut optimality conditions) for (Edge e : edges()) { // all edges in MST except e uf = new UF(graph.V()); for (Edge f : mst) { int x = f.either(), y = f.other(x); if (f != e) uf.union(x, y); } // check that e is min weight edge in crossing cut for (Edge f : graph.edges()) { int x = f.either(), y = f.other(x); if (uf.find(x) != uf.find(y)) { if (f.weight() < e.weight()) { System.err.println("Edge " + f + " violates cut optimality conditions"); return false; } } } } return true; } /** * Unit tests the {@code BoruvkaMST} data type. * * @param args the command-line arguments */ public static void main(String[] args) { In in = new In(args[0]); EdgeWeightedGraph graph = new EdgeWeightedGraph(in); BoruvkaMST mst = new BoruvkaMST(graph); for (Edge e : mst.edges()) { StdOut.println(e); } StdOut.printf("%.5f", mst.weight()); } }
[ "https://algs4.cs.princeton.edu/43mst/mediumEWG.txt", "https://algs4.cs.princeton.edu/43mst/tinyEWG.txt", "https://algs4.cs.princeton.edu/43mst/largeEWG.txt" ]
{ "number": "4.3.43", "code_execution": true, "url": "https://algs4.cs.princeton.edu/43mst/BoruvkaMST.java", "params": [ "mediumEWG.txt", "tinyEWG.txt" ], "dependencies": [ "EdgeWeightedGraph.java", "Edge.java", "Bag.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Provide an implementation of toString() for EdgeWeightedDigraph.java.
/****************************************************************************** * Compilation: javac EdgeWeightedDigraph.java * Execution: java EdgeWeightedDigraph digraph.txt * Dependencies: Bag.java DirectedEdge.java * Data files: https://algs4.cs.princeton.edu/44sp/tinyEWD.txt * https://algs4.cs.princeton.edu/44sp/mediumEWD.txt * https://algs4.cs.princeton.edu/44sp/largeEWD.txt * * An edge-weighted digraph, implemented using adjacency lists. * ******************************************************************************/ import java.util.NoSuchElementException; /** * The {@code EdgeWeightedDigraph} class represents an edge-weighted * digraph of vertices named 0 through <em>V</em> - 1, where each * directed edge is of type {@link DirectedEdge} and has a real-valued weight. * It supports the following two primary operations: add a directed edge * to the digraph and iterate over all edges incident from a given vertex. * It also provides methods for returning the indegree or outdegree of a * vertex, the number of vertices <em>V</em> in the digraph, and * the number of edges <em>E</em> in the digraph. * Parallel edges and self-loops are permitted. * <p> * This implementation uses an <em>adjacency-lists representation</em>, which * is a vertex-indexed array of {@link Bag} objects. * It uses &Theta;(<em>E</em> + <em>V</em>) space, where <em>E</em> is * the number of edges and <em>V</em> is the number of vertices. * All instance methods take &Theta;(1) time. (Though, iterating over * the edges returned by {@link #adj(int)} takes time proportional * to the outdegree of the vertex.) * Constructing an empty edge-weighted digraph with <em>V</em> vertices * takes &Theta;(<em>V</em>) time; constructing an edge-weighted digraph * with <em>E</em> edges and <em>V</em> vertices takes * &Theta;(<em>E</em> + <em>V</em>) time. * <p> * For additional documentation, * see <a href="https://algs4.cs.princeton.edu/44sp">Section 4.4</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class EdgeWeightedDigraph { private static final String NEWLINE = System.getProperty("line.separator"); private final int V; // number of vertices in this digraph private int E; // number of edges in this digraph private Bag<DirectedEdge>[] adj; // adj[v] = adjacency list for vertex v private int[] indegree; // indegree[v] = indegree of vertex v /** * Initializes an empty edge-weighted digraph with {@code V} vertices and 0 edges. * * @param V the number of vertices * @throws IllegalArgumentException if {@code V < 0} */ public EdgeWeightedDigraph(int V) { if (V < 0) throw new IllegalArgumentException("Number of vertices in a Digraph must be non-negative"); this.V = V; this.E = 0; this.indegree = new int[V]; adj = (Bag<DirectedEdge>[]) new Bag[V]; for (int v = 0; v < V; v++) adj[v] = new Bag<DirectedEdge>(); } /** * Initializes a random edge-weighted digraph with {@code V} vertices and <em>E</em> edges. * * @param V the number of vertices * @param E the number of edges * @throws IllegalArgumentException if {@code V < 0} * @throws IllegalArgumentException if {@code E < 0} */ public EdgeWeightedDigraph(int V, int E) { this(V); if (E < 0) throw new IllegalArgumentException("Number of edges in a Digraph must be non-negative"); for (int i = 0; i < E; i++) { int v = StdRandom.uniformInt(V); int w = StdRandom.uniformInt(V); double weight = 0.01 * StdRandom.uniformInt(100); DirectedEdge e = new DirectedEdge(v, w, weight); addEdge(e); } } /** * Initializes an edge-weighted digraph from the specified input stream. * The format is the number of vertices <em>V</em>, * followed by the number of edges <em>E</em>, * followed by <em>E</em> pairs of vertices and edge weights, * with each entry separated by whitespace. * * @param in the input stream * @throws IllegalArgumentException if {@code in} is {@code null} * @throws IllegalArgumentException if the endpoints of any edge are not in prescribed range * @throws IllegalArgumentException if the number of vertices or edges is negative */ public EdgeWeightedDigraph(In in) { if (in == null) throw new IllegalArgumentException("argument is null"); try { this.V = in.readInt(); if (V < 0) throw new IllegalArgumentException("number of vertices in a Digraph must be non-negative"); indegree = new int[V]; adj = (Bag<DirectedEdge>[]) new Bag[V]; for (int v = 0; v < V; v++) { adj[v] = new Bag<DirectedEdge>(); } int E = in.readInt(); if (E < 0) throw new IllegalArgumentException("Number of edges must be non-negative"); for (int i = 0; i < E; i++) { int v = in.readInt(); int w = in.readInt(); validateVertex(v); validateVertex(w); double weight = in.readDouble(); addEdge(new DirectedEdge(v, w, weight)); } } catch (NoSuchElementException e) { throw new IllegalArgumentException("invalid input format in EdgeWeightedDigraph constructor", e); } } /** * Initializes a new edge-weighted digraph that is a deep copy of {@code G}. * * @param G the edge-weighted digraph to copy */ public EdgeWeightedDigraph(EdgeWeightedDigraph G) { this(G.V()); this.E = G.E(); for (int v = 0; v < G.V(); v++) this.indegree[v] = G.indegree(v); for (int v = 0; v < G.V(); v++) { // reverse so that adjacency list is in same order as original Stack<DirectedEdge> reverse = new Stack<DirectedEdge>(); for (DirectedEdge e : G.adj[v]) { reverse.push(e); } for (DirectedEdge e : reverse) { adj[v].add(e); } } } /** * Returns the number of vertices in this edge-weighted digraph. * * @return the number of vertices in this edge-weighted digraph */ public int V() { return V; } /** * Returns the number of edges in this edge-weighted digraph. * * @return the number of edges in this edge-weighted digraph */ public int E() { return E; } // throw an IllegalArgumentException unless {@code 0 <= v < V} private void validateVertex(int v) { if (v < 0 || v >= V) throw new IllegalArgumentException("vertex " + v + " is not between 0 and " + (V-1)); } /** * Adds the directed edge {@code e} to this edge-weighted digraph. * * @param e the edge * @throws IllegalArgumentException unless endpoints of edge are between {@code 0} * and {@code V-1} */ public void addEdge(DirectedEdge e) { int v = e.from(); int w = e.to(); validateVertex(v); validateVertex(w); adj[v].add(e); indegree[w]++; E++; } /** * Returns the directed edges incident from vertex {@code v}. * * @param v the vertex * @return the directed edges incident from vertex {@code v} as an Iterable * @throws IllegalArgumentException unless {@code 0 <= v < V} */ public Iterable<DirectedEdge> adj(int v) { validateVertex(v); return adj[v]; } /** * Returns the number of directed edges incident from vertex {@code v}. * This is known as the <em>outdegree</em> of vertex {@code v}. * * @param v the vertex * @return the outdegree of vertex {@code v} * @throws IllegalArgumentException unless {@code 0 <= v < V} */ public int outdegree(int v) { validateVertex(v); return adj[v].size(); } /** * Returns the number of directed edges incident to vertex {@code v}. * This is known as the <em>indegree</em> of vertex {@code v}. * * @param v the vertex * @return the indegree of vertex {@code v} * @throws IllegalArgumentException unless {@code 0 <= v < V} */ public int indegree(int v) { validateVertex(v); return indegree[v]; } /** * Returns all directed edges in this edge-weighted digraph. * To iterate over the edges in this edge-weighted digraph, use foreach notation: * {@code for (DirectedEdge e : G.edges())}. * * @return all edges in this edge-weighted digraph, as an iterable */ public Iterable<DirectedEdge> edges() { Bag<DirectedEdge> list = new Bag<DirectedEdge>(); for (int v = 0; v < V; v++) { for (DirectedEdge e : adj(v)) { list.add(e); } } return list; } /** * Returns a string representation of this edge-weighted digraph. * * @return the number of vertices <em>V</em>, followed by the number of edges <em>E</em>, * followed by the <em>V</em> adjacency lists of edges */ public String toString() { StringBuilder s = new StringBuilder(); s.append(V + " " + E + NEWLINE); for (int v = 0; v < V; v++) { s.append(v + ": "); for (DirectedEdge e : adj[v]) { s.append(e + " "); } s.append(NEWLINE); } return s.toString(); } /** * Returns a string representation of this edge-weighted digraph in DOT format, * suitable for visualization with Graphviz. * * To visualize the graph, install Graphviz (e.g., "brew install graphviz"). * Then use one of the graph visualization tools * - dot (hierarchical or layer drawing) * - neato (spring model) * - fdp (force-directed placement) * - sfdp (scalable force-directed placement) * - twopi (radial layout) * * For example, the following commands will create graph drawings in SVG * and PDF formats * - dot input.dot -Tsvg -o output.svg * - dot input.dot -Tpdf -o output.pdf * * To change the digraph attributes (e.g., vertex and edge shapes, arrows, colors) * in the DOT format, see https://graphviz.org/doc/info/lang.html * * @return a string representation of this edge-weighted digraph in DOT format */ public String toDot() { StringBuilder s = new StringBuilder(); s.append("digraph {" + NEWLINE); s.append("node[shape=circle, style=filled, fixedsize=true, width=0.3, fontsize=\"10pt\"]" + NEWLINE); s.append("edge[arrowhead=normal, fontsize=\"9pt\"]" + NEWLINE); for (int v = 0; v < V; v++) { for (DirectedEdge e : adj[v]) { int w = e.to(); s.append(v + " -> " + w + " [label=\"" + e.weight() + "\"]" + NEWLINE); } } s.append("}" + NEWLINE); return s.toString(); } /** * Unit tests the {@code EdgeWeightedDigraph} data type. * * @param args the command-line arguments */ public static void main(String[] args) { In in = new In(args[0]); EdgeWeightedDigraph G = new EdgeWeightedDigraph(in); StdOut.println(G); } }
[ "https://algs4.cs.princeton.edu/44sp/largeEWD.txt", "https://algs4.cs.princeton.edu/44sp/tinyEWD.txt", "https://algs4.cs.princeton.edu/44sp/mediumEWD.txt" ]
{ "number": "4.4.2", "code_execution": true, "url": "https://algs4.cs.princeton.edu/44sp/EdgeWeightedDigraph.java", "params": [ "tinyEWD.txt", "mediumEWD.txt" ], "dependencies": [ "Bag.java", "DirectedEdge.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Adapt the Topological classes from Section 4.2 to use the EdgeweightedDigraph and DirectedEdge APIs of this section, thus implementing Topological.java.
/****************************************************************************** * Compilation: javac Topological.java * Execution: java Topological filename.txt delimiter * Dependencies: Digraph.java DepthFirstOrder.java DirectedCycle.java * EdgeWeightedDigraph.java EdgeWeightedDirectedCycle.java * SymbolDigraph.java * Data files: https://algs4.cs.princeton.edu/42digraph/jobs.txt * * Compute topological ordering of a DAG or edge-weighted DAG. * Runs in O(E + V) time. * * % java Topological jobs.txt "/" * Calculus * Linear Algebra * Introduction to CS * Advanced Programming * Algorithms * Theoretical CS * Artificial Intelligence * Robotics * Machine Learning * Neural Networks * Databases * Scientific Computing * Computational Biology * ******************************************************************************/ /** * The {@code Topological} class represents a data type for * determining a topological order of a <em>directed acyclic graph</em> (DAG). * A digraph has a topological order if and only if it is a DAG. * The <em>hasOrder</em> operation determines whether the digraph has * a topological order, and if so, the <em>order</em> operation * returns one. * <p> * This implementation uses depth-first search. * The constructor takes &Theta;(<em>V</em> + <em>E</em>) time in the * worst case, where <em>V</em> is the number of vertices and <em>E</em> * is the number of edges. * Each instance method takes &Theta;(1) time. * It uses &Theta;(<em>V</em>) extra space (not including the digraph). * <p> * See {@link DirectedCycle}, {@link DirectedCycleX}, and * {@link EdgeWeightedDirectedCycle} for computing a directed cycle * if the digraph is not a DAG. * See {@link TopologicalX} for a nonrecursive, queue-based algorithm * for computing a topological order of a DAG. * <p> * For additional documentation, * see <a href="https://algs4.cs.princeton.edu/42digraph">Section 4.2</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class Topological { private Iterable<Integer> order; // topological order private int[] rank; // rank[v] = rank of vertex v in order /** * Determines whether the {@code digraph} has a topological order and, if so, * finds such a topological order. * @param digraph the digraph */ public Topological(Digraph digraph) { DirectedCycle finder = new DirectedCycle(digraph); if (!finder.hasCycle()) { DepthFirstOrder dfs = new DepthFirstOrder(digraph); order = dfs.reversePost(); rank = new int[digraph.V()]; int i = 0; for (int v : order) rank[v] = i++; } } /** * Determines whether the edge-weighted digraph {@code digraph} has a topological * order and, if so, finds such an order. * @param digraph the edge-weighted digraph */ public Topological(EdgeWeightedDigraph digraph) { EdgeWeightedDirectedCycle finder = new EdgeWeightedDirectedCycle(digraph); if (!finder.hasCycle()) { DepthFirstOrder dfs = new DepthFirstOrder(digraph); order = dfs.reversePost(); } } /** * Returns a topological order if the digraph has a topological order, * and {@code null} otherwise. * @return a topological order of the vertices (as an iterable) if the * digraph has a topological order (or equivalently, if the digraph is a DAG), * and {@code null} otherwise */ public Iterable<Integer> order() { return order; } /** * Does the digraph have a topological order? * @return {@code true} if the digraph has a topological order (or equivalently, * if the digraph is a DAG), and {@code false} otherwise */ public boolean hasOrder() { return order != null; } /** * Does the digraph have a topological order? * @return {@code true} if the digraph has a topological order (or equivalently, * if the digraph is a DAG), and {@code false} otherwise * @deprecated Replaced by {@link #hasOrder()}. */ @Deprecated public boolean isDAG() { return hasOrder(); } /** * The rank of vertex {@code v} in the topological order; * -1 if the digraph is not a DAG * * @param v the vertex * @return the position of vertex {@code v} in a topological order * of the digraph; -1 if the digraph is not a DAG * @throws IllegalArgumentException unless {@code 0 <= v < V} */ public int rank(int v) { validateVertex(v); if (hasOrder()) return rank[v]; else return -1; } // throw an IllegalArgumentException unless {@code 0 <= v < V} private void validateVertex(int v) { int V = rank.length; if (v < 0 || v >= V) throw new IllegalArgumentException("vertex " + v + " is not between 0 and " + (V-1)); } /** * Unit tests the {@code Topological} data type. * * @param args the command-line arguments */ public static void main(String[] args) { String filename = args[0]; String delimiter = args[1]; SymbolDigraph sg = new SymbolDigraph(filename, delimiter); Topological topological = new Topological(sg.digraph()); for (int v : topological.order()) { StdOut.println(sg.nameOf(v)); } } }
[ "https://algs4.cs.princeton.edu/42digraph/jobs.txt" ]
{ "number": "4.4.12", "code_execution": true, "url": "https://algs4.cs.princeton.edu/44sp/Topological.java", "params": [ "jobs.txt \"/\"" ], "dependencies": [ "Digraph.java", "DepthFirstOrder.java", "DirectedCycle.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Longest paths in DAGs. Develop an implementation AcyclicLP.java that can solve the longest-paths problem in edge-weighted DAGs.
/****************************************************************************** * Compilation: javac AcyclicLP.java * Execution: java AcyclicP V E * Dependencies: EdgeWeightedDigraph.java DirectedEdge.java Topological.java * Data files: https://algs4.cs.princeton.edu/44sp/tinyEWDAG.txt * * Computes longest paths in an edge-weighted acyclic digraph. * * Remark: should probably check that graph is a DAG before running * * % java AcyclicLP tinyEWDAG.txt 5 * 5 to 0 (2.44) 5->1 0.32 1->3 0.29 3->6 0.52 6->4 0.93 4->0 0.38 * 5 to 1 (0.32) 5->1 0.32 * 5 to 2 (2.77) 5->1 0.32 1->3 0.29 3->6 0.52 6->4 0.93 4->7 0.37 7->2 0.34 * 5 to 3 (0.61) 5->1 0.32 1->3 0.29 * 5 to 4 (2.06) 5->1 0.32 1->3 0.29 3->6 0.52 6->4 0.93 * 5 to 5 (0.00) * 5 to 6 (1.13) 5->1 0.32 1->3 0.29 3->6 0.52 * 5 to 7 (2.43) 5->1 0.32 1->3 0.29 3->6 0.52 6->4 0.93 4->7 0.37 * ******************************************************************************/ /** * The {@code AcyclicLP} class represents a data type for solving the * single-source longest paths problem in edge-weighted directed * acyclic graphs (DAGs). The edge weights can be positive, negative, or zero. * <p> * This implementation uses a topological-sort based algorithm. * The constructor takes &Theta;(<em>V</em> + <em>E</em>) time in the * worst case, where <em>V</em> is the number of vertices and * <em>E</em> is the number of edges. * Each instance method takes &Theta;(1) time. * It uses &Theta;(<em>V</em>) extra space (not including the * edge-weighted digraph). * <p> * This correctly computes longest paths if all arithmetic performed is * without floating-point rounding error or arithmetic overflow. * This is the case if all edge weights are integers and if none of the * intermediate results exceeds 2<sup>52</sup>. Since all intermediate * results are sums of edge weights, they are bounded by <em>V C</em>, * where <em>V</em> is the number of vertices and <em>C</em> is the maximum * absolute value of any edge weight. * <p> * For additional documentation, * see <a href="https://algs4.cs.princeton.edu/44sp">Section 4.4</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class AcyclicLP { private double[] distTo; // distTo[v] = distance of longest s->v path private DirectedEdge[] edgeTo; // edgeTo[v] = last edge on longest s->v path /** * Computes a longest paths tree from {@code s} to every other vertex in * the directed acyclic graph {@code digraph}. * @param digraph the acyclic digraph * @param s the source vertex * @throws IllegalArgumentException if the digraph is not acyclic * @throws IllegalArgumentException unless {@code 0 <= s < V} */ public AcyclicLP(EdgeWeightedDigraph digraph, int s) { distTo = new double[digraph.V()]; edgeTo = new DirectedEdge[digraph.V()]; validateVertex(s); for (int v = 0; v < digraph.V(); v++) distTo[v] = Double.NEGATIVE_INFINITY; distTo[s] = 0.0; // relax vertices in topological order Topological topological = new Topological(digraph); if (!topological.hasOrder()) throw new IllegalArgumentException("Digraph is not acyclic."); for (int v : topological.order()) { for (DirectedEdge e : digraph.adj(v)) relax(e); } } // relax edge e, but update if you find a *longer* path private void relax(DirectedEdge e) { int v = e.from(), w = e.to(); if (distTo[w] < distTo[v] + e.weight()) { distTo[w] = distTo[v] + e.weight(); edgeTo[w] = e; } } /** * Returns the length of a longest path from the source vertex {@code s} to vertex {@code v}. * @param v the destination vertex * @return the length of a longest path from the source vertex {@code s} to vertex {@code v}; * {@code Double.NEGATIVE_INFINITY} if no such path * @throws IllegalArgumentException unless {@code 0 <= v < V} */ public double distTo(int v) { validateVertex(v); return distTo[v]; } /** * Is there a path from the source vertex {@code s} to vertex {@code v}? * @param v the destination vertex * @return {@code true} if there is a path from the source vertex * {@code s} to vertex {@code v}, and {@code false} otherwise * @throws IllegalArgumentException unless {@code 0 <= v < V} */ public boolean hasPathTo(int v) { validateVertex(v); return distTo[v] > Double.NEGATIVE_INFINITY; } /** * Returns a longest path from the source vertex {@code s} to vertex {@code v}. * @param v the destination vertex * @return a longest path from the source vertex {@code s} to vertex {@code v} * as an iterable of edges, and {@code null} if no such path * @throws IllegalArgumentException unless {@code 0 <= v < V} */ public Iterable<DirectedEdge> pathTo(int v) { validateVertex(v); if (!hasPathTo(v)) return null; Stack<DirectedEdge> path = new Stack<DirectedEdge>(); for (DirectedEdge e = edgeTo[v]; e != null; e = edgeTo[e.from()]) { path.push(e); } return path; } // throw an IllegalArgumentException unless {@code 0 <= v < V} private void validateVertex(int v) { int V = distTo.length; if (v < 0 || v >= V) throw new IllegalArgumentException("vertex " + v + " is not between 0 and " + (V-1)); } /** * Unit tests the {@code AcyclicLP} data type. * * @param args the command-line arguments */ public static void main(String[] args) { In in = new In(args[0]); int s = Integer.parseInt(args[1]); EdgeWeightedDigraph digraph = new EdgeWeightedDigraph(in); AcyclicLP lp = new AcyclicLP(digraph, s); for (int v = 0; v < digraph.V(); v++) { if (lp.hasPathTo(v)) { StdOut.printf("%d to %d (%.2f) ", s, v, lp.distTo(v)); for (DirectedEdge e : lp.pathTo(v)) { StdOut.print(e + " "); } StdOut.println(); } else { StdOut.printf("%d to %d no path", s, v); } } } }
[ "https://algs4.cs.princeton.edu/44sp/tinyEWDAG.txt" ]
{ "number": "4.4.28", "code_execution": true, "url": "https://algs4.cs.princeton.edu/44sp/AcyclicLP.java", "params": [ "tinyEWDAG.txt 5" ], "dependencies": [ "EdgeWeightedDigraph.java", "DirectedEdge.java", "Topological.java" ], "chapter": null, "chapter_title": null, "section": null, "section_title": null, "type": null }
Give the value of each of the following expressions: a. ( 0 + 15 ) / 2 b. 2.0e-6 * 100000000.1 c. true && false || true && true
1.1.1 a) 7 b) 200.0000002 c) true
[]
{ "number": "1.1.1", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Exercise" }
Give the type and value of each of the following expressions: a. (1 + 2.236)/2 b. 1 + 2 + 3 + 4.0 c. 4.1 >= 4 d. 1 + 2 + "3"
1.1.2 a) 1.618 -> double b) 10.0 -> double c) true -> boolean d) 33 -> String
[]
{ "number": "1.1.2", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Exercise" }
What (if anything) is wrong with each of the following statements? a. if (a > b) then c = 0; b. if a > b { c = 0; } c. if (a > b) c = 0; d. if (a > b) c = 0 else b = 0;
1.1.4 a) No such keyword as "then" in Java language b) Missing Parentheses on if conditional c) Nothing wrong d) Missing semicolon after the "then" clause
[]
{ "number": "1.1.4", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Exercise" }
What does the following program print? int f = 0; int g = 1; for (int i = 0; i <= 15; i++) { StdOut.println(f); f = f + g; g = f - g; }
1.1.6 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610
[]
{ "number": "1.1.6", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Exercise" }
Give the value printed by each of the following code fragments: a. double t = 9.0; while (Math.abs(t - 9.0/t) > .001) t = (9.0/t + t) / 2.0; StdOut.printf("%.5f\n", t); b. int sum = 0; for (int i = 1; i < 1000; i++) for (int j = 0; j < i; j++) sum++; StdOut.println(sum); c. int sum = 0; for (int i = 1; i < 1000; i *= 2) for (int j = 0; j < N; j++) sum++; StdOut.println(sum);
1.1.7 a) 3.00009 b) 499500 c) 10000
[]
{ "number": "1.1.7", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Exercise" }
What do each of the following print? a. System.out.println('b'); b. System.out.println('b' + 'c'); c. System.out.println((char) ('a' + 4)); Explain each outcome.
1.1.8 a) b -> converts the char "b" to String and prints it b) 197 -> sums the char codes of "b" and "c", converts to String and prints it c) e -> sums the char code of "a" with 4, converts it to char and prints it
[]
{ "number": "1.1.8", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Exercise" }
What is wrong with the following code fragment? int[] a; for (int i = 0; i < 10; i++) a[i] = i * i;
1.1.10 The array was not initialized and will generate a compile-time error.
[]
{ "number": "1.1.10", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Exercise" }
What does the following code fragment print? int[] a = new int[10]; for (int i = 0; i < 10; i++) a[i] = 9 - i; for (int i = 0; i < 10; i++) a[i] = a[a[i]]; for (int i = 0; i < 10; i++) System.out.println(i);
1.1.12 0 1 2 3 4 4 3 2 1 0
[]
{ "number": "1.1.12", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Exercise" }
Give the value of exR1(6): public static String exR1(int n) { if (n <= 0) return ""; return exR1(n-3) + n + exR1(n-2) + n; }
1.1.16 311361142246
[]
{ "number": "1.1.16", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Exercise" }
Criticize the following recursive function: public static String exR2(int n) { String s = exR2(n-3) + n + exR2(n-2) + n; if (n <= 0) return ""; return s; }
1.1.17 The function never stops because it keeps calling itself on the first line, until a StackOverflowError occurs.
[]
{ "number": "1.1.17", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Exercise" }
Consider the following recursive function: public static int mystery(int a, int b) { if (b == 0) return 0; if (b % 2 == 0) return mystery(a+a, b/2); return mystery(a+a, b/2) + a; } What are the values of mystery(2, 25) and mystery(3, 11)? Given positive integers a and b, describe what value mystery(a, b) computes. Answer the same question, but replace + with * and replace return 0 with return 1.
1.1.18 mystery(2,25) is equal to 50 mystery(3,11) is equal to 33 mystery(a,b) computes a * b mystery2(2,25) is equal to 33554432 mystery2(3,11) is equal to 177147 mystery2(a,b) computes a^b
[]
{ "number": "1.1.18", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Exercise" }
Run the following program on your computer: public class Fibonacci { public static long F(int N) { if (N == 0) return 0; if (N == 1) return 1; return F(N-1) + F(N-2); } public static void main(String[] args) { for (int N = 0; N < 100; N++) StdOut.println(N + " " + F(N)); } } What is the largest value of N for which this program takes less 1 hour to compute the value of F(N)? Develop a better implementation of F(N) that saves computed values in an array.
1.1.19 The largest value of N that takes less than 1 hour to compute is 51.
[]
{ "number": "1.1.19", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Exercise" }
Use mathematical induction to prove that Euclid’s algorithm computes the greatest common divisor of any pair of nonnegative integers p and q.
1.1.25 For all N E NaturalNumbers and for all nonnegative integers a <= N and b <= N, the Euclidean algorithm computes the greatest common divisor of a and b. Proving that gcd(a, b) = gcd(b, a % b) gcd(20,5) = gcd(5,0) gcd(20,5) is 5 gcd(5,0) is also 5 http://math.stackexchange.com/questions/1274515/prove-that-euclids-algorithm-computes-the-gcd-of-any-pair-of-nonnegative-intege https://www.whitman.edu/mathematics/higher_math_online/section03.03.html
[]
{ "number": "1.1.25", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Exercise" }
Binomial distribution. Estimate the number of recursive calls that would be used by the code public static double binomial(int N, int k, double p) { if ((N == 0) || (k < 0)) return 1.0; return (1.0 - p)*binomial(N-1, k) + p*binomial(N-1, k-1); } to compute binomial(100, 50). Develop a better implementation that is based on saving computed values in an array.
1.1.27 - Binomial distribution For binomial(100, 50, 0.25) the estimate is around 5 billion calls.
[]
{ "number": "1.1.27", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Creative Problem" }
Filtering. Which of the following require saving all the values from standard input (in an array, say), and which could be implemented as a filter using only a fixed number of variables and arrays of fixed size (not dependent on N)? For each, the input comes from standard input and consists of N real numbers between 0 and 1. - Print the maximum and minimum numbers. - Print the median of the numbers. - Print the k th smallest value, for k less than 100. - Print the sum of the squares of the numbers. - Print the average of the N numbers. - Print the percentage of numbers greater than the average. - Print the N numbers in increasing order. - Print the N numbers in random order.
1.1.34 - Filtering Print the maximum and minimum numbers -> Could be implemented as a filter Print the median of the numbers -> Requires saving all values Print the Kth smallest value, for K less than 100 -> Could be implemented as a filter with an array of size K Print the sum of the squares of the numbers -> Could be implemented as a filter Print the average of the N numbers -> Could be implemented as a filter Print the percentage of numbers greater than the average -> Requires saving all values Print the N numbers in increasing order -> Requires saving all values Print the N numbers in random order -> Requires saving all values Thanks to imyuewu (https://github.com/imyuewu) for suggesting a correction for the Kth smallest value case. https://github.com/reneargento/algorithms-sedgewick-wayne/issues/175
[]
{ "number": "1.1.34", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Creative Problem" }
Dice simulation. The following code computes the exact probability distribution for the sum of two dice: int SIDES = 6; double[] dist = new double[2*SIDES+1]; for (int i = 1; i <= SIDES; i++) for (int j = 1; j <= SIDES; j++) dist[i+j] += 1.0; for (int k = 2; k <= 2*SIDES; k++) dist[k] /= 36.0; The value dist[i] is the probability that the dice sum to k. Run experiments to validate this calculation simulating N dice throws, keeping track of the frequencies of occurrence of each value when you compute the sum of two random integers between 1 and 6. How large does N have to be before your empirical results match the exact results to three decimal places?
1.1.35 - Dice simulation N has to be 6.000.000 before my empirical results match the exact results to three decimal places.
[]
{ "number": "1.1.35", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Experiment" }
Binary search versus brute-force search. Write a program BruteForceSearch that uses the brute-force search method given on page 48 and compare its running time on your computer with that of BinarySearch for largeW.txt and largeT.txt.
1.1.38 - Binary search versus brute-force search largeW.txt results: Bruteforce: 760274 Duration: 9705800 nanoseconds. BinarySearch: 760274 Duration: 112000 nanoseconds. largeT.txt results: Bruteforce: 7328283 Duration: 1325191800 nanoseconds. BinarySearch: 7328279 Duration: 158600 nanoseconds. For testing: https://algs4.cs.princeton.edu/11model/tinyW.txt https://algs4.cs.princeton.edu/11model/tinyT.txt https://algs4.cs.princeton.edu/11model/largeW.txt https://algs4.cs.princeton.edu/11model/largeT.txt
[]
{ "number": "1.1.38", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Experiment" }
Write a Point2D client that takes an integer value N from the command line, generates N random points in the unit square, and computes the distance separating the closest pair of points.
1.1.1 a) 7 b) 200.0000002 c) true
[]
{ "number": "1.2.1", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.2, "section_title": "Data Abstraction", "type": "Exercise" }
Write an Interval1D client that takes an int value N as command-line argument, reads N intervals (each defined by a pair of double values) from standard input, and prints all pairs that intersect.
1.1.2 a) 1.618 -> double b) 10.0 -> double c) true -> boolean d) 33 -> String
[]
{ "number": "1.2.2", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.2, "section_title": "Data Abstraction", "type": "Exercise" }
What does the following code fragment print? String string1 = "hello"; String string2 = string1; string1 = "world"; StdOut.println(string1); StdOut.println(string2);
1.1.4 a) No such keyword as "then" in Java language b) Missing Parentheses on if conditional c) Nothing wrong d) Missing semicolon after the "then" clause
[]
{ "number": "1.2.4", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.2, "section_title": "Data Abstraction", "type": "Exercise" }
A string s is a circular rotation of a string t if it matches when the characters are circularly shifted by any number of positions; e.g., ACTGACG is a circular shift of TGACGAC, and vice versa. Detecting this condition is important in the study of genomic sequences. Write a program that checks whether two given strings s and t are circular shifts of one another. Hint: The solution is a one-liner with indexOf(), length(), and string concatenation.
1.1.6 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610
[]
{ "number": "1.2.6", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.2, "section_title": "Data Abstraction", "type": "Exercise" }
What does the following recursive function return? public static String mystery(String s) { int N = s.length(); if (N <= 1) return s; String a = s.substring(0, N/2); String b = s.substring(N/2, N); return mystery(b) + mystery(a); }
1.1.7 a) 3.00009 b) 499500 c) 10000
[]
{ "number": "1.2.7", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.2, "section_title": "Data Abstraction", "type": "Exercise" }
Suppose that a[] and b[] are each integer arrays consisting of millions of integers. What does the follow code do? Is it reasonably efficient? int[] t = a; a = b; b = t;
1.1.8 a) b -> converts the char "b" to String and prints it b) 197 -> sums the char codes of "b" and "c", converts to String and prints it c) e -> sums the char code of "a" with 4, converts it to char and prints it
[]
{ "number": "1.2.8", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.2, "section_title": "Data Abstraction", "type": "Exercise" }
Develop a class VisualCounter that allows both increment and decrement operations. Take two arguments N and max in the constructor, where N specifies the maximum number of operations and max specifies the maximum absolute value for the counter. As a side effect, create a plot showing the value of the counter each time its tally changes.
1.1.10 The array was not initialized and will generate a compile-time error.
[]
{ "number": "1.2.10", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.2, "section_title": "Data Abstraction", "type": "Exercise" }
Add a method dayOfTheWeek() to SmartDate that returns a String value Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, or Sunday, giving the appropriate day of the week for the date. You may assume that the date is in the 21st century.
1.1.12 0 1 2 3 4 4 3 2 1 0
[]
{ "number": "1.2.12", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.2, "section_title": "Data Abstraction", "type": "Exercise" }
Rational numbers. Implement an immutable data type Rational for rational numbers that supports addition, subtraction, multiplication, and division. public class Rational Rational(int numerator, int denominator) Rational plus(Rational b) // sum of this number and b Rational minus(Rational b) // difference of this number and b Rational times(Rational b) // product of this number and b Rational divides(Rational b) // quotient of this number and b boolean equals(Rational that) // is this number equal to that ? String toString() // string representation You do not have to worry about testing for overflow (see Exercise 1.2.17), but use as instance variables two long values that represent the numerator and denominator to limit the possibility of overflow. Use Euclid’s algorithm (see page 4) to ensure that the numerator and denominator never have any common factors. Include a test client that exercises all of your methods.
1.1.16 311361142246
[]
{ "number": "1.2.16", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.2, "section_title": "Data Abstraction", "type": "Creative Problem" }
Robust implementation of rational numbers. Use assertions to develop an implementation of Rational (see Exercise 1.2.16) that is immune to overflow.
1.1.17 The function never stops because it keeps calling itself on the first line, until a StackOverflowError occurs.
[]
{ "number": "1.2.17", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.2, "section_title": "Data Abstraction", "type": "Creative Problem" }
Variance for accumulator. Validate that the following code, which adds the methods var() and stddev() to Accumulator, computes both the mean and variance of the numbers presented as arguments to addDataValue(): public class Accumulator { private double m; private double s; private int N; public void addDataValue(double x) { N++; s = s + 1.0 * (N-1) / N * (x - m) * (x - m); m = m + (x - m) / N; } public double mean() { return m; } public double var() { return s/(N - 1); } public double stddev() { return Math.sqrt(this.var()); } } This implementation is less susceptible to roundoff error than the straightforward implementation based on saving the sum of the squares of the numbers.
1.1.18 mystery(2,25) is equal to 50 mystery(3,11) is equal to 33 mystery(a,b) computes a * b mystery2(2,25) is equal to 33554432 mystery2(3,11) is equal to 177147 mystery2(a,b) computes a^b
[]
{ "number": "1.2.18", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.2, "section_title": "Data Abstraction", "type": "Creative Problem" }
Parsing. Develop the parse constructors for your Date and Transaction implementations of Exercise 1.2.13 that take a single String argument to specify the initialization values, using the formats given in the table below. | type | format | example | |-------------|--------------------------------------------|------------------------| | Date | integers separated by slashes | 5/22/1939 | | Transaction | customer, date, and amount, separated by whitespace | Turing 5/22/1939 11.99 |
1.1.19 The largest value of N that takes less than 1 hour to compute is 51.
[]
{ "number": "1.2.19", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.2, "section_title": "Data Abstraction", "type": "Creative Problem" }
Add a method isFull() to FixedCapacityStackOfStrings.
1.1.1 a) 7 b) 200.0000002 c) true
[]
{ "number": "1.3.1", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Exercise" }
Give the output printed by java Stack for the input it was - the best - of times - - - it was - the - -
1.1.2 a) 1.618 -> double b) 10.0 -> double c) true -> boolean d) 33 -> String
[]
{ "number": "1.3.2", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Exercise" }
Write a stack client Parentheses that reads in a text stream from standard input and uses a stack to determine whether its parentheses are properly balanced. For example, your program should print true for [()]{}{[()()]()} and false for [(]).
1.1.4 a) No such keyword as "then" in Java language b) Missing Parentheses on if conditional c) Nothing wrong d) Missing semicolon after the "then" clause
[]
{ "number": "1.3.4", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Exercise" }
What does the following code fragment do to the queue q? Stack<String> stack = new Stack<String>(); while (!q.isEmpty()) stack.push(q.dequeue()); while (!stack.isEmpty()) q.enqueue(stack.pop());
1.1.6 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610
[]
{ "number": "1.3.6", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Exercise" }
Add a method peek() to Stack that returns the most recently inserted item on the stack (without popping it).
1.1.7 a) 3.00009 b) 499500 c) 10000
[]
{ "number": "1.3.7", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Exercise" }
Give the contents and size of the array for DoublingStackOfStrings with the input it was - the best - of times - - - it was - the - -
1.1.8 a) b -> converts the char "b" to String and prints it b) 197 -> sums the char codes of "b" and "c", converts to String and prints it c) e -> sums the char code of "a" with 4, converts it to char and prints it
[]
{ "number": "1.3.8", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Exercise" }
Write a filter InfixToPostfix that converts an arithmetic expression from infix to postfix.
1.1.10 The array was not initialized and will generate a compile-time error.
[]
{ "number": "1.3.10", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Exercise" }
Write an iterable Stack client that has a static method copy() that takes a stack of strings as argument and returns a copy of the stack. Note: This ability is a prime example of the value of having an iterator, because it allows development of such functionality without changing the basic API.
1.1.12 0 1 2 3 4 4 3 2 1 0
[]
{ "number": "1.3.12", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Exercise" }
Using readInts() on page 126 as a model, write a static method readDates() for Date that reads dates from standard input in the format specified in the table on page 119 and returns an array containing them.
1.1.16 311361142246
[]
{ "number": "1.3.16", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Exercise" }
Do Exercise 1.3.16 for Transaction.
1.1.17 The function never stops because it keeps calling itself on the first line, until a StackOverflowError occurs.
[]
{ "number": "1.3.17", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Exercise" }
Suppose x is a linked-list node and not the last node on the list. What is the effect of the following code fragment? x.next = x.next.next;
1.1.18 mystery(2,25) is equal to 50 mystery(3,11) is equal to 33 mystery(a,b) computes a * b mystery2(2,25) is equal to 33554432 mystery2(3,11) is equal to 177147 mystery2(a,b) computes a^b
[]
{ "number": "1.3.18", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Exercise" }
Give a code fragment that removes the last node in a linked list whose first node is first.
1.1.19 The largest value of N that takes less than 1 hour to compute is 51.
[]
{ "number": "1.3.19", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Exercise" }
Write a method insertAfter() that takes two linked-list Node arguments and inserts the second after the first on its list (and does nothing if either argument is null).
1.1.25 For all N E NaturalNumbers and for all nonnegative integers a <= N and b <= N, the Euclidean algorithm computes the greatest common divisor of a and b. Proving that gcd(a, b) = gcd(b, a % b) gcd(20,5) = gcd(5,0) gcd(20,5) is 5 gcd(5,0) is also 5 http://math.stackexchange.com/questions/1274515/prove-that-euclids-algorithm-computes-the-gcd-of-any-pair-of-nonnegative-intege https://www.whitman.edu/mathematics/higher_math_online/section03.03.html
[]
{ "number": "1.3.25", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Exercise" }
Write a method max() that takes a reference to the first node in a linked list as argument and returns the value of the maximum key in the list. Assume that all keys are positive integers, and return 0 if the list is empty.
1.1.27 - Binomial distribution For binomial(100, 50, 0.25) the estimate is around 5 billion calls.
[]
{ "number": "1.3.27", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Exercise" }
Random bag. A random bag stores a collection of items and supports the following API: public class RandomBag<Item> implements Iterable<Item> RandomBag() // create an empty random bag boolean isEmpty() // is the bag empty? int size() // number of items in the bag void add(Item item) // add an item Write a class RandomBag that implements this API. Note that this API is the same as for Bag, except for the adjective random, which indicates that the iteration should provide the items in random order (all N! permutations equally likely, for each iterator). Hint: Put the items in an array and randomize their order in the iterator’s constructor.
1.1.34 - Filtering Print the maximum and minimum numbers -> Could be implemented as a filter Print the median of the numbers -> Requires saving all values Print the Kth smallest value, for K less than 100 -> Could be implemented as a filter with an array of size K Print the sum of the squares of the numbers -> Could be implemented as a filter Print the average of the N numbers -> Could be implemented as a filter Print the percentage of numbers greater than the average -> Requires saving all values Print the N numbers in increasing order -> Requires saving all values Print the N numbers in random order -> Requires saving all values Thanks to imyuewu (https://github.com/imyuewu) for suggesting a correction for the Kth smallest value case. https://github.com/reneargento/algorithms-sedgewick-wayne/issues/175
[]
{ "number": "1.3.34", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Creative Problem" }
Random queue. A random queue stores a collection of items and supports the following API: public class RandomQueue<Item> RandomQueue() // create an empty random queue boolean isEmpty() // is the queue empty? void enqueue(Item item) // add an item Item dequeue() // remove and return a random item (sample without replacement) Item sample() // return a random item, but do not remove (sample with replacement) Write a class RandomQueue that implements this API. Hint: Use an array representation (with resizing). To remove an item, swap one at a random position (indexed 0 through N-1) with the one at the last position (index N-1). Then delete and return the last object, as in ResizingArrayStack. Write a client that deals bridge hands (13 cards each) using RandomQueue<Card>.
1.1.35 - Dice simulation N has to be 6.000.000 before my empirical results match the exact results to three decimal places.
[]
{ "number": "1.3.35", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Creative Problem" }
Delete kth element. Implement a class that supports the following API: public class GeneralizedQueue<Item> GeneralizedQueue() // create an empty queue boolean isEmpty() // is the queue empty? void insert(Item x) // add an item Item delete(int k) // delete and return the kth least recently inserted item First, develop an implementation that uses an array implementation, and then develop one that uses a linked-list implementation. Note: the algorithms and data structures that we introduce in Chapter 3 make it possible to develop an implementation that can guarantee that both insert() and delete() take time proportional to the logarithm of the number of items in the queue—see Exercise 3.5.27.
1.1.38 - Binary search versus brute-force search largeW.txt results: Bruteforce: 760274 Duration: 9705800 nanoseconds. BinarySearch: 760274 Duration: 112000 nanoseconds. largeT.txt results: Bruteforce: 7328283 Duration: 1325191800 nanoseconds. BinarySearch: 7328279 Duration: 158600 nanoseconds. For testing: https://algs4.cs.princeton.edu/11model/tinyW.txt https://algs4.cs.princeton.edu/11model/tinyT.txt https://algs4.cs.princeton.edu/11model/largeW.txt https://algs4.cs.princeton.edu/11model/largeT.txt
[]
{ "number": "1.3.38", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Creative Problem" }
Forbidden triple for stack generability. Prove that a permutation can be generated by a stack (as in the previous question) if and only if it has no forbidden triple (a, b, c) such that a < b < c with c first, a second, and b third (possibly with other intervening integers between c and a and between a and b).
1.3.46 - Forbidden triple for stack generability Suppose that there is a forbidden triple (a,b,c). Item "c" is popped before "a" and "b", but "a" and "b" are pushed before "c". Thus, when "c" is pushed, both "a" and "b" are on the stack. Therefore, "a" cannot be popped before "b". When pushing items in the order 0, 1, ..., N-1, all items are above smaller items on the stack because they are pushed after smaller items. If a < b, "a" cannot be above "b" on the stack. Therefore, a permutation would not exist when a forbidden triple exists.
[]
{ "number": "1.3.46", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Creative Problem" }
Show that the number of different triples that can be chosen from N items is precisely N(N-1)(N-2)/6. Hint: Use mathematical induction.
1.1.1 a) 7 b) 200.0000002 c) true
[]
{ "number": "1.4.1", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Exercise" }
Modify ThreeSum to work properly even when the int values are so large that adding two of them might cause overflow.
1.1.2 a) 1.618 -> double b) 10.0 -> double c) true -> boolean d) 33 -> String
[]
{ "number": "1.4.2", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Exercise" }
Develop a table like the one on page 181 for TwoSum.
1.1.4 a) No such keyword as "then" in Java language b) Missing Parentheses on if conditional c) Nothing wrong d) Missing semicolon after the "then" clause
[]
{ "number": "1.4.4", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Exercise" }
Give the order of growth (as a function of N) of the running times of each of the following code fragments: a. int sum = 0; for (int n = N; n > 0; n /= 2) for(int i = 0; i < n; i++) sum++; b. int sum = 0; for (int i = 1; i < N; i *= 2) for (int j = 0; j < i; j++) sum++; c. int sum = 0; for (int i = 1; i < N; i *= 2) for (int j = 0; j < N; j++) sum++;
1.1.6 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610
[]
{ "number": "1.4.6", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Exercise" }
Analyze ThreeSum under a cost model that counts arithmetic operations (and comparisons) involving the input numbers.
1.1.7 a) 3.00009 b) 499500 c) 10000
[]
{ "number": "1.4.7", "code_execution": false, "url": null, "params": null, "dependencies": null, "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Exercise" }