{"question": "Add a method isFull() to:\n\n/******************************************************************************\n * Compilation: javac FixedCapacityStackOfStrings.java\n * Execution: java FixedCapacityStackOfStrings\n * Dependencies: StdIn.java StdOut.java\n *\n * Stack of strings implementation with a fixed-size array.\n *\n * % more tobe.txt\n * to be or not to - be - - that - - - is\n *\n * % java FixedCapacityStackOfStrings 5 < tobe.txt\n * to be not that or be\n *\n * Remark: bare-bones implementation. Does not do repeated\n * doubling or null out empty array entries to avoid loitering.\n *\n ******************************************************************************/\n\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\n\npublic class FixedCapacityStackOfStrings implements Iterable {\n private String[] a; // holds the items\n private int n; // number of items in stack\n\n // create an empty stack with given capacity\n public FixedCapacityStackOfStrings(int capacity) {\n a = new String[capacity];\n n = 0;\n }\n\n public boolean isEmpty() {\n return n == 0;\n }\n\npublic void push(String item) {\n a[n++] = item;\n }\n\n public String pop() {\n return a[--n];\n }\n\n public String peek() {\n return a[n-1];\n }\n\n public Iterator iterator() {\n return new ReverseArrayIterator();\n }\n\n // an array iterator, in reverse order\n public class ReverseArrayIterator implements Iterator {\n private int i = n-1;\n\n public boolean hasNext() {\n return i >= 0;\n }\n\n public String next() {\n if (!hasNext()) throw new NoSuchElementException();\n return a[i--];\n }\n }\n\n\n public static void main(String[] args) {\n int max = Integer.parseInt(args[0]);\n FixedCapacityStackOfStrings stack = new FixedCapacityStackOfStrings(max);\n while (!StdIn.isEmpty()) {\n String item = StdIn.readString();\n if (!item.equals(\"-\")) stack.push(item);\n else if (stack.isEmpty()) StdOut.println(\"BAD INPUT\");\n else StdOut.print(stack.pop() + \" \");\n }\n StdOut.println();\n\n // print what's left on the stack\n StdOut.print(\"Left on stack: \");\n for (String s : stack) {\n StdOut.print(s + \" \");\n }\n StdOut.println();\n }\n}", "answer": "/******************************************************************************\n * Compilation: javac FixedCapacityStackOfStrings.java\n * Execution: java FixedCapacityStackOfStrings\n * Dependencies: StdIn.java StdOut.java\n *\n * Stack of strings implementation with a fixed-size array.\n *\n * % more tobe.txt\n * to be or not to - be - - that - - - is\n *\n * % java FixedCapacityStackOfStrings 5 < tobe.txt\n * to be not that or be\n *\n * Remark: bare-bones implementation. Does not do repeated\n * doubling or null out empty array entries to avoid loitering.\n *\n ******************************************************************************/\n\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\n\npublic class FixedCapacityStackOfStrings implements Iterable {\n private String[] a; // holds the items\n private int n; // number of items in stack\n\n // create an empty stack with given capacity\n public FixedCapacityStackOfStrings(int capacity) {\n a = new String[capacity];\n n = 0;\n }\n\n public boolean isEmpty() {\n return n == 0;\n }\n\n public boolean isFull() {\n return n == a.length;\n }\n\n public void push(String item) {\n a[n++] = item;\n }\n\n public String pop() {\n return a[--n];\n }\n\n public String peek() {\n return a[n-1];\n }\n\n public Iterator iterator() {\n return new ReverseArrayIterator();\n }\n\n // an array iterator, in reverse order\n public class ReverseArrayIterator implements Iterator {\n private int i = n-1;\n\n public boolean hasNext() {\n return i >= 0;\n }\n\n public String next() {\n if (!hasNext()) throw new NoSuchElementException();\n return a[i--];\n }\n }\n\n\n public static void main(String[] args) {\n int max = Integer.parseInt(args[0]);\n FixedCapacityStackOfStrings stack = new FixedCapacityStackOfStrings(max);\n while (!StdIn.isEmpty()) {\n String item = StdIn.readString();\n if (!item.equals(\"-\")) stack.push(item);\n else if (stack.isEmpty()) StdOut.println(\"BAD INPUT\");\n else StdOut.print(stack.pop() + \" \");\n }\n StdOut.println();\n\n // print what's left on the stack\n StdOut.print(\"Left on stack: \");\n for (String s : stack) {\n StdOut.print(s + \" \");\n }\n StdOut.println();\n }\n}\n", "support_files": ["https://algs4.cs.princeton.edu/13stacks/tobe.txt"], "metadata": {"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"]}} {"question": "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 [(]). ", "answer": "/******************************************************************************\n * Compilation: javac Parentheses.java\n * Execution: java Parentheses\n * Dependencies: In.java Stack.java\n *\n * Reads in a text file and checks to see if the parentheses are balanced.\n *\n * % java Parentheses\n * [()]{}{[()()]()}\n * true\n *\n * % java Parentheses\n * [(])\n * false\n *\n ******************************************************************************/\n\npublic class Parentheses {\n private static final char LEFT_PAREN = '(';\n private static final char RIGHT_PAREN = ')';\n private static final char LEFT_BRACE = '{';\n private static final char RIGHT_BRACE = '}';\n private static final char LEFT_BRACKET = '[';\n private static final char RIGHT_BRACKET = ']';\n\n public static boolean isBalanced(String s) {\n Stack stack = new Stack();\n for (int i = 0; i < s.length(); i++) {\n if (s.charAt(i) == LEFT_PAREN) stack.push(LEFT_PAREN);\n if (s.charAt(i) == LEFT_BRACE) stack.push(LEFT_BRACE);\n if (s.charAt(i) == LEFT_BRACKET) stack.push(LEFT_BRACKET);\n\n if (s.charAt(i) == RIGHT_PAREN) {\n if (stack.isEmpty()) return false;\n if (stack.pop() != LEFT_PAREN) return false;\n }\n\n else if (s.charAt(i) == RIGHT_BRACE) {\n if (stack.isEmpty()) return false;\n if (stack.pop() != LEFT_BRACE) return false;\n }\n\n else if (s.charAt(i) == RIGHT_BRACKET) {\n if (stack.isEmpty()) return false;\n if (stack.pop() != LEFT_BRACKET) return false;\n }\n }\n return stack.isEmpty();\n }\n\n\n public static void main(String[] args) {\n In in = new In();\n String s = in.readAll().trim();\n StdOut.println(isBalanced(s));\n }\n}\n\n", "support_files": [], "metadata": {"number": "1.3.4", "code_execution": true, "url": "https://algs4.cs.princeton.edu/13stacks/Parentheses.java", "params": ["<<< \"[(])\"", "<<< \"[()]{}{[()()]()}\""], "dependencies": ["In.java", "Stack.java"]}} {"question": "Add a method peek() that returns the most recently inserted item on the stack (without popping it) to:\n\n/******************************************************************************\n * Compilation: javac Stack.java\n * Execution: java Stack < input.txt\n * Dependencies: StdIn.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/13stacks/tobe.txt\n *\n * A generic stack, implemented using a singly linked list.\n * Each stack element is of type Item.\n *\n * This version uses a static nested class Node (to save 8 bytes per\n * Node), whereas the version in the textbook uses a non-static nested\n * class (for simplicity).\n *\n * % more tobe.txt\n * to be or not to - be - - that - - - is\n *\n * % java Stack < tobe.txt\n * to be not that or be (2 left on stack)\n *\n ******************************************************************************/\n\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\n\n\n/**\n * The {@code Stack} class represents a last-in-first-out (LIFO) stack of generic items.\n * It supports the usual push and pop operations, along with methods\n * for peeking at the top item, testing if the stack is empty, and iterating through\n * the items in LIFO order.\n *

\n * This implementation uses a singly linked list with a static nested class for\n * linked-list nodes. See {@link LinkedStack} for the version from the\n * textbook that uses a non-static nested class.\n * See {@link ResizingArrayStack} for a version that uses a resizing array.\n * The push, pop, peek, size, and is-empty\n * operations all take constant time in the worst case.\n *

\n * For additional documentation,\n * see Section 1.3 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n *\n * @param the generic type each item in this stack\n */\npublic class Stack implements Iterable {\n private Node first; // top of stack\n private int n; // size of the stack\n\n // helper linked list class\n private static class Node {\n private Item item;\n private Node next;\n }\n\n /**\n * Initializes an empty stack.\n */\n public Stack() {\n first = null;\n n = 0;\n }\n\n /**\n * Returns true if this stack is empty.\n *\n * @return true if this stack is empty; false otherwise\n */\n public boolean isEmpty() {\n return first == null;\n }\n\n /**\n * Returns the number of items in this stack.\n *\n * @return the number of items in this stack\n */\n public int size() {\n return n;\n }\n\n /**\n * Adds the item to this stack.\n *\n * @param item the item to add\n */\n public void push(Item item) {\n Node oldfirst = first;\n first = new Node();\n first.item = item;\n first.next = oldfirst;\n n++;\n }\n\n /**\n * Removes and returns the item most recently added to this stack.\n *\n * @return the item most recently added\n * @throws NoSuchElementException if this stack is empty\n */\n public Item pop() {\n if (isEmpty()) throw new NoSuchElementException(\"Stack underflow\");\n Item item = first.item; // save item to return\n first = first.next; // delete first node\n n--;\n return item; // return the saved item\n }\n\n\n /**\n * Returns (but does not remove) the item most recently added to this stack.\n *\n * @return the item most recently added to this stack\n * @throws NoSuchElementException if this stack is empty\n */\n\n/**\n * Returns a string representation of this stack.\n *\n * @return the sequence of items in this stack in LIFO order, separated by spaces\n */\n public String toString() {\n StringBuilder s = new StringBuilder();\n for (Item item : this) {\n s.append(item);\n s.append(' ');\n }\n return s.toString();\n }\n\n\n /**\n * Returns an iterator to this stack that iterates through the items in LIFO order.\n *\n * @return an iterator to this stack that iterates through the items in LIFO order\n */\n public Iterator iterator() {\n return new LinkedIterator(first);\n }\n\n // the iterator\n private class LinkedIterator implements Iterator {\n private Node current;\n\n public LinkedIterator(Node first) {\n current = first;\n }\n\n // is there a next item?\n public boolean hasNext() {\n return current != null;\n }\n\n // returns the next item\n public Item next() {\n if (!hasNext()) throw new NoSuchElementException();\n Item item = current.item;\n current = current.next;\n return item;\n }\n }\n\n\n /**\n * Unit tests the {@code Stack} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n Stack stack = new Stack();\n while (!StdIn.isEmpty()) {\n String item = StdIn.readString();\n if (!item.equals(\"-\"))\n stack.push(item);\n else if (!stack.isEmpty())\n StdOut.print(stack.pop() + \" \");\n }\n StdOut.println(\"(\" + stack.size() + \" left on stack)\");\n }\n}", "answer": "/******************************************************************************\n * Compilation: javac Stack.java\n * Execution: java Stack < input.txt\n * Dependencies: StdIn.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/13stacks/tobe.txt\n *\n * A generic stack, implemented using a singly linked list.\n * Each stack element is of type Item.\n *\n * This version uses a static nested class Node (to save 8 bytes per\n * Node), whereas the version in the textbook uses a non-static nested\n * class (for simplicity).\n *\n * % more tobe.txt\n * to be or not to - be - - that - - - is\n *\n * % java Stack < tobe.txt\n * to be not that or be (2 left on stack)\n *\n ******************************************************************************/\n\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\n\n\n/**\n * The {@code Stack} class represents a last-in-first-out (LIFO) stack of generic items.\n * It supports the usual push and pop operations, along with methods\n * for peeking at the top item, testing if the stack is empty, and iterating through\n * the items in LIFO order.\n *

\n * This implementation uses a singly linked list with a static nested class for\n * linked-list nodes. See {@link LinkedStack} for the version from the\n * textbook that uses a non-static nested class.\n * See {@link ResizingArrayStack} for a version that uses a resizing array.\n * The push, pop, peek, size, and is-empty\n * operations all take constant time in the worst case.\n *

\n * For additional documentation,\n * see Section 1.3 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n *\n * @param the generic type each item in this stack\n */\npublic class Stack implements Iterable {\n private Node first; // top of stack\n private int n; // size of the stack\n\n // helper linked list class\n private static class Node {\n private Item item;\n private Node next;\n }\n\n /**\n * Initializes an empty stack.\n */\n public Stack() {\n first = null;\n n = 0;\n }\n\n /**\n * Returns true if this stack is empty.\n *\n * @return true if this stack is empty; false otherwise\n */\n public boolean isEmpty() {\n return first == null;\n }\n\n /**\n * Returns the number of items in this stack.\n *\n * @return the number of items in this stack\n */\n public int size() {\n return n;\n }\n\n /**\n * Adds the item to this stack.\n *\n * @param item the item to add\n */\n public void push(Item item) {\n Node oldfirst = first;\n first = new Node();\n first.item = item;\n first.next = oldfirst;\n n++;\n }\n\n /**\n * Removes and returns the item most recently added to this stack.\n *\n * @return the item most recently added\n * @throws NoSuchElementException if this stack is empty\n */\n public Item pop() {\n if (isEmpty()) throw new NoSuchElementException(\"Stack underflow\");\n Item item = first.item; // save item to return\n first = first.next; // delete first node\n n--;\n return item; // return the saved item\n }\n\n\n /**\n * Returns (but does not remove) the item most recently added to this stack.\n *\n * @return the item most recently added to this stack\n * @throws NoSuchElementException if this stack is empty\n */\n public Item peek() {\n if (isEmpty()) throw new NoSuchElementException(\"Stack underflow\");\n return first.item;\n }\n\n /**\n * Returns a string representation of this stack.\n *\n * @return the sequence of items in this stack in LIFO order, separated by spaces\n */\n public String toString() {\n StringBuilder s = new StringBuilder();\n for (Item item : this) {\n s.append(item);\n s.append(' ');\n }\n return s.toString();\n }\n\n\n /**\n * Returns an iterator to this stack that iterates through the items in LIFO order.\n *\n * @return an iterator to this stack that iterates through the items in LIFO order\n */\n public Iterator iterator() {\n return new LinkedIterator(first);\n }\n\n // the iterator\n private class LinkedIterator implements Iterator {\n private Node current;\n\n public LinkedIterator(Node first) {\n current = first;\n }\n\n // is there a next item?\n public boolean hasNext() {\n return current != null;\n }\n\n // returns the next item\n public Item next() {\n if (!hasNext()) throw new NoSuchElementException();\n Item item = current.item;\n current = current.next;\n return item;\n }\n }\n\n\n /**\n * Unit tests the {@code Stack} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n Stack stack = new Stack();\n while (!StdIn.isEmpty()) {\n String item = StdIn.readString();\n if (!item.equals(\"-\"))\n stack.push(item);\n else if (!stack.isEmpty())\n StdOut.print(stack.pop() + \" \");\n }\n StdOut.println(\"(\" + stack.size() + \" left on stack)\");\n }\n}\n\n", "support_files": ["https://algs4.cs.princeton.edu/13stacks/tobe.txt"], "metadata": {"number": "1.3.7", "code_execution": true, "url": "https://algs4.cs.princeton.edu/13stacks/Stack.java", "params": ["< tobe.txt"], "dependencies": ["StdIn.java", "StdOut.java"]}} {"question": "Write a filter Program InfixToPostfix.java that converts an arithmetic expression from infix to postfix. ", "answer": "/******************************************************************************\n * Compilation: javac InfixToPostfix.java\n * Execution: java InfixToPostFix\n * Dependencies: Stack.java StdIn.java StdOut.java\n *\n * Reads in a fully parenthesized infix expression from standard input\n * and prints an equivalent postfix expression to standard output.\n *\n * Windows users: replace [Ctrl-d] with [Ctrl-z] to signify end of file.\n *\n * % java InfixToPostfix\n * ( 2 + ( ( 3 + 4 ) * ( 5 * 6 ) ) )\n * [Ctrl-d]\n * 2 3 4 + 5 6 * * +\n *\n * % java InfixToPostfix\n * ( ( ( 5 + ( 7 * ( 1 + 1 ) ) ) * 3 ) + ( 2 * ( 1 + 1 ) ) )\n * 5 7 1 1 + * + 3 * 2 1 1 + * +\n *\n * % java InfixToPostfix | java EvaluatePostfix\n * ( 2 + ( ( 3 + 4 ) * ( 5 * 6 ) ) )\n * [Ctrl-d]\n * 212\n *\n ******************************************************************************/\n\npublic class InfixToPostfix {\n public static void main(String[] args) {\n Stack stack = new Stack();\n while (!StdIn.isEmpty()) {\n String s = StdIn.readString();\n if (s.equals(\"+\")) stack.push(s);\n else if (s.equals(\"*\")) stack.push(s);\n else if (s.equals(\")\")) StdOut.print(stack.pop() + \" \");\n else if (s.equals(\"(\")) StdOut.print(\"\");\n else StdOut.print(s + \" \");\n }\n StdOut.println();\n }\n}\n\n", "support_files": [], "metadata": {"number": "1.3.10", "code_execution": true, "url": "https://algs4.cs.princeton.edu/13stacks/InfixToPostfix.java", "params": ["< stack = new Stack();\n\n while (!StdIn.isEmpty()) {\n String s = StdIn.readString();\n if (s.equals(\"+\")) stack.push(stack.pop() + stack.pop());\n else if (s.equals(\"*\")) stack.push(stack.pop() * stack.pop());\n else stack.push(Integer.parseInt(s));\n }\n StdOut.println(stack.pop());\n }\n}\n\n", "support_files": [], "metadata": {"number": "1.3.11", "code_execution": true, "url": "https://algs4.cs.princeton.edu/13stacks/EvaluatePostfix.java", "params": ["<enqueue and dequeue\n * operations, along with methods for peeking at the first item,\n * testing if the queue is empty, and iterating through\n * the items in FIFO order.\n *

\n * This implementation uses a resizing array, which double the underlying array\n * when it is full and halves the underlying array when it is one-quarter full.\n * The enqueue and dequeue operations take constant amortized time.\n * The size, peek, and is-empty operations takes\n * constant time in the worst case.\n *

\n * For additional documentation, see Section 1.3 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class ResizingArrayQueue implements Iterable {\n // initial capacity of underlying resizing array\n private static final int INIT_CAPACITY = 8;\n\n private Item[] q; // queue elements\n private int n; // number of elements on queue\n private int first; // index of first element of queue\n private int last; // index of next available slot\n\n\n /**\n * Initializes an empty queue.\n */\n public ResizingArrayQueue() {\n q = (Item[]) new Object[INIT_CAPACITY];\n n = 0;\n first = 0;\n last = 0;\n }\n\n /**\n * Is this queue empty?\n * @return true if this queue is empty; false otherwise\n */\n public boolean isEmpty() {\n return n == 0;\n }\n\n /**\n * Returns the number of items in this queue.\n * @return the number of items in this queue\n */\n public int size() {\n return n;\n }\n\n // resize the underlying array\n private void resize(int capacity) {\n assert capacity >= n;\n Item[] copy = (Item[]) new Object[capacity];\n for (int i = 0; i < n; i++) {\n copy[i] = q[(first + i) % q.length];\n }\n q = copy;\n first = 0;\n last = n;\n }\n\n /**\n * Adds the item to this queue.\n * @param item the item to add\n */\n public void enqueue(Item item) {\n // double size of array if necessary and recopy to front of array\n if (n == q.length) resize(2*q.length); // double size of array if necessary\n q[last++] = item; // add item\n if (last == q.length) last = 0; // wrap-around\n n++;\n }\n\n /**\n * Removes and returns the item on this queue that was least recently added.\n * @return the item on this queue that was least recently added\n * @throws java.util.NoSuchElementException if this queue is empty\n */\n public Item dequeue() {\n if (isEmpty()) throw new NoSuchElementException(\"Queue underflow\");\n Item item = q[first];\n q[first] = null; // to avoid loitering\n n--;\n first++;\n if (first == q.length) first = 0; // wrap-around\n // shrink size of array if necessary\n if (n > 0 && n == q.length/4) resize(q.length/2);\n return item;\n }\n\n /**\n * Returns the item least recently added to this queue.\n * @return the item least recently added to this queue\n * @throws java.util.NoSuchElementException if this queue is empty\n */\n public Item peek() {\n if (isEmpty()) throw new NoSuchElementException(\"Queue underflow\");\n return q[first];\n }\n\n\n /**\n * Returns an iterator that iterates over the items in this queue in FIFO order.\n * @return an iterator that iterates over the items in this queue in FIFO order\n */\n public Iterator iterator() {\n return new ArrayIterator();\n }\n\n // an array iterator, from first to last-1\n private class ArrayIterator implements Iterator {\n private int i = 0;\n\n public boolean hasNext() {\n return i < n;\n }\n\n public Item next() {\n if (!hasNext()) throw new NoSuchElementException();\n Item item = q[(i + first) % q.length];\n i++;\n return item;\n }\n }\n\n /**\n * Unit tests the {@code ResizingArrayQueue} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n ResizingArrayQueue queue = new ResizingArrayQueue();\n while (!StdIn.isEmpty()) {\n String item = StdIn.readString();\n if (!item.equals(\"-\")) queue.enqueue(item);\n else if (!queue.isEmpty()) StdOut.print(queue.dequeue() + \" \");\n }\n StdOut.println(\"(\" + queue.size() + \" left on queue)\");\n }\n\n}\n", "support_files": ["https://algs4.cs.princeton.edu/13stacks/tobe.txt"], "metadata": {"number": "1.3.14", "code_execution": true, "url": "https://algs4.cs.princeton.edu/13stacks/ResizingArrayQueue.java", "params": ["< tobe.txt"], "dependencies": ["StdIn.java", "StdOut.java"]}} {"question": "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).\n\n % java Josephus 2 7\n 1 3 5 0 4 2 6\n", "answer": "/******************************************************************************\n * Compilation: javac Josephus.java\n * Execution: java Josephus m n\n * Dependencies: Queue.java\n *\n * Solves the Josephus problem.\n *\n * % java Josephus 2 7\n * 1 3 5 0 4 2 6\n *\n ******************************************************************************/\n\npublic class Josephus {\n public static void main(String[] args) {\n int m = Integer.parseInt(args[0]);\n int n = Integer.parseInt(args[1]);\n\n // initialize the queue\n Queue queue = new Queue();\n for (int i = 0; i < n; i++)\n queue.enqueue(i);\n\n while (!queue.isEmpty()) {\n for (int i = 0; i < m-1; i++)\n queue.enqueue(queue.dequeue());\n StdOut.print(queue.dequeue() + \" \");\n }\n StdOut.println();\n }\n}\n\n", "support_files": [], "metadata": {"number": "1.3.37", "code_execution": true, "url": "https://algs4.cs.princeton.edu/13stacks/Josephus.java", "params": ["2 7"], "dependencies": ["Queue.java"]}} {"question": "Develop classes QuickUnionUF.java that implement quick-union.", "answer": "/******************************************************************************\n * Compilation: javac QuickUnionUF.java\n * Execution: java QuickUnionUF < input.txt\n * Dependencies: StdIn.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/15uf/tinyUF.txt\n * https://algs4.cs.princeton.edu/15uf/mediumUF.txt\n * https://algs4.cs.princeton.edu/15uf/largeUF.txt\n *\n * Quick-union algorithm.\n *\n ******************************************************************************/\n\n/**\n * The {@code QuickUnionUF} class represents a union–find data type\n * (also known as the disjoint-sets data type).\n * It supports the classic union and find operations,\n * along with a count operation that returns the total number\n * of sets.\n *

\n * The union–find data type models a collection of sets containing\n * n elements, with each element in exactly one set.\n * The elements are named 0 through n–1.\n * Initially, there are n sets, with each element in its\n * own set. The canonical element of a set\n * (also known as the root, identifier,\n * leader, or set representative)\n * is one distinguished element in the set. Here is a summary of\n * the operations:\n *

    \n *
  • find(p) returns the canonical element\n * of the set containing p. The find operation\n * returns the same value for two elements if and only if\n * they are in the same set.\n *
  • union(p, q) merges the set\n * containing element p with the set containing\n * element q. That is, if p and q\n * are in different sets, replace these two sets\n * with a new set that is the union of the two.\n *
  • count() returns the number of sets.\n *
\n *

\n * The canonical element of a set can change only when the set\n * itself changes during a call to union—it cannot\n * change during a call to either find or count.\n *

\n * This implementation uses quick union.\n * The constructor takes Θ(n) time, where\n * n is the number of sites.\n * The union and find operations take\n * Θ(n) time in the worst case.\n * The count operation takes Θ(1) time.\n *

\n * For alternative implementations of the same API, see\n * {@link UF}, {@link QuickFindUF}, and {@link WeightedQuickUnionUF}.\n * For additional documentation,\n * see Section 1.5 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class QuickUnionUF {\n private int[] parent; // parent[i] = parent of i\n private int count; // number of components\n\n /**\n * Initializes an empty union-find data structure with\n * {@code n} elements {@code 0} through {@code n-1}.\n * Initially, each element is in its own set.\n *\n * @param n the number of elements\n * @throws IllegalArgumentException if {@code n < 0}\n */\n public QuickUnionUF(int n) {\n parent = new int[n];\n count = n;\n for (int i = 0; i < n; i++) {\n parent[i] = i;\n }\n }\n\n /**\n * Returns the number of sets.\n *\n * @return the number of sets (between {@code 1} and {@code n})\n */\n public int count() {\n return count;\n }\n\n /**\n * Returns the canonical element of the set containing element {@code p}.\n *\n * @param p an element\n * @return the canonical element of the set containing {@code p}\n * @throws IllegalArgumentException unless {@code 0 <= p < n}\n */\n public int find(int p) {\n validate(p);\n while (p != parent[p])\n p = parent[p];\n return p;\n }\n\n // validate that p is a valid index\n private void validate(int p) {\n int n = parent.length;\n if (p < 0 || p >= n) {\n throw new IllegalArgumentException(\"index \" + p + \" is not between 0 and \" + (n-1));\n }\n }\n\n /**\n * Returns true if the two elements are in the same set.\n *\n * @param p one element\n * @param q the other element\n * @return {@code true} if {@code p} and {@code q} are in the same set;\n * {@code false} otherwise\n * @throws IllegalArgumentException unless\n * both {@code 0 <= p < n} and {@code 0 <= q < n}\n * @deprecated Replace with two calls to {@link #find(int)}.\n */\n @Deprecated\n public boolean connected(int p, int q) {\n return find(p) == find(q);\n }\n\n /**\n * Merges the set containing element {@code p} with the set\n * containing element {@code q}.\n *\n * @param p one element\n * @param q the other element\n * @throws IllegalArgumentException unless\n * both {@code 0 <= p < n} and {@code 0 <= q < n}\n */\n public void union(int p, int q) {\n int rootP = find(p);\n int rootQ = find(q);\n if (rootP == rootQ) return;\n parent[rootP] = rootQ;\n count--;\n }\n\n /**\n * Reads an integer {@code n} and a sequence of pairs of integers\n * (between {@code 0} and {@code n-1}) from standard input, where each integer\n * in the pair represents some element;\n * if the elements are in different sets, merge the two sets\n * and print the pair to standard output.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n int n = StdIn.readInt();\n QuickUnionUF uf = new QuickUnionUF(n);\n while (!StdIn.isEmpty()) {\n int p = StdIn.readInt();\n int q = StdIn.readInt();\n if (uf.find(p) == uf.find(q)) continue;\n uf.union(p, q);\n StdOut.println(p + \" \" + q);\n }\n StdOut.println(uf.count() + \" components\");\n }\n\n\n}\n", "support_files": ["https://algs4.cs.princeton.edu/15uf/tinyUF.txt", "https://algs4.cs.princeton.edu/15uf/mediumUF.txt"], "metadata": {"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"]}} {"question": "Develop classes QuickFindUF.java that implement quick-find.", "answer": "/******************************************************************************\n * Compilation: javac QuickFindUF.java\n * Execution: java QuickFindUF < input.txt\n * Dependencies: StdIn.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/15uf/tinyUF.txt\n * https://algs4.cs.princeton.edu/15uf/mediumUF.txt\n * https://algs4.cs.princeton.edu/15uf/largeUF.txt\n *\n * Quick-find algorithm.\n *\n ******************************************************************************/\n\n/**\n * The {@code QuickFindUF} class represents a union–find data type\n * (also known as the disjoint-sets data type).\n * It supports the classic union and find operations,\n * along with a count operation that returns the total number\n * of sets.\n *

\n * The union–find data type models a collection of sets containing\n * n elements, with each element in exactly one set.\n * The elements are named 0 through n–1.\n * Initially, there are n sets, with each element in its\n * own set. The canonical element of a set\n * (also known as the root, identifier,\n * leader, or set representative)\n * is one distinguished element in the set. Here is a summary of\n * the operations:\n *

    \n *
  • find(p) returns the canonical element\n * of the set containing p. The find operation\n * returns the same value for two elements if and only if\n * they are in the same set.\n *
  • union(p, q) merges the set\n * containing element p with the set containing\n * element q. That is, if p and q\n * are in different sets, replace these two sets\n * with a new set that is the union of the two.\n *
  • count() returns the number of sets.\n *
\n *

\n * The canonical element of a set can change only when the set\n * itself changes during a call to union—it cannot\n * change during a call to either find or count.\n *

\n * This implementation uses quick find.\n * The constructor takes Θ(n) time, where n\n * is the number of sites.\n * The find, connected, and count\n * operations take Θ(1) time; the union operation\n * takes Θ(n) time.\n *

\n * For alternative implementations of the same API, see\n * {@link UF}, {@link QuickUnionUF}, and {@link WeightedQuickUnionUF}.\n * For additional documentation, see\n * Section 1.5 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\n\npublic class QuickFindUF {\n private int[] id; // id[i] = component identifier of i\n private int count; // number of components\n\n /**\n * Initializes an empty union-find data structure with\n * {@code n} elements {@code 0} through {@code n-1}.\n * Initially, each element is in its own set.\n *\n * @param n the number of elements\n * @throws IllegalArgumentException if {@code n < 0}\n */\n public QuickFindUF(int n) {\n count = n;\n id = new int[n];\n for (int i = 0; i < n; i++)\n id[i] = i;\n }\n\n /**\n * Returns the number of sets.\n *\n * @return the number of sets (between {@code 1} and {@code n})\n */\n public int count() {\n return count;\n }\n\n /**\n * Returns the canonical element of the set containing element {@code p}.\n *\n * @param p an element\n * @return the canonical element of the set containing {@code p}\n * @throws IllegalArgumentException unless {@code 0 <= p < n}\n */\n public int find(int p) {\n validate(p);\n return id[p];\n }\n\n // validate that p is a valid index\n private void validate(int p) {\n int n = id.length;\n if (p < 0 || p >= n) {\n throw new IllegalArgumentException(\"index \" + p + \" is not between 0 and \" + (n-1));\n }\n }\n\n /**\n * Returns true if the two elements are in the same set.\n *\n * @param p one element\n * @param q the other element\n * @return {@code true} if {@code p} and {@code q} are in the same set;\n * {@code false} otherwise\n * @throws IllegalArgumentException unless\n * both {@code 0 <= p < n} and {@code 0 <= q < n}\n * @deprecated Replace with two calls to {@link #find(int)}.\n */\n @Deprecated\n public boolean connected(int p, int q) {\n validate(p);\n validate(q);\n return id[p] == id[q];\n }\n\n /**\n * Merges the set containing element {@code p} with the set\n * containing element {@code q}.\n *\n * @param p one element\n * @param q the other element\n * @throws IllegalArgumentException unless\n * both {@code 0 <= p < n} and {@code 0 <= q < n}\n */\n public void union(int p, int q) {\n validate(p);\n validate(q);\n int pID = id[p]; // needed for correctness\n int qID = id[q]; // to reduce the number of array accesses\n\n // p and q are already in the same component\n if (pID == qID) return;\n\n for (int i = 0; i < id.length; i++)\n if (id[i] == pID) id[i] = qID;\n count--;\n }\n\n /**\n * Reads an integer {@code n} and a sequence of pairs of integers\n * (between {@code 0} and {@code n-1}) from standard input, where each integer\n * in the pair represents some element;\n * if the elements are in different sets, merge the two sets\n * and print the pair to standard output.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n int n = StdIn.readInt();\n QuickFindUF uf = new QuickFindUF(n);\n while (!StdIn.isEmpty()) {\n int p = StdIn.readInt();\n int q = StdIn.readInt();\n if (uf.find(p) == uf.find(q)) continue;\n uf.union(p, q);\n StdOut.println(p + \" \" + q);\n }\n StdOut.println(uf.count() + \" components\");\n }\n\n}\n", "support_files": ["https://algs4.cs.princeton.edu/15uf/tinyUF.txt", "https://algs4.cs.princeton.edu/15uf/mediumUF.txt"], "metadata": {"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"]}} {"question": "Transaction sort test client. Write a class SortTransactions.java that consists of a static method main() that reads a sequence of transactions from standard\ninput, sorts them, and prints the result on standard output.", "answer": "/******************************************************************************\n * Compilation: javac SortTransactions.java\n * Execution: java SortTransactions < input.txt\n * Dependencies: StdOut.java\n * Data file: https://algs4.cs.princeton.edu/21elementary/tinyBatch.txt\n *\n * % java SortTransactions < transactions.txt\n * Turing 1/11/2002 66.10\n * Knuth 6/14/1999 288.34\n * Turing 6/17/1990 644.08\n * Dijkstra 9/10/2000 708.95\n * Dijkstra 11/18/1995 837.42\n * Hoare 8/12/2003 1025.70\n * Bellman 10/26/2007 1358.62\n * Knuth 7/25/2008 1564.55\n * Turing 2/11/1991 2156.86\n * Tarjan 10/13/1993 2520.97\n * Dijkstra 8/22/2007 2678.40\n * Hoare 5/10/1993 3229.27\n * Knuth 11/11/2008 3284.33\n * Turing 10/12/1993 3532.36\n * Hoare 2/10/2005 4050.20\n * Tarjan 3/26/2002 4121.85\n * Hoare 8/18/1992 4381.21\n * Tarjan 1/11/1999 4409.74\n * Tarjan 2/12/1994 4732.35\n * Thompson 2/27/2000 4747.08\n *\n ******************************************************************************/\n\nimport java.util.Arrays;\n\npublic class SortTransactions {\n public static Transaction[] readTransactions() {\n Queue queue = new Queue();\n while (StdIn.hasNextLine()) {\n String line = StdIn.readLine();\n Transaction transaction = new Transaction(line);\n queue.enqueue(transaction);\n }\n\n int n = queue.size();\n Transaction[] transactions = new Transaction[n];\n for (int i = 0; i < n; i++)\n transactions[i] = queue.dequeue();\n\n return transactions;\n }\n\n public static void main(String[] args) {\n Transaction[] transactions = readTransactions();\n Arrays.sort(transactions);\n for (int i = 0; i < transactions.length; i++)\n StdOut.println(transactions[i]);\n }\n}\n", "support_files": ["https://algs4.cs.princeton.edu/21elementary/tinyBatch.txt"], "metadata": {"number": "2.1.22", "code_execution": true, "url": "https://algs4.cs.princeton.edu/21elementary/SortTransactions.java", "params": ["< tinyBatch.txt"], "dependencies": ["StdOut.java"]}} {"question": "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", "answer": "/******************************************************************************\n * Compilation: javac InsertionX.java\n * Execution: java InsertionX < input.txt\n * Dependencies: StdOut.java StdIn.java\n * Data files: https://algs4.cs.princeton.edu/21elementary/tiny.txt\n * https://algs4.cs.princeton.edu/21elementary/words3.txt\n *\n * Sorts a sequence of strings from standard input using an optimized\n * version of insertion sort that uses half exchanges instead of\n * full exchanges to reduce data movement..\n *\n * % more tiny.txt\n * S O R T E X A M P L E\n *\n * % java InsertionX < tiny.txt\n * A E E L M O P R S T X [ one string per line ]\n *\n * % more words3.txt\n * bed bug dad yes zoo ... all bad yet\n *\n * % java InsertionX < words3.txt\n * all bad bed bug dad ... yes yet zoo [ one string per line ]\n *\n ******************************************************************************/\n/**\n * The {@code InsertionX} class provides static methods for sorting\n * an array using an optimized version of insertion sort (with half exchanges\n * and a sentinel).\n *

\n * In the worst case, this implementation makes ~ 1/2 n2\n * compares to sort an array of length n.\n * So, it is not suitable for sorting large arrays\n * (unless the number of inversions is small).\n *

\n * This sorting algorithm is stable.\n * It uses Θ(1) extra memory (not including the input array).\n *

\n * For additional documentation, see\n * Section 2.1 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\n\npublic class InsertionX {\n\n // This class should not be instantiated.\n private InsertionX() { }\n\n /**\n * Rearranges the array in ascending order, using the natural order.\n * @param a the array to be sorted\n */\n public static void sort(Comparable[] a) {\n int n = a.length;\n\n // put smallest element in position to serve as sentinel\n int exchanges = 0;\n for (int i = n-1; i > 0; i--) {\n if (less(a[i], a[i-1])) {\n exch(a, i, i-1);\n exchanges++;\n }\n }\n if (exchanges == 0) return;\n\n\n // insertion sort with half-exchanges\n for (int i = 2; i < n; i++) {\n Comparable v = a[i];\n int j = i;\n while (less(v, a[j-1])) {\n a[j] = a[j-1];\n j--;\n }\n a[j] = v;\n }\n\n assert isSorted(a);\n }\n\n\n /***************************************************************************\n * Helper sorting functions.\n ***************************************************************************/\n\n // is v < w ?\n private static boolean less(Comparable v, Comparable w) {\n return v.compareTo(w) < 0;\n }\n\n // exchange a[i] and a[j]\n private static void exch(Object[] a, int i, int j) {\n Object swap = a[i];\n a[i] = a[j];\n a[j] = swap;\n }\n\n\n /***************************************************************************\n * Check if array is sorted - useful for debugging.\n ***************************************************************************/\n private static boolean isSorted(Comparable[] a) {\n for (int i = 1; i < a.length; i++)\n if (less(a[i], a[i-1])) return false;\n return true;\n }\n\n // print array to standard output\n private static void show(Comparable[] a) {\n for (int i = 0; i < a.length; i++) {\n StdOut.println(a[i]);\n }\n }\n\n /**\n * Reads in a sequence of strings from standard input; insertion sorts them;\n * and prints them to standard output in ascending order.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n String[] a = StdIn.readAllStrings();\n InsertionX.sort(a);\n show(a);\n }\n\n}\n", "support_files": ["https://algs4.cs.princeton.edu/21elementary/tiny.txt", "https://algs4.cs.princeton.edu/21elementary/words3.txt"], "metadata": {"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"]}} {"question": "Insertion sort without exchanges. Develop an implementation InsertionX.java of insertion sort that moves larger items to the right one position rather\nthan doing full exchanges.", "answer": "/******************************************************************************\n * Compilation: javac InsertionX.java\n * Execution: java InsertionX < input.txt\n * Dependencies: StdOut.java StdIn.java\n * Data files: https://algs4.cs.princeton.edu/21elementary/tiny.txt\n * https://algs4.cs.princeton.edu/21elementary/words3.txt\n *\n * Sorts a sequence of strings from standard input using an optimized\n * version of insertion sort that uses half exchanges instead of\n * full exchanges to reduce data movement..\n *\n * % more tiny.txt\n * S O R T E X A M P L E\n *\n * % java InsertionX < tiny.txt\n * A E E L M O P R S T X [ one string per line ]\n *\n * % more words3.txt\n * bed bug dad yes zoo ... all bad yet\n *\n * % java InsertionX < words3.txt\n * all bad bed bug dad ... yes yet zoo [ one string per line ]\n *\n ******************************************************************************/\n/**\n * The {@code InsertionX} class provides static methods for sorting\n * an array using an optimized version of insertion sort (with half exchanges\n * and a sentinel).\n *

\n * In the worst case, this implementation makes ~ 1/2 n2\n * compares to sort an array of length n.\n * So, it is not suitable for sorting large arrays\n * (unless the number of inversions is small).\n *

\n * This sorting algorithm is stable.\n * It uses Θ(1) extra memory (not including the input array).\n *

\n * For additional documentation, see\n * Section 2.1 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\n\npublic class InsertionX {\n\n // This class should not be instantiated.\n private InsertionX() { }\n\n /**\n * Rearranges the array in ascending order, using the natural order.\n * @param a the array to be sorted\n */\n public static void sort(Comparable[] a) {\n int n = a.length;\n\n // put smallest element in position to serve as sentinel\n int exchanges = 0;\n for (int i = n-1; i > 0; i--) {\n if (less(a[i], a[i-1])) {\n exch(a, i, i-1);\n exchanges++;\n }\n }\n if (exchanges == 0) return;\n\n\n // insertion sort with half-exchanges\n for (int i = 2; i < n; i++) {\n Comparable v = a[i];\n int j = i;\n while (less(v, a[j-1])) {\n a[j] = a[j-1];\n j--;\n }\n a[j] = v;\n }\n\n assert isSorted(a);\n }\n\n\n /***************************************************************************\n * Helper sorting functions.\n ***************************************************************************/\n\n // is v < w ?\n private static boolean less(Comparable v, Comparable w) {\n return v.compareTo(w) < 0;\n }\n\n // exchange a[i] and a[j]\n private static void exch(Object[] a, int i, int j) {\n Object swap = a[i];\n a[i] = a[j];\n a[j] = swap;\n }\n\n\n /***************************************************************************\n * Check if array is sorted - useful for debugging.\n ***************************************************************************/\n private static boolean isSorted(Comparable[] a) {\n for (int i = 1; i < a.length; i++)\n if (less(a[i], a[i-1])) return false;\n return true;\n }\n\n // print array to standard output\n private static void show(Comparable[] a) {\n for (int i = 0; i < a.length; i++) {\n StdOut.println(a[i]);\n }\n }\n\n /**\n * Reads in a sequence of strings from standard input; insertion sorts them;\n * and prints them to standard output in ascending order.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n String[] a = StdIn.readAllStrings();\n InsertionX.sort(a);\n show(a);\n }\n\n}\n", "support_files": ["https://algs4.cs.princeton.edu/21elementary/tiny.txt", "https://algs4.cs.princeton.edu/21elementary/words3.txt"], "metadata": {"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"]}} {"question": "Use of a static array like aux[] is inadvisable in library software because\nmultiple clients might use the class concurrently. Give an implementation of Merge.java that \ndoes not use a static array.", "answer": "/******************************************************************************\n * Compilation: javac Merge.java\n * Execution: java Merge < input.txt\n * Dependencies: StdOut.java StdIn.java\n * Data files: https://algs4.cs.princeton.edu/22mergesort/tiny.txt\n * https://algs4.cs.princeton.edu/22mergesort/words3.txt\n *\n * Sorts a sequence of strings from standard input using mergesort.\n *\n * % more tiny.txt\n * S O R T E X A M P L E\n *\n * % java Merge < tiny.txt\n * A E E L M O P R S T X [ one string per line ]\n *\n * % more words3.txt\n * bed bug dad yes zoo ... all bad yet\n *\n * % java Merge < words3.txt\n * all bad bed bug dad ... yes yet zoo [ one string per line ]\n *\n ******************************************************************************/\n\n/**\n * The {@code Merge} class provides static methods for sorting an\n * array using a top-down, recursive version of mergesort.\n *

\n * This implementation takes Θ(n log n) time\n * to sort any array of length n (assuming comparisons\n * take constant time). It makes between\n * ~ ½ n log2 n and\n * ~ 1 n log2 n compares.\n *

\n * This sorting algorithm is stable.\n * It uses Θ(n) extra memory (not including the input array).\n *

\n * For additional documentation, see\n * Section 2.2 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n * For an optimized version, see {@link MergeX}.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class Merge {\n\n // This class should not be instantiated.\n private Merge() { }\n\n // stably merge a[lo .. mid] with a[mid+1 ..hi] using aux[lo .. hi]\n private static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) {\n // precondition: a[lo .. mid] and a[mid+1 .. hi] are sorted subarrays\n assert isSorted(a, lo, mid);\n assert isSorted(a, mid+1, hi);\n\n // copy to aux[]\n for (int k = lo; k <= hi; k++) {\n aux[k] = a[k];\n }\n\n // merge back to a[]\n int i = lo, j = mid+1;\n for (int k = lo; k <= hi; k++) {\n if (i > mid) a[k] = aux[j++];\n else if (j > hi) a[k] = aux[i++];\n else if (less(aux[j], aux[i])) a[k] = aux[j++];\n else a[k] = aux[i++];\n }\n\n // postcondition: a[lo .. hi] is sorted\n assert isSorted(a, lo, hi);\n }\n\n // mergesort a[lo..hi] using auxiliary array aux[lo..hi]\n private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) {\n if (hi <= lo) return;\n int mid = lo + (hi - lo) / 2;\n sort(a, aux, lo, mid);\n sort(a, aux, mid + 1, hi);\n merge(a, aux, lo, mid, hi);\n }\n\n /**\n * Rearranges the array in ascending order, using the natural order.\n * @param a the array to be sorted\n */\n public static void sort(Comparable[] a) {\n Comparable[] aux = new Comparable[a.length];\n sort(a, aux, 0, a.length-1);\n assert isSorted(a);\n }\n\n\n /***************************************************************************\n * Helper sorting function.\n ***************************************************************************/\n\n // is v < w ?\n private static boolean less(Comparable v, Comparable w) {\n return v.compareTo(w) < 0;\n }\n\n /***************************************************************************\n * Check if array is sorted - useful for debugging.\n ***************************************************************************/\n private static boolean isSorted(Comparable[] a) {\n return isSorted(a, 0, a.length - 1);\n }\n\n private static boolean isSorted(Comparable[] a, int lo, int hi) {\n for (int i = lo + 1; i <= hi; i++)\n if (less(a[i], a[i-1])) return false;\n return true;\n }\n\n\n /***************************************************************************\n * Index mergesort.\n ***************************************************************************/\n // stably merge a[lo .. mid] with a[mid+1 .. hi] using aux[lo .. hi]\n private static void merge(Comparable[] a, int[] index, int[] aux, int lo, int mid, int hi) {\n\n // copy to aux[]\n for (int k = lo; k <= hi; k++) {\n aux[k] = index[k];\n }\n\n // merge back to a[]\n int i = lo, j = mid+1;\n for (int k = lo; k <= hi; k++) {\n if (i > mid) index[k] = aux[j++];\n else if (j > hi) index[k] = aux[i++];\n else if (less(a[aux[j]], a[aux[i]])) index[k] = aux[j++];\n else index[k] = aux[i++];\n }\n }\n\n /**\n * Returns a permutation that gives the elements in the array in ascending order.\n * @param a the array\n * @return a permutation {@code p[]} such that {@code a[p[0]]}, {@code a[p[1]]},\n * ..., {@code a[p[n-1]]} are in ascending order\n */\n public static int[] indexSort(Comparable[] a) {\n int n = a.length;\n int[] index = new int[n];\n for (int i = 0; i < n; i++)\n index[i] = i;\n\n int[] aux = new int[n];\n sort(a, index, aux, 0, n-1);\n return index;\n }\n\n // mergesort a[lo..hi] using auxiliary array aux[lo..hi]\n private static void sort(Comparable[] a, int[] index, int[] aux, int lo, int hi) {\n if (hi <= lo) return;\n int mid = lo + (hi - lo) / 2;\n sort(a, index, aux, lo, mid);\n sort(a, index, aux, mid + 1, hi);\n merge(a, index, aux, lo, mid, hi);\n }\n\n // print array to standard output\n private static void show(Comparable[] a) {\n for (int i = 0; i < a.length; i++) {\n StdOut.println(a[i]);\n }\n }\n\n /**\n * Reads in a sequence of strings from standard input; mergesorts them;\n * and prints them to standard output in ascending order.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n String[] a = StdIn.readAllStrings();\n Merge.sort(a);\n show(a);\n }\n}\n", "support_files": ["https://algs4.cs.princeton.edu/22mergesort/tiny.txt", "https://algs4.cs.princeton.edu/22mergesort/words3.txt"], "metadata": {"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"]}} {"question": "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", "answer": "/******************************************************************************\n * Compilation: javac MergeX.java\n * Execution: java MergeX < input.txt\n * Dependencies: StdOut.java StdIn.java\n * Data files: https://algs4.cs.princeton.edu/22mergesort/tiny.txt\n * https://algs4.cs.princeton.edu/22mergesort/words3.txt\n *\n * Sorts a sequence of strings from standard input using an\n * optimized version of mergesort.\n *\n * % more tiny.txt\n * S O R T E X A M P L E\n *\n * % java MergeX < tiny.txt\n * A E E L M O P R S T X [ one string per line ]\n *\n * % more words3.txt\n * bed bug dad yes zoo ... all bad yet\n *\n * % java MergeX < words3.txt\n * all bad bed bug dad ... yes yet zoo [ one string per line ]\n *\n ******************************************************************************/\n\nimport java.util.Comparator;\n\n/**\n * The {@code MergeX} class provides static methods for sorting an\n * array using an optimized version of mergesort.\n *

\n * In the worst case, this implementation takes\n * Θ(n log n) time to sort an array of\n * length n (assuming comparisons take constant time).\n *

\n * This sorting algorithm is stable.\n * It uses Θ(n) extra memory (not including the input array).\n *

\n * For additional documentation, see\n * Section 2.2 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class MergeX {\n private static final int CUTOFF = 7; // cutoff to insertion sort\n\n // This class should not be instantiated.\n private MergeX() { }\n\n private static void merge(Comparable[] src, Comparable[] dst, int lo, int mid, int hi) {\n\n // precondition: src[lo .. mid] and src[mid+1 .. hi] are sorted subarrays\n assert isSorted(src, lo, mid);\n assert isSorted(src, mid+1, hi);\n\n int i = lo, j = mid+1;\n for (int k = lo; k <= hi; k++) {\n if (i > mid) dst[k] = src[j++];\n else if (j > hi) dst[k] = src[i++];\n else if (less(src[j], src[i])) dst[k] = src[j++]; // to ensure stability\n else dst[k] = src[i++];\n }\n\n // postcondition: dst[lo .. hi] is sorted subarray\n assert isSorted(dst, lo, hi);\n }\n\n private static void sort(Comparable[] src, Comparable[] dst, int lo, int hi) {\n // if (hi <= lo) return;\n if (hi <= lo + CUTOFF) {\n insertionSort(dst, lo, hi);\n return;\n }\n int mid = lo + (hi - lo) / 2;\n sort(dst, src, lo, mid);\n sort(dst, src, mid+1, hi);\n\n // if (!less(src[mid+1], src[mid])) {\n // for (int i = lo; i <= hi; i++) dst[i] = src[i];\n // return;\n // }\n\n // using System.arraycopy() is a bit faster than the above loop\n if (!less(src[mid+1], src[mid])) {\n System.arraycopy(src, lo, dst, lo, hi - lo + 1);\n return;\n }\n\n merge(src, dst, lo, mid, hi);\n }\n\n /**\n * Rearranges the array in ascending order, using the natural order.\n * @param a the array to be sorted\n */\n public static void sort(Comparable[] a) {\n Comparable[] aux = a.clone();\n sort(aux, a, 0, a.length-1);\n assert isSorted(a);\n }\n\n // sort from a[lo] to a[hi] using insertion sort\n private static void insertionSort(Comparable[] a, int lo, int hi) {\n for (int i = lo; i <= hi; i++)\n for (int j = i; j > lo && less(a[j], a[j-1]); j--)\n exch(a, j, j-1);\n }\n\n\n /*******************************************************************\n * Utility methods.\n *******************************************************************/\n\n // exchange a[i] and a[j]\n private static void exch(Object[] a, int i, int j) {\n Object swap = a[i];\n a[i] = a[j];\n a[j] = swap;\n }\n\n // is a[i] < a[j]?\n private static boolean less(Comparable a, Comparable b) {\n return a.compareTo(b) < 0;\n }\n\n // is a[i] < a[j]?\n private static boolean less(Object a, Object b, Comparator comparator) {\n return comparator.compare(a, b) < 0;\n }\n\n\n /*******************************************************************\n * Version that takes Comparator as argument.\n *******************************************************************/\n\n /**\n * Rearranges the array in ascending order, using the provided order.\n *\n * @param a the array to be sorted\n * @param comparator the comparator that defines the total order\n */\n public static void sort(Object[] a, Comparator comparator) {\n Object[] aux = a.clone();\n sort(aux, a, 0, a.length-1, comparator);\n assert isSorted(a, comparator);\n }\n\n private static void merge(Object[] src, Object[] dst, int lo, int mid, int hi, Comparator comparator) {\n\n // precondition: src[lo .. mid] and src[mid+1 .. hi] are sorted subarrays\n assert isSorted(src, lo, mid, comparator);\n assert isSorted(src, mid+1, hi, comparator);\n\n int i = lo, j = mid+1;\n for (int k = lo; k <= hi; k++) {\n if (i > mid) dst[k] = src[j++];\n else if (j > hi) dst[k] = src[i++];\n else if (less(src[j], src[i], comparator)) dst[k] = src[j++];\n else dst[k] = src[i++];\n }\n\n // postcondition: dst[lo .. hi] is sorted subarray\n assert isSorted(dst, lo, hi, comparator);\n }\n\n\n private static void sort(Object[] src, Object[] dst, int lo, int hi, Comparator comparator) {\n // if (hi <= lo) return;\n if (hi <= lo + CUTOFF) {\n insertionSort(dst, lo, hi, comparator);\n return;\n }\n int mid = lo + (hi - lo) / 2;\n sort(dst, src, lo, mid, comparator);\n sort(dst, src, mid+1, hi, comparator);\n\n // using System.arraycopy() is a bit faster than the above loop\n if (!less(src[mid+1], src[mid], comparator)) {\n System.arraycopy(src, lo, dst, lo, hi - lo + 1);\n return;\n }\n\n merge(src, dst, lo, mid, hi, comparator);\n }\n\n // sort from a[lo] to a[hi] using insertion sort\n private static void insertionSort(Object[] a, int lo, int hi, Comparator comparator) {\n for (int i = lo; i <= hi; i++)\n for (int j = i; j > lo && less(a[j], a[j-1], comparator); j--)\n exch(a, j, j-1);\n }\n\n\n /***************************************************************************\n * Check if array is sorted - useful for debugging.\n ***************************************************************************/\n private static boolean isSorted(Comparable[] a) {\n return isSorted(a, 0, a.length - 1);\n }\n\n private static boolean isSorted(Comparable[] a, int lo, int hi) {\n for (int i = lo + 1; i <= hi; i++)\n if (less(a[i], a[i-1])) return false;\n return true;\n }\n\n private static boolean isSorted(Object[] a, Comparator comparator) {\n return isSorted(a, 0, a.length - 1, comparator);\n }\n\n private static boolean isSorted(Object[] a, int lo, int hi, Comparator comparator) {\n for (int i = lo + 1; i <= hi; i++)\n if (less(a[i], a[i-1], comparator)) return false;\n return true;\n }\n\n // print array to standard output\n private static void show(Object[] a) {\n for (int i = 0; i < a.length; i++) {\n StdOut.println(a[i]);\n }\n }\n\n /**\n * Reads in a sequence of strings from standard input; mergesorts them\n * (using an optimized version of mergesort);\n * and prints them to standard output in ascending order.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n String[] a = StdIn.readAllStrings();\n MergeX.sort(a);\n show(a);\n }\n}\n", "support_files": ["https://algs4.cs.princeton.edu/22mergesort/tiny.txt", "https://algs4.cs.princeton.edu/22mergesort/words3.txt"], "metadata": {"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"]}} {"question": "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", "answer": "/******************************************************************************\n * Compilation: javac Inversions.java\n * Execution: java Inversions < input.txt\n * Dependencies: StdIn.java StdOut.java\n *\n * Read array of n integers and count number of inversions in n log n time.\n *\n ******************************************************************************/\n\n/**\n * The {@code Inversions} class provides static methods to count the\n * number of inversions in either an array of integers or comparables.\n * An inversion in an array {@code a[]} is a pair of indicies {@code i} and\n * {@code j} such that {@code i < j} and {@code a[i] > a[j]}.\n *

\n * This implementation uses a generalization of mergesort. The count\n * operation takes Θ(n log n) time to count the\n * number of inversions in any array of length n (assuming\n * comparisons take constant time).\n *

\n * For additional documentation, see\n * Section 2.2\n * of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class Inversions {\n\n // do not instantiate\n private Inversions() { }\n\n // merge and count\n private static long merge(int[] a, int[] aux, int lo, int mid, int hi) {\n long inversions = 0;\n\n // copy to aux[]\n for (int k = lo; k <= hi; k++) {\n aux[k] = a[k];\n }\n\n // merge back to a[]\n int i = lo, j = mid+1;\n for (int k = lo; k <= hi; k++) {\n if (i > mid) a[k] = aux[j++];\n else if (j > hi) a[k] = aux[i++];\n else if (aux[j] < aux[i]) { a[k] = aux[j++]; inversions += (mid - i + 1); }\n else a[k] = aux[i++];\n }\n return inversions;\n }\n\n // return the number of inversions in the subarray b[lo..hi]\n // side effect b[lo..hi] is rearranged in ascending order\n private static long count(int[] a, int[] b, int[] aux, int lo, int hi) {\n long inversions = 0;\n if (hi <= lo) return 0;\n int mid = lo + (hi - lo) / 2;\n inversions += count(a, b, aux, lo, mid);\n inversions += count(a, b, aux, mid+1, hi);\n inversions += merge(b, aux, lo, mid, hi);\n assert inversions == brute(a, lo, hi);\n return inversions;\n }\n\n\n /**\n * Returns the number of inversions in the integer array.\n * The argument array is not modified.\n * @param a the array\n * @return the number of inversions in the array. An inversion is a pair of\n * indicies {@code i} and {@code j} such that {@code i < j}\n * and {@code a[i] > a[j]}.\n */\n public static long count(int[] a) {\n int[] b = new int[a.length];\n int[] aux = new int[a.length];\n for (int i = 0; i < a.length; i++)\n b[i] = a[i];\n long inversions = count(a, b, aux, 0, a.length - 1);\n return inversions;\n }\n\n\n\n // merge and count (Comparable version)\n private static > long merge(Key[] a, Key[] aux, int lo, int mid, int hi) {\n long inversions = 0;\n\n // copy to aux[]\n for (int k = lo; k <= hi; k++) {\n aux[k] = a[k];\n }\n\n // merge back to a[]\n int i = lo, j = mid+1;\n for (int k = lo; k <= hi; k++) {\n if (i > mid) a[k] = aux[j++];\n else if (j > hi) a[k] = aux[i++];\n else if (less(aux[j], aux[i])) { a[k] = aux[j++]; inversions += (mid - i + 1); }\n else a[k] = aux[i++];\n }\n return inversions;\n }\n\n // return the number of inversions in the subarray b[lo..hi]\n // side effect b[lo..hi] is rearranged in ascending order\n private static > long count(Key[] a, Key[] b, Key[] aux, int lo, int hi) {\n long inversions = 0;\n if (hi <= lo) return 0;\n int mid = lo + (hi - lo) / 2;\n inversions += count(a, b, aux, lo, mid);\n inversions += count(a, b, aux, mid+1, hi);\n inversions += merge(b, aux, lo, mid, hi);\n assert inversions == brute(a, lo, hi);\n return inversions;\n }\n\n\n /**\n * Returns the number of inversions in the comparable array.\n * The argument array is not modified.\n * @param a the array\n * @param the inferred type of the elements in the array\n * @return the number of inversions in the array. An inversion is a pair of\n * indicies {@code i} and {@code j} such that {@code i < j}\n * and {@code a[i].compareTo(a[j]) > 0}.\n */\n public static > long count(Key[] a) {\n Key[] b = a.clone();\n Key[] aux = a.clone();\n long inversions = count(a, b, aux, 0, a.length - 1);\n return inversions;\n }\n\n\n // is v < w ?\n private static > boolean less(Key v, Key w) {\n return (v.compareTo(w) < 0);\n }\n\n // count number of inversions in a[lo..hi] via brute force (for debugging only)\n private static > long brute(Key[] a, int lo, int hi) {\n long inversions = 0;\n for (int i = lo; i <= hi; i++)\n for (int j = i + 1; j <= hi; j++)\n if (less(a[j], a[i])) inversions++;\n return inversions;\n }\n\n // count number of inversions in a[lo..hi] via brute force (for debugging only)\n private static long brute(int[] a, int lo, int hi) {\n long inversions = 0;\n for (int i = lo; i <= hi; i++)\n for (int j = i + 1; j <= hi; j++)\n if (a[j] < a[i]) inversions++;\n return inversions;\n }\n\n /**\n * Reads a sequence of integers from standard input and\n * prints the number of inversions to standard output.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n int[] a = StdIn.readAllInts();\n int n = a.length;\n Integer[] b = new Integer[n];\n for (int i = 0; i < n; i++)\n b[i] = a[i];\n StdOut.println(Inversions.count(a));\n StdOut.println(Inversions.count(b));\n }\n}\n", "support_files": ["https://algs4.cs.princeton.edu/14analysis/16Kints.txt", "https://algs4.cs.princeton.edu/14analysis/1Kints.txt", "https://algs4.cs.princeton.edu/14analysis/2Kints.txt", "https://algs4.cs.princeton.edu/14analysis/32Kints.txt", "https://algs4.cs.princeton.edu/14analysis/4Kints.txt", "https://algs4.cs.princeton.edu/14analysis/8Kints.txt"], "metadata": {"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"]}} {"question": "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.", "answer": "/******************************************************************************\n * Compilation: javac Merge.java\n * Execution: java Merge < input.txt\n * Dependencies: StdOut.java StdIn.java\n * Data files: https://algs4.cs.princeton.edu/22mergesort/tiny.txt\n * https://algs4.cs.princeton.edu/22mergesort/words3.txt\n *\n * Sorts a sequence of strings from standard input using mergesort.\n *\n * % more tiny.txt\n * S O R T E X A M P L E\n *\n * % java Merge < tiny.txt\n * A E E L M O P R S T X [ one string per line ]\n *\n * % more words3.txt\n * bed bug dad yes zoo ... all bad yet\n *\n * % java Merge < words3.txt\n * all bad bed bug dad ... yes yet zoo [ one string per line ]\n *\n ******************************************************************************/\n\n/**\n * The {@code Merge} class provides static methods for sorting an\n * array using a top-down, recursive version of mergesort.\n *

\n * This implementation takes Θ(n log n) time\n * to sort any array of length n (assuming comparisons\n * take constant time). It makes between\n * ~ ½ n log2 n and\n * ~ 1 n log2 n compares.\n *

\n * This sorting algorithm is stable.\n * It uses Θ(n) extra memory (not including the input array).\n *

\n * For additional documentation, see\n * Section 2.2 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n * For an optimized version, see {@link MergeX}.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class Merge {\n\n // This class should not be instantiated.\n private Merge() { }\n\n // stably merge a[lo .. mid] with a[mid+1 ..hi] using aux[lo .. hi]\n private static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) {\n // precondition: a[lo .. mid] and a[mid+1 .. hi] are sorted subarrays\n assert isSorted(a, lo, mid);\n assert isSorted(a, mid+1, hi);\n\n // copy to aux[]\n for (int k = lo; k <= hi; k++) {\n aux[k] = a[k];\n }\n\n // merge back to a[]\n int i = lo, j = mid+1;\n for (int k = lo; k <= hi; k++) {\n if (i > mid) a[k] = aux[j++];\n else if (j > hi) a[k] = aux[i++];\n else if (less(aux[j], aux[i])) a[k] = aux[j++];\n else a[k] = aux[i++];\n }\n\n // postcondition: a[lo .. hi] is sorted\n assert isSorted(a, lo, hi);\n }\n\n // mergesort a[lo..hi] using auxiliary array aux[lo..hi]\n private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) {\n if (hi <= lo) return;\n int mid = lo + (hi - lo) / 2;\n sort(a, aux, lo, mid);\n sort(a, aux, mid + 1, hi);\n merge(a, aux, lo, mid, hi);\n }\n\n /**\n * Rearranges the array in ascending order, using the natural order.\n * @param a the array to be sorted\n */\n public static void sort(Comparable[] a) {\n Comparable[] aux = new Comparable[a.length];\n sort(a, aux, 0, a.length-1);\n assert isSorted(a);\n }\n\n\n /***************************************************************************\n * Helper sorting function.\n ***************************************************************************/\n\n // is v < w ?\n private static boolean less(Comparable v, Comparable w) {\n return v.compareTo(w) < 0;\n }\n\n /***************************************************************************\n * Check if array is sorted - useful for debugging.\n ***************************************************************************/\n private static boolean isSorted(Comparable[] a) {\n return isSorted(a, 0, a.length - 1);\n }\n\n private static boolean isSorted(Comparable[] a, int lo, int hi) {\n for (int i = lo + 1; i <= hi; i++)\n if (less(a[i], a[i-1])) return false;\n return true;\n }\n\n\n /***************************************************************************\n * Index mergesort.\n ***************************************************************************/\n // stably merge a[lo .. mid] with a[mid+1 .. hi] using aux[lo .. hi]\n private static void merge(Comparable[] a, int[] index, int[] aux, int lo, int mid, int hi) {\n\n // copy to aux[]\n for (int k = lo; k <= hi; k++) {\n aux[k] = index[k];\n }\n\n // merge back to a[]\n int i = lo, j = mid+1;\n for (int k = lo; k <= hi; k++) {\n if (i > mid) index[k] = aux[j++];\n else if (j > hi) index[k] = aux[i++];\n else if (less(a[aux[j]], a[aux[i]])) index[k] = aux[j++];\n else index[k] = aux[i++];\n }\n }\n\n /**\n * Returns a permutation that gives the elements in the array in ascending order.\n * @param a the array\n * @return a permutation {@code p[]} such that {@code a[p[0]]}, {@code a[p[1]]},\n * ..., {@code a[p[n-1]]} are in ascending order\n */\n public static int[] indexSort(Comparable[] a) {\n int n = a.length;\n int[] index = new int[n];\n for (int i = 0; i < n; i++)\n index[i] = i;\n\n int[] aux = new int[n];\n sort(a, index, aux, 0, n-1);\n return index;\n }\n\n // mergesort a[lo..hi] using auxiliary array aux[lo..hi]\n private static void sort(Comparable[] a, int[] index, int[] aux, int lo, int hi) {\n if (hi <= lo) return;\n int mid = lo + (hi - lo) / 2;\n sort(a, index, aux, lo, mid);\n sort(a, index, aux, mid + 1, hi);\n merge(a, index, aux, lo, mid, hi);\n }\n\n // print array to standard output\n private static void show(Comparable[] a) {\n for (int i = 0; i < a.length; i++) {\n StdOut.println(a[i]);\n }\n }\n\n /**\n * Reads in a sequence of strings from standard input; mergesorts them;\n * and prints them to standard output in ascending order.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n String[] a = StdIn.readAllStrings();\n Merge.sort(a);\n show(a);\n }\n}\n", "support_files": ["https://algs4.cs.princeton.edu/22mergesort/tiny.txt", "https://algs4.cs.princeton.edu/22mergesort/words3.txt"], "metadata": {"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"]}} {"question": "Write a program Sort2distinct.java that sorts an array that is known to contain just two distinct key values. ", "answer": "/******************************************************************************\n * Compilation: javac Sort2distinct.java\n * Execution: java Sort2distinct binary-string\n * Dependencies: StdOut.java\n *\n * Partitions the array of specified as the command-line.\n * Assumes there are at most 2 distinct elements.\n *\n ******************************************************************************/\n\npublic class Sort2distinct {\n\n // rearranges a[] in ascending order assuming a[] has at most 3 distinct values\n public static void sort(Comparable[] a) {\n int lt = 0, gt = a.length - 1;\n int i = 0;\n while (i <= gt) {\n int cmp = a[i].compareTo(a[lt]);\n if (cmp < 0) exch(a, lt++, i++);\n else if (cmp > 0) exch(a, i, gt--);\n else i++;\n }\n }\n\n // exchange a[i] and a[j]\n private static void exch(Comparable[] a, int i, int j) {\n Comparable swap = a[i];\n a[i] = a[j];\n a[j] = swap;\n }\n\n // test client\n public static void main(String[] args) {\n\n // parse command-line argument as an array of 1-character strings\n String s = args[0];\n int n = s.length();\n String[] a = new String[n];\n for (int i = 0; i < n; i++)\n a[i] = s.substring(i, i+1);\n\n // sort a print results\n sort(a);\n for (int i = 0; i < n; i++)\n StdOut.print(a[i]);\n StdOut.println();\n }\n\n}\n", "support_files": [], "metadata": {"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"]}} {"question": "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. ", "answer": "/******************************************************************************\n * Compilation: javac QuickBest.java\n * Execution: java QuickBest n\n * Dependencies: StdOut.java\n *\n * Generate a best-case input of size n for standard quicksort.\n *\n * % java QuickBest 3\n * BAC\n *\n * % java QuickBest 7\n * DACBFEG\n *\n * % java QuickBest 15\n * HACBFEGDLIKJNMO\n *\n ******************************************************************************/\n\npublic class QuickBest {\n\n // postcondition: a[lo..hi] is best-case input for quicksorting that subarray\n private static void best(int[] a, int lo, int hi) {\n\n // precondition: a[lo..hi] contains keys lo to hi, in order\n for (int i = lo; i <= hi; i++)\n assert a[i] == i;\n\n if (hi <= lo) return;\n int mid = lo + (hi - lo) / 2;\n best(a, lo, mid-1);\n best(a, mid+1, hi);\n exch(a, lo, mid);\n }\n\n public static int[] best(int n) {\n int[] a = new int[n];\n for (int i = 0; i < n; i++)\n a[i] = i;\n best(a, 0, n-1);\n return a;\n }\n\n // exchange a[i] and a[j]\n private static void exch(int[] a, int i, int j) {\n int swap = a[i];\n a[i] = a[j];\n a[j] = swap;\n }\n\n\n public static void main(String[] args) {\n String alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n int n = Integer.parseInt(args[0]);\n int[] a = best(n);\n for (int i = 0; i < n; i++)\n // StdOut.println(a[i]);\n StdOut.print(alphabet.charAt(a[i]));\n StdOut.println();\n }\n}\n", "support_files": [], "metadata": {"number": "2.3.16", "code_execution": true, "url": "https://algs4.cs.princeton.edu/23quicksort/QuickBest.java", "params": ["3", "7", "15"], "dependencies": ["StdOut.java"]}} {"question": "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", "answer": "/******************************************************************************\n * Compilation: javac QuickBentleyMcIlroy.java\n * Execution: java QuickBentleyMcIlroy < input.txt\n * Dependencies: StdOut.java StdIn.java\n * Data files: https://algs4.cs.princeton.edu/23quicksort/tiny.txt\n * https://algs4.cs.princeton.edu/23quicksort/words3.txt\n *\n * Uses the Bentley-McIlroy 3-way partitioning scheme,\n * chooses the partitioning element using Tukey's ninther,\n * and cuts off to insertion sort.\n *\n * Reference: Engineering a Sort Function by Jon L. Bentley\n * and M. Douglas McIlroy. Software-Practice and Experience,\n * Vol. 23 (11), 1249-1265 (November 1993).\n *\n ******************************************************************************/\n\n/**\n * The {@code QuickBentleyMcIlroy} class provides static methods for sorting\n * an array using an optimized version of quicksort (using Bentley-McIlroy\n * 3-way partitioning, Tukey's ninther, and cutoff to insertion sort).\n *

\n * For additional documentation, see\n * Section 2.3\n * of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class QuickBentleyMcIlroy {\n\n // cutoff to insertion sort, must be >= 1\n private static final int INSERTION_SORT_CUTOFF = 8;\n\n // cutoff to median-of-3 partitioning\n private static final int MEDIAN_OF_3_CUTOFF = 40;\n\n // This class should not be instantiated.\n private QuickBentleyMcIlroy() { }\n\n /**\n * Rearranges the array in ascending order, using the natural order.\n * @param a the array to be sorted\n */\n public static void sort(Comparable[] a) {\n sort(a, 0, a.length - 1);\n }\n\n private static void sort(Comparable[] a, int lo, int hi) {\n int n = hi - lo + 1;\n\n // cutoff to insertion sort\n if (n <= INSERTION_SORT_CUTOFF) {\n insertionSort(a, lo, hi);\n return;\n }\n\n // use median-of-3 as partitioning element\n else if (n <= MEDIAN_OF_3_CUTOFF) {\n int m = median3(a, lo, lo + n/2, hi);\n exch(a, m, lo);\n }\n\n // use Tukey ninther as partitioning element\n else {\n int eps = n/8;\n int mid = lo + n/2;\n int m1 = median3(a, lo, lo + eps, lo + eps + eps);\n int m2 = median3(a, mid - eps, mid, mid + eps);\n int m3 = median3(a, hi - eps - eps, hi - eps, hi);\n int ninther = median3(a, m1, m2, m3);\n exch(a, ninther, lo);\n }\n\n // Bentley-McIlroy 3-way partitioning\n int i = lo, j = hi+1;\n int p = lo, q = hi+1;\n Comparable v = a[lo];\n while (true) {\n while (less(a[++i], v))\n if (i == hi) break;\n while (less(v, a[--j]))\n if (j == lo) break;\n\n // pointers cross\n if (i == j && eq(a[i], v))\n exch(a, ++p, i);\n if (i >= j) break;\n\n exch(a, i, j);\n if (eq(a[i], v)) exch(a, ++p, i);\n if (eq(a[j], v)) exch(a, --q, j);\n }\n\n\n i = j + 1;\n for (int k = lo; k <= p; k++)\n exch(a, k, j--);\n for (int k = hi; k >= q; k--)\n exch(a, k, i++);\n\n sort(a, lo, j);\n sort(a, i, hi);\n }\n\n\n // sort from a[lo] to a[hi] using insertion sort\n private static void insertionSort(Comparable[] a, int lo, int hi) {\n for (int i = lo; i <= hi; i++)\n for (int j = i; j > lo && less(a[j], a[j-1]); j--)\n exch(a, j, j-1);\n }\n\n\n // return the index of the median element among a[i], a[j], and a[k]\n private static int median3(Comparable[] a, int i, int j, int k) {\n return (less(a[i], a[j]) ?\n (less(a[j], a[k]) ? j : less(a[i], a[k]) ? k : i) :\n (less(a[k], a[j]) ? j : less(a[k], a[i]) ? k : i));\n }\n\n /***************************************************************************\n * Helper sorting functions.\n ***************************************************************************/\n\n // is v < w ?\n private static boolean less(Comparable v, Comparable w) {\n if (v == w) return false; // optimization when reference equal\n return v.compareTo(w) < 0;\n }\n\n // does v == w ?\n private static boolean eq(Comparable v, Comparable w) {\n if (v == w) return true; // optimization when reference equal\n return v.compareTo(w) == 0;\n }\n\n // exchange a[i] and a[j]\n private static void exch(Object[] a, int i, int j) {\n Object swap = a[i];\n a[i] = a[j];\n a[j] = swap;\n }\n\n\n /***************************************************************************\n * Check if array is sorted - useful for debugging.\n ***************************************************************************/\n private static boolean isSorted(Comparable[] a) {\n for (int i = 1; i < a.length; i++)\n if (less(a[i], a[i-1])) return false;\n return true;\n }\n\n // print array to standard output\n private static void show(Comparable[] a) {\n for (int i = 0; i < a.length; i++) {\n StdOut.println(a[i]);\n }\n }\n\n /**\n * Reads in a sequence of strings from standard input; quicksorts them\n * (using an optimized version of quicksort);\n * and prints them to standard output in ascending order.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n String[] a = StdIn.readAllStrings();\n QuickBentleyMcIlroy.sort(a);\n assert isSorted(a);\n show(a);\n }\n\n}\n", "support_files": ["https://algs4.cs.princeton.edu/23quicksort/tiny.txt", "https://algs4.cs.princeton.edu/23quicksort/words3.txt"], "metadata": {"number": "2.3.22", "code_execution": true, "url": "https://algs4.cs.princeton.edu/23quicksort/QuickBentleyMcIlroy.java", "params": ["< tiny.txt", "< words3.txt"], "dependencies": ["StdOut.java", "StdIn.java"]}} {"question": "Design a linear-time certification algorithm to check whether an array pq[] is a min-oriented heap.", "answer": "For a 1-based heap array `pq[1..n]`, scan every internal node and check only its children. That visits each parent-child edge once, so the running time is linear.\n\n```java\npublic static boolean isMinHeap(Comparable[] pq, int n) {\n for (int k = 1; k <= n / 2; k++) {\n int left = 2 * k;\n int right = left + 1;\n if (left <= n && greater(pq[k], pq[left])) return false;\n if (right <= n && greater(pq[k], pq[right])) return false;\n }\n return true;\n}\n\nprivate static boolean greater(Comparable a, Comparable b) {\n return a.compareTo(b) > 0;\n}\n```", "support_files": ["https://algs4.cs.princeton.edu/24pq/tinyPQ.txt"], "metadata": {"number": "2.4.15", "code_execution": false}} {"question": "Computational number theory. Write a program CubeSum.java that prints out all integers of the form \\(a^3 + b^3\\)\nwhere \\(a\\) and \\(b\\) are integers between 0 and \\(n<\\) in sorted order,\nwithout using excessive space. That is, instead of computing an array of\nthe \\(n^2\\) sums and sorting them, build a minimum-oriented priority\nqueue, initially containing\n\\((0^3, 0, 0), (1^3 + 1^3, 1, 1), (2^3 + 2^3, 2, 2), \\ldots, (n^3 + n^3, n, n)\\).\nThen, while the priority queue is nonempty, remove the smallest item\n\\(i^3 + j^3,\\; i, \\; j)\\), print it, and then, if \n\\(j < n\\), insert the item \\((i^3 + (j+1)^3,\\; i,\\; j+1)\\).\nUse this program to find all distinct integers \\(a, b, c\\), and \\(d\\) between 0 and \n\\(10^6\\) such that \n\\(a^3 + b^3 = c^3 + d^3\\), such as\n\\(1729 = 9^3 + 10^3 = 1^3 + 12^3\\).", "answer": "/******************************************************************************\n * Compilation: javac CubeSum.java\n * Execution: java CubeSum n\n * Dependencies: MinPQ.java\n *\n * Print out integers of the form a^3 + b^3 in sorted order, where\n * 0 <= a <= b <= n.\n *\n * % java CubeSum 12\n * 0 = 0^3 + 0^3\n * 1 = 0^3 + 1^3\n * 2 = 1^3 + 1^3\n * 8 = 0^3 + 2^3\n * 9 = 1^3 + 2^3\n * ...\n * 1729 = 9^3 + 10^3\n * 1729 = 1^3 + 12^3\n * ...\n * 3456 = 12^3 + 12^3\n *\n * Remarks\n * -------\n * - Easily extends to handle sums of the form f(a) + g(b)\n * - Prints out a sum more than once if it can be obtained\n * in more than one way, e.g., 1729 = 9^3 + 10^3 = 1^3 + 12^3\n *\n ******************************************************************************/\n\npublic class CubeSum implements Comparable {\n private final int sum;\n private final int i;\n private final int j;\n\n public CubeSum(int i, int j) {\n this.sum = i*i*i + j*j*j;\n this.i = i;\n this.j = j;\n }\n\n public int compareTo(CubeSum that) {\n if (this.sum < that.sum) return -1;\n if (this.sum > that.sum) return +1;\n return 0;\n }\n\n public String toString() {\n return sum + \" = \" + i + \"^3\" + \" + \" + j + \"^3\";\n }\n\n\n public static void main(String[] args) {\n\n int n = Integer.parseInt(args[0]);\n\n // initialize priority queue\n MinPQ pq = new MinPQ();\n for (int i = 0; i <= n; i++) {\n pq.insert(new CubeSum(i, i));\n }\n\n // find smallest sum, print it out, and update\n while (!pq.isEmpty()) {\n CubeSum s = pq.delMin();\n StdOut.println(s);\n if (s.j < n)\n pq.insert(new CubeSum(s.i, s.j + 1));\n }\n }\n\n}\n", "support_files": [], "metadata": {"number": "2.4.25", "code_execution": true, "url": "https://algs4.cs.princeton.edu/24pq/CubeSum.java", "params": ["4", "12"], "dependencies": ["MinPQ.java"]}} {"question": "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.", "answer": "/******************************************************************************\n * Compilation: javac Interval1D.java\n * Execution: java Interval1D\n * Dependencies: StdOut.java\n *\n * 1-dimensional interval data type.\n *\n ******************************************************************************/\n\npackage edu.princeton.cs.algs4;\n\nimport java.util.Arrays;\nimport java.util.Comparator;\n\n/**\n * The {@code Interval1D} class represents a one-dimensional interval.\n * The interval is closed—it contains both endpoints.\n * Intervals are immutable: their values cannot be changed after they are created.\n * The class {@code Interval1D} includes methods for checking whether\n * an interval contains a point and determining whether two intervals intersect.\n *

\n * For additional documentation,\n * see Section 1.2 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class Interval1D {\n\n /**\n * Compares two intervals by min endpoint.\n */\n public static final Comparator MIN_ENDPOINT_ORDER = new MinEndpointComparator();\n\n /**\n * Compares two intervals by max endpoint.\n */\n public static final Comparator MAX_ENDPOINT_ORDER = new MaxEndpointComparator();\n\n /**\n * Compares two intervals by length.\n */\n public static final Comparator LENGTH_ORDER = new LengthComparator();\n\n private final double min;\n private final double max;\n\n /**\n * Initializes a closed interval [min, max].\n *\n * @param min the smaller endpoint\n * @param max the larger endpoint\n * @throws IllegalArgumentException if the min endpoint is greater than the max endpoint\n * @throws IllegalArgumentException if either {@code min} or {@code max}\n * is {@code Double.NaN}, {@code Double.POSITIVE_INFINITY} or\n * {@code Double.NEGATIVE_INFINITY}\n\n */\n public Interval1D(double min, double max) {\n if (Double.isInfinite(min) || Double.isInfinite(max))\n throw new IllegalArgumentException(\"Endpoints must be finite\");\n if (Double.isNaN(min) || Double.isNaN(max))\n throw new IllegalArgumentException(\"Endpoints cannot be NaN\");\n\n // convert -0.0 to +0.0\n if (min == 0.0) min = 0.0;\n if (max == 0.0) max = 0.0;\n\n if (min <= max) {\n this.min = min;\n this.max = max;\n }\n else throw new IllegalArgumentException(\"Illegal interval\");\n }\n\n /**\n * Returns the left endpoint of this interval.\n *\n * @return the left endpoint of this interval\n * @deprecated Replaced by {@link #min()}.\n */\n @Deprecated\n public double left() {\n return min;\n }\n\n /**\n * Returns the right endpoint of this interval.\n * @return the right endpoint of this interval\n * @deprecated Replaced by {@link #max()}.\n */\n @Deprecated\n public double right() {\n return max;\n }\n\n /**\n * Returns the min endpoint of this interval.\n *\n * @return the min endpoint of this interval\n */\n public double min() {\n return min;\n }\n\n /**\n * Returns the max endpoint of this interval.\n *\n * @return the max endpoint of this interval\n */\n public double max() {\n return max;\n }\n\n /**\n * Returns true if this interval intersects the specified interval.\n *\n * @param that the other interval\n * @return {@code true} if this interval intersects the argument interval;\n * {@code false} otherwise\n */\n public boolean intersects(Interval1D that) {\n if (this.max < that.min) return false;\n if (that.max < this.min) return false;\n return true;\n }\n\n /**\n * Returns true if this interval contains the specified interval.\n *\n * @param that the other interval\n * @return {@code true} if this interval contains the argument interval;\n * {@code false} otherwise\n */\n public boolean contains(Interval1D that) {\n return (this.max >= that.max) && (this.min <= that.min);\n }\n\n /**\n * Returns true if this interval contains the specified value.\n *\n * @param x the value\n * @return {@code true} if this interval contains the value {@code x};\n * {@code false} otherwise\n */\n public boolean contains(double x) {\n return (min <= x) && (x <= max);\n }\n\n /**\n * Returns the length of this interval.\n *\n * @return the length of this interval (max - min)\n */\n public double length() {\n return max - min;\n }\n\n /**\n * Returns a string representation of this interval.\n *\n * @return a string representation of this interval in the form [min, max]\n */\n public String toString() {\n return \"[\" + min + \", \" + max + \"]\";\n }\n\n /**\n * Compares this transaction to the specified object.\n *\n * @param other the other interval\n * @return {@code true} if this interval equals the other interval;\n * {@code false} otherwise\n */\n public boolean equals(Object other) {\n if (other == this) return true;\n if (other == null) return false;\n if (other.getClass() != this.getClass()) return false;\n Interval1D that = (Interval1D) other;\n return this.min == that.min && this.max == that.max;\n }\n\n /**\n * Returns an integer hash code for this interval.\n *\n * @return an integer hash code for this interval\n */\n public int hashCode() {\n int hash1 = ((Double) min).hashCode();\n int hash2 = ((Double) max).hashCode();\n return 31*hash1 + hash2;\n }\n\n // ascending order of min endpoint, breaking ties by max endpoint\n private static class MinEndpointComparator implements Comparator {\n public int compare(Interval1D a, Interval1D b) {\n if (a.min < b.min) return -1;\n else if (a.min > b.min) return +1;\n else if (a.max < b.max) return -1;\n else if (a.max > b.max) return +1;\n else return 0;\n }\n }\n\n // ascending order of max endpoint, breaking ties by min endpoint\n private static class MaxEndpointComparator implements Comparator {\n public int compare(Interval1D a, Interval1D b) {\n if (a.max < b.max) return -1;\n else if (a.max > b.max) return +1;\n else if (a.min < b.min) return -1;\n else if (a.min > b.min) return +1;\n else return 0;\n }\n }\n\n // ascending order of length\n private static class LengthComparator implements Comparator {\n public int compare(Interval1D a, Interval1D b) {\n double alen = a.length();\n double blen = b.length();\n if (alen < blen) return -1;\n else if (alen > blen) return +1;\n else return 0;\n }\n }\n\n\n\n\n /**\n * Unit tests the {@code Interval1D} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n Interval1D[] intervals = new Interval1D[4];\n intervals[0] = new Interval1D(15.0, 33.0);\n intervals[1] = new Interval1D(45.0, 60.0);\n intervals[2] = new Interval1D(20.0, 70.0);\n intervals[3] = new Interval1D(46.0, 55.0);\n\n StdOut.println(\"Unsorted\");\n for (int i = 0; i < intervals.length; i++)\n StdOut.println(intervals[i]);\n StdOut.println();\n\n StdOut.println(\"Sort by min endpoint\");\n Arrays.sort(intervals, Interval1D.MIN_ENDPOINT_ORDER);\n for (int i = 0; i < intervals.length; i++)\n StdOut.println(intervals[i]);\n StdOut.println();\n\n StdOut.println(\"Sort by max endpoint\");\n Arrays.sort(intervals, Interval1D.MAX_ENDPOINT_ORDER);\n for (int i = 0; i < intervals.length; i++)\n StdOut.println(intervals[i]);\n StdOut.println();\n\n StdOut.println(\"Sort by length\");\n Arrays.sort(intervals, Interval1D.LENGTH_ORDER);\n for (int i = 0; i < intervals.length; i++)\n StdOut.println(intervals[i]);\n StdOut.println();\n }\n}\n\n/******************************************************************************\n * Copyright 2002-2025, Robert Sedgewick and Kevin Wayne.\n *\n * This file is part of algs4.jar, which accompanies the textbook\n *\n * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,\n * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.\n * http://algs4.cs.princeton.edu\n *\n *\n * algs4.jar is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * algs4.jar is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with algs4.jar. If not, see http://www.gnu.org/licenses.\n ******************************************************************************/\n", "support_files": [], "metadata": {"number": "2.5.27", "code_execution": true, "url": "https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/Interval1D.java", "params": [""], "dependencies": ["StdOut.java"]}} {"question": "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.", "answer": "/******************************************************************************\n * Compilation: javac FileSorter.java\n * Execution: java FileSorter directory-name\n * Dependencies: StdOut.java\n *\n * Prints out all of the files in the given directory in\n * sorted order.\n *\n * % java FileSorter .\n *\n ******************************************************************************/\n\nimport java.io.File;\nimport java.util.Arrays;\n\npublic class FileSorter {\n\n public static void main(String[] args) {\n File directory = new File(args[0]); // root directory\n if (!directory.exists()) {\n StdOut.println(args[0] + \" does not exist\");\n return;\n }\n if (!directory.isDirectory()) {\n StdOut.println(args[0] + \" is not a directory\");\n return;\n }\n File[] files = directory.listFiles();\n if (files == null) {\n StdOut.println(\"could not read files\");\n return;\n }\n Arrays.sort(files);\n for (int i = 0; i < files.length; i++)\n StdOut.println(files[i].getName());\n }\n\n}\n", "support_files": [], "metadata": {"number": "2.5.28", "code_execution": true, "url": "https://algs4.cs.princeton.edu/25applications/FileSorter.java", "params": ["."], "dependencies": ["StdOut.java"]}} {"question": "Write a client \nprogram GPA.java that creates a symbol table mapping letter grades to numerical \nscores, as in the table below, then reads from standard input a list of letter \ngrades and computes and prints the GPA (the average of the numerical\nscores of the corresponding grades). A+ A A- B+ B B- C+ C C- D F\n4.33 4.00 3.67 3.33 3.00 2.67 2.33 2.00 1.67 1.00 0.00", "answer": "/******************************************************************************\n * Compilation: javac GPA.java\n * Execution: java GPA < input.txt\n * Dependencies: ST.java\n *\n * Create a symbol table mapping letter grades to numerical\n * scores, then read a list of letter grades from standard input,\n * and print the GPA.\n *\n * % java GPA\n * A- B+ B+ B-\n * GPA = 3.25\n *\n ******************************************************************************/\n\npublic class GPA {\n public static void main(String[] args) {\n\n // create symbol table of grades and values\n ST grades = new ST();\n grades.put(\"A\", 4.00);\n grades.put(\"B\", 3.00);\n grades.put(\"C\", 2.00);\n grades.put(\"D\", 1.00);\n grades.put(\"F\", 0.00);\n grades.put(\"A+\", 4.33);\n grades.put(\"B+\", 3.33);\n grades.put(\"C+\", 2.33);\n grades.put(\"C-\", 1.67);\n grades.put(\"A-\", 3.67);\n grades.put(\"B-\", 2.67);\n\n\n // read grades from standard input and compute gpa\n int n = 0;\n double total = 0.0;\n for (n = 0; !StdIn.isEmpty(); n++) {\n String grade = StdIn.readString();\n double value = grades.get(grade);\n total += value;\n }\n double gpa = total / n;\n StdOut.println(\"GPA = \" + gpa);\n }\n}\n\n\n", "support_files": [], "metadata": {"number": "3.1.1", "code_execution": true, "url": "https://algs4.cs.princeton.edu/31elementary/GPA.java", "params": ["< {\n private static final int INIT_SIZE = 8;\n\n private Value[] vals; // symbol table values\n private Key[] keys; // symbol table keys\n private int n = 0; // number of elements in symbol table\n\n public ArrayST() {\n keys = (Key[]) new Object[INIT_SIZE];\n vals = (Value[]) new Object[INIT_SIZE];\n }\n\n // return the number of key-value pairs in the symbol table\n public int size() {\n return n;\n }\n\n // is the symbol table empty?\n public boolean isEmpty() {\n return size() == 0;\n }\n\n // resize the parallel arrays to the given capacity\n private void resize(int capacity) {\n Key[] tempk = (Key[]) new Object[capacity];\n Value[] tempv = (Value[]) new Object[capacity];\n for (int i = 0; i < n; i++)\n tempk[i] = keys[i];\n for (int i = 0; i < n; i++)\n tempv[i] = vals[i];\n keys = tempk;\n vals = tempv;\n }\n\n // insert the key-value pair into the symbol table\n public void put(Key key, Value val) {\n\n // to deal with duplicates\n delete(key);\n\n // double size of arrays if necessary\n if (n >= vals.length) resize(2*n);\n\n // add new key and value at the end of array\n vals[n] = val;\n keys[n] = key;\n n++;\n }\n\n public Value get(Key key) {\n for (int i = 0; i < n; i++)\n if (keys[i].equals(key)) return vals[i];\n return null;\n }\n\n public Iterable keys() {\n Queue queue = new Queue();\n for (int i = 0; i < n; i++)\n queue.enqueue(keys[i]);\n return queue;\n }\n\n // remove given key (and associated value)\n public void delete(Key key) {\n for (int i = 0; i < n; i++) {\n if (key.equals(keys[i])) {\n keys[i] = keys[n-1];\n vals[i] = vals[n-1];\n keys[n-1] = null;\n vals[n-1] = null;\n n--;\n if (n > 0 && n == keys.length/4) resize(keys.length/2);\n return;\n }\n }\n }\n\n\n\n\n /***************************************************************************\n * Test routine.\n ***************************************************************************/\n public static void main(String[] args) {\n ArrayST st = new ArrayST();\n for (int i = 0; !StdIn.isEmpty(); i++) {\n String key = StdIn.readString();\n st.put(key, i);\n }\n for (String s : st.keys())\n StdOut.println(s + \" \" + st.get(s));\n }\n}\n", "support_files": ["https://algs4.cs.princeton.edu/31elementary/tinyST.txt"], "metadata": {"number": "3.1.2", "code_execution": true, "url": "https://algs4.cs.princeton.edu/31elementary/ArrayST.java", "params": ["< tinyST.txt"], "dependencies": ["StdIn.java", "StdOut.java"]}} {"question": "Implement size(), delete(), and keys() for SequentialSearchST.java.", "answer": "/******************************************************************************\n * Compilation: javac SequentialSearchST.java\n * Execution: java SequentialSearchST\n * Dependencies: StdIn.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/31elementary/tinyST.txt\n *\n * Symbol table implementation with sequential search in an\n * unordered linked list of key-value pairs.\n *\n * % more tinyST.txt\n * S E A R C H E X A M P L E\n *\n * % java SequentialSearchST < tinyST.txt\n * L 11\n * P 10\n * M 9\n * X 7\n * H 5\n * C 4\n * R 3\n * A 8\n * E 12\n * S 0\n *\n ******************************************************************************/\n\n/**\n * The {@code SequentialSearchST} class represents an (unordered)\n * symbol table of generic key-value pairs.\n * It supports the usual put, get, contains,\n * delete, size, and is-empty methods.\n * It also provides a keys method for iterating over all of the keys.\n * A symbol table implements the associative array abstraction:\n * when associating a value with a key that is already in the symbol table,\n * the convention is to replace the old value with the new value.\n * The class also uses the convention that values cannot be {@code null}. Setting the\n * value associated with a key to {@code null} is equivalent to deleting the key\n * from the symbol table.\n *

\n * It relies on the {@code equals()} method to test whether two keys\n * are equal. It does not call either the {@code compareTo()} or\n * {@code hashCode()} method.\n *

\n * This implementation uses a singly linked list and\n * sequential search.\n * The put and delete operations take Θ(n).\n * The get and contains operations takes Θ(n)\n * time in the worst case.\n * The size, and is-empty operations take Θ(1) time.\n * Construction takes Θ(1) time.\n *

\n * For additional documentation, see\n * Section 3.1 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class SequentialSearchST {\n private int n; // number of key-value pairs\n private Node first; // the linked list of key-value pairs\n\n // a helper linked list data type\n private class Node {\n private Key key;\n private Value val;\n private Node next;\n\n public Node(Key key, Value val, Node next) {\n this.key = key;\n this.val = val;\n this.next = next;\n }\n }\n\n /**\n * Initializes an empty symbol table.\n */\n public SequentialSearchST() {\n }\n\n /**\n * Returns the number of key-value pairs in this symbol table.\n *\n * @return the number of key-value pairs in this symbol table\n */\n public int size() {\n return n;\n }\n\n /**\n * Returns true if this symbol table is empty.\n *\n * @return {@code true} if this symbol table is empty;\n * {@code false} otherwise\n */\n public boolean isEmpty() {\n return size() == 0;\n }\n\n /**\n * Returns true if this symbol table contains the specified key.\n *\n * @param key the key\n * @return {@code true} if this symbol table contains {@code key};\n * {@code false} otherwise\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public boolean contains(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to contains() is null\");\n return get(key) != null;\n }\n\n /**\n * Returns the value associated with the given key in this symbol table.\n *\n * @param key the key\n * @return the value associated with the given key if the key is in the symbol table\n * and {@code null} if the key is not in the symbol table\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Value get(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to get() is null\");\n for (Node x = first; x != null; x = x.next) {\n if (key.equals(x.key))\n return x.val;\n }\n return null;\n }\n\n /**\n * Inserts the specified key-value pair into the symbol table, overwriting the old\n * value with the new value if the symbol table already contains the specified key.\n * Deletes the specified key (and its associated value) from this symbol table\n * if the specified value is {@code null}.\n *\n * @param key the key\n * @param val the value\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public void put(Key key, Value val) {\n if (key == null) throw new IllegalArgumentException(\"first argument to put() is null\");\n if (val == null) {\n delete(key);\n return;\n }\n\n for (Node x = first; x != null; x = x.next) {\n if (key.equals(x.key)) {\n x.val = val;\n return;\n }\n }\n first = new Node(key, val, first);\n n++;\n }\n\n /**\n * Removes the specified key and its associated value from this symbol table\n * (if the key is in this symbol table).\n *\n * @param key the key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public void delete(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to delete() is null\");\n first = delete(first, key);\n }\n\n // delete key in linked list beginning at Node x\n // warning: function call stack too large if table is large\n private Node delete(Node x, Key key) {\n if (x == null) return null;\n if (key.equals(x.key)) {\n n--;\n return x.next;\n }\n x.next = delete(x.next, key);\n return x;\n }\n\n\n /**\n * Returns all keys in the symbol table as an {@code Iterable}.\n * To iterate over all of the keys in the symbol table named {@code st},\n * use the foreach notation: {@code for (Key key : st.keys())}.\n *\n * @return all keys in the symbol table\n */\n public Iterable keys() {\n Queue queue = new Queue();\n for (Node x = first; x != null; x = x.next)\n queue.enqueue(x.key);\n return queue;\n }\n\n\n /**\n * Unit tests the {@code SequentialSearchST} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n SequentialSearchST st = new SequentialSearchST();\n for (int i = 0; !StdIn.isEmpty(); i++) {\n String key = StdIn.readString();\n st.put(key, i);\n }\n for (String s : st.keys())\n StdOut.println(s + \" \" + st.get(s));\n }\n}\n", "support_files": ["https://algs4.cs.princeton.edu/31elementary/tinyST.txt"], "metadata": {"number": "3.1.5", "code_execution": true, "url": "https://algs4.cs.princeton.edu/31elementary/SequentialSearchST.java", "params": ["< tinyST.txt"], "dependencies": ["StdIn.java", "StdOut.java"]}} {"question": "Implement the delete() method for BinarySearchST.java.", "answer": "/******************************************************************************\n * Compilation: javac BinarySearchST.java\n * Execution: java BinarySearchST\n * Dependencies: StdIn.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/31elementary/tinyST.txt\n *\n * Symbol table implementation with binary search in an ordered array.\n *\n * % more tinyST.txt\n * S E A R C H E X A M P L E\n *\n * % java BinarySearchST < tinyST.txt\n * A 8\n * C 4\n * E 12\n * H 5\n * L 11\n * M 9\n * P 10\n * R 3\n * S 0\n * X 7\n *\n ******************************************************************************/\n\nimport java.util.NoSuchElementException;\n\n/**\n * The {@code BST} class represents an ordered symbol table of generic\n * key-value pairs.\n * It supports the usual put, get, contains,\n * delete, size, and is-empty methods.\n * It also provides ordered methods for finding the minimum,\n * maximum, floor, select, and ceiling.\n * It also provides a keys method for iterating over all of the keys.\n * A symbol table implements the associative array abstraction:\n * when associating a value with a key that is already in the symbol table,\n * the convention is to replace the old value with the new value.\n * Unlike {@link java.util.Map}, this class uses the convention that\n * values cannot be {@code null}—setting the\n * value associated with a key to {@code null} is equivalent to deleting the key\n * from the symbol table.\n *

\n * It requires that\n * the key type implements the {@code Comparable} interface and calls the\n * {@code compareTo()} and method to compare two keys. It does not call either\n * {@code equals()} or {@code hashCode()}.\n *

\n * This implementation uses a sorted array.\n * The put and remove operations take Θ(n)\n * time in the worst case.\n * The contains, ceiling, floor,\n * and rank operations take Θ(log n) time in the worst\n * case.\n * The size, is-empty, minimum, maximum,\n * and select operations take Θ(1) time.\n * Construction takes Θ(1) time.\n *

\n * For alternative implementations of the symbol table API,\n * see {@link ST}, {@link BST}, {@link SequentialSearchST}, {@link RedBlackBST},\n * {@link SeparateChainingHashST}, and {@link LinearProbingHashST},\n * For additional documentation,\n * see Section 3.1 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n */\npublic class BinarySearchST, Value> {\n private static final int INIT_CAPACITY = 2;\n private Key[] keys;\n private Value[] vals;\n private int n = 0;\n\n /**\n * Initializes an empty symbol table.\n */\n public BinarySearchST() {\n this(INIT_CAPACITY);\n }\n\n /**\n * Initializes an empty symbol table with the specified initial capacity.\n * @param capacity the maximum capacity\n */\n public BinarySearchST(int capacity) {\n keys = (Key[]) new Comparable[capacity];\n vals = (Value[]) new Object[capacity];\n }\n\n // resize the underlying arrays\n private void resize(int capacity) {\n assert capacity >= n;\n Key[] tempk = (Key[]) new Comparable[capacity];\n Value[] tempv = (Value[]) new Object[capacity];\n for (int i = 0; i < n; i++) {\n tempk[i] = keys[i];\n tempv[i] = vals[i];\n }\n vals = tempv;\n keys = tempk;\n }\n\n /**\n * Returns the number of key-value pairs in this symbol table.\n *\n * @return the number of key-value pairs in this symbol table\n */\n public int size() {\n return n;\n }\n\n /**\n * Returns true if this symbol table is empty.\n *\n * @return {@code true} if this symbol table is empty;\n * {@code false} otherwise\n */\n public boolean isEmpty() {\n return size() == 0;\n }\n\n\n /**\n * Does this symbol table contain the given key?\n *\n * @param key the key\n * @return {@code true} if this symbol table contains {@code key} and\n * {@code false} otherwise\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public boolean contains(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to contains() is null\");\n return get(key) != null;\n }\n\n /**\n * Returns the value associated with the given key in this symbol table.\n *\n * @param key the key\n * @return the value associated with the given key if the key is in the symbol table\n * and {@code null} if the key is not in the symbol table\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Value get(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to get() is null\");\n if (isEmpty()) return null;\n int i = rank(key);\n if (i < n && keys[i].compareTo(key) == 0) return vals[i];\n return null;\n }\n\n /**\n * Returns the number of keys in this symbol table strictly less than {@code key}.\n *\n * @param key the key\n * @return the number of keys in the symbol table strictly less than {@code key}\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public int rank(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to rank() is null\");\n\n int lo = 0, hi = n-1;\n while (lo <= hi) {\n int mid = lo + (hi - lo) / 2;\n int cmp = key.compareTo(keys[mid]);\n if (cmp < 0) hi = mid - 1;\n else if (cmp > 0) lo = mid + 1;\n else return mid;\n }\n return lo;\n }\n\n\n\n /**\n * Inserts the specified key-value pair into the symbol table, overwriting the old\n * value with the new value if the symbol table already contains the specified key.\n * Deletes the specified key (and its associated value) from this symbol table\n * if the specified value is {@code null}.\n *\n * @param key the key\n * @param val the value\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public void put(Key key, Value val) {\n if (key == null) throw new IllegalArgumentException(\"first argument to put() is null\");\n\n if (val == null) {\n delete(key);\n return;\n }\n\n int i = rank(key);\n\n // key is already in table\n if (i < n && keys[i].compareTo(key) == 0) {\n vals[i] = val;\n return;\n }\n\n // insert new key-value pair\n if (n == keys.length) resize(2*keys.length);\n\n for (int j = n; j > i; j--) {\n keys[j] = keys[j-1];\n vals[j] = vals[j-1];\n }\n keys[i] = key;\n vals[i] = val;\n n++;\n\n assert check();\n }\n\n /**\n * Removes the specified key and associated value from this symbol table\n * (if the key is in the symbol table).\n *\n * @param key the key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public void delete(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to delete() is null\");\n if (isEmpty()) return;\n\n // compute rank\n int i = rank(key);\n\n // key not in table\n if (i == n || keys[i].compareTo(key) != 0) {\n return;\n }\n\n for (int j = i; j < n-1; j++) {\n keys[j] = keys[j+1];\n vals[j] = vals[j+1];\n }\n\n n--;\n keys[n] = null; // to avoid loitering\n vals[n] = null;\n\n // resize if 1/4 full\n if (n > 0 && n == keys.length/4) resize(keys.length/2);\n\n assert check();\n }\n\n /**\n * Removes the smallest key and associated value from this symbol table.\n *\n * @throws NoSuchElementException if the symbol table is empty\n */\n public void deleteMin() {\n if (isEmpty()) throw new NoSuchElementException(\"Symbol table underflow error\");\n delete(min());\n }\n\n /**\n * Removes the largest key and associated value from this symbol table.\n *\n * @throws NoSuchElementException if the symbol table is empty\n */\n public void deleteMax() {\n if (isEmpty()) throw new NoSuchElementException(\"Symbol table underflow error\");\n delete(max());\n }\n\n\n /***************************************************************************\n * Ordered symbol table methods.\n ***************************************************************************/\n\n /**\n * Returns the smallest key in this symbol table.\n *\n * @return the smallest key in this symbol table\n * @throws NoSuchElementException if this symbol table is empty\n */\n public Key min() {\n if (isEmpty()) throw new NoSuchElementException(\"called min() with empty symbol table\");\n return keys[0];\n }\n\n /**\n * Returns the largest key in this symbol table.\n *\n * @return the largest key in this symbol table\n * @throws NoSuchElementException if this symbol table is empty\n */\n public Key max() {\n if (isEmpty()) throw new NoSuchElementException(\"called max() with empty symbol table\");\n return keys[n-1];\n }\n\n /**\n * Return the kth smallest key in this symbol table.\n *\n * @param k the order statistic\n * @return the {@code k}th smallest key in this symbol table\n * @throws IllegalArgumentException unless {@code k} is between 0 and\n * n–1\n */\n public Key select(int k) {\n if (k < 0 || k >= size()) {\n throw new IllegalArgumentException(\"called select() with invalid argument: \" + k);\n }\n return keys[k];\n }\n\n /**\n * Returns the largest key in this symbol table less than or equal to {@code key}.\n *\n * @param key the key\n * @return the largest key in this symbol table less than or equal to {@code key}\n * @throws NoSuchElementException if there is no such key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Key floor(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to floor() is null\");\n int i = rank(key);\n if (i < n && key.compareTo(keys[i]) == 0) return keys[i];\n if (i == 0) throw new NoSuchElementException(\"argument to floor() is too small\");\n else return keys[i-1];\n }\n\n /**\n * Returns the smallest key in this symbol table greater than or equal to {@code key}.\n *\n * @param key the key\n * @return the smallest key in this symbol table greater than or equal to {@code key}\n * @throws NoSuchElementException if there is no such key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Key ceiling(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to ceiling() is null\");\n int i = rank(key);\n if (i == n) throw new NoSuchElementException(\"argument to ceiling() is too large\");\n else return keys[i];\n }\n\n /**\n * Returns the number of keys in this symbol table in the specified range.\n *\n * @param lo minimum endpoint\n * @param hi maximum endpoint\n * @return the number of keys in this symbol table between {@code lo}\n * (inclusive) and {@code hi} (inclusive)\n * @throws IllegalArgumentException if either {@code lo} or {@code hi}\n * is {@code null}\n */\n public int size(Key lo, Key hi) {\n if (lo == null) throw new IllegalArgumentException(\"first argument to size() is null\");\n if (hi == null) throw new IllegalArgumentException(\"second argument to size() is null\");\n\n if (lo.compareTo(hi) > 0) return 0;\n if (contains(hi)) return rank(hi) - rank(lo) + 1;\n else return rank(hi) - rank(lo);\n }\n\n /**\n * Returns all keys in this symbol table as an {@code Iterable}.\n * To iterate over all of the keys in the symbol table named {@code st},\n * use the foreach notation: {@code for (Key key : st.keys())}.\n *\n * @return all keys in this symbol table\n */\n public Iterable keys() {\n return keys(min(), max());\n }\n\n /**\n * Returns all keys in this symbol table in the given range,\n * as an {@code Iterable}.\n *\n * @param lo minimum endpoint\n * @param hi maximum endpoint\n * @return all keys in this symbol table between {@code lo}\n * (inclusive) and {@code hi} (inclusive)\n * @throws IllegalArgumentException if either {@code lo} or {@code hi}\n * is {@code null}\n */\n public Iterable keys(Key lo, Key hi) {\n if (lo == null) throw new IllegalArgumentException(\"first argument to keys() is null\");\n if (hi == null) throw new IllegalArgumentException(\"second argument to keys() is null\");\n\n Queue queue = new Queue();\n if (lo.compareTo(hi) > 0) return queue;\n for (int i = rank(lo); i < rank(hi); i++)\n queue.enqueue(keys[i]);\n if (contains(hi)) queue.enqueue(keys[rank(hi)]);\n return queue;\n }\n\n\n /***************************************************************************\n * Check internal invariants.\n ***************************************************************************/\n\n private boolean check() {\n return isSorted() && rankCheck();\n }\n\n // are the items in the array in ascending order?\n private boolean isSorted() {\n for (int i = 1; i < size(); i++)\n if (keys[i].compareTo(keys[i-1]) < 0) return false;\n return true;\n }\n\n // check that rank(select(i)) = i\n private boolean rankCheck() {\n for (int i = 0; i < size(); i++)\n if (i != rank(select(i))) return false;\n for (int i = 0; i < size(); i++)\n if (keys[i].compareTo(select(rank(keys[i]))) != 0) return false;\n return true;\n }\n\n\n /**\n * Unit tests the {@code BinarySearchST} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n BinarySearchST st = new BinarySearchST();\n for (int i = 0; !StdIn.isEmpty(); i++) {\n String key = StdIn.readString();\n st.put(key, i);\n }\n for (String s : st.keys())\n StdOut.println(s + \" \" + st.get(s));\n }\n}\n", "support_files": ["https://algs4.cs.princeton.edu/31elementary/tinyST.txt"], "metadata": {"number": "3.1.16", "code_execution": true, "url": "https://algs4.cs.princeton.edu/31elementary/BinarySearchST.java", "params": ["< tinyST.txt"], "dependencies": ["StdIn.java", "StdOut.java"]}} {"question": "Implement the floor() method for BinarySearchST.java .", "answer": "/******************************************************************************\n * Compilation: javac BinarySearchST.java\n * Execution: java BinarySearchST\n * Dependencies: StdIn.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/31elementary/tinyST.txt\n *\n * Symbol table implementation with binary search in an ordered array.\n *\n * % more tinyST.txt\n * S E A R C H E X A M P L E\n *\n * % java BinarySearchST < tinyST.txt\n * A 8\n * C 4\n * E 12\n * H 5\n * L 11\n * M 9\n * P 10\n * R 3\n * S 0\n * X 7\n *\n ******************************************************************************/\n\nimport java.util.NoSuchElementException;\n\n/**\n * The {@code BST} class represents an ordered symbol table of generic\n * key-value pairs.\n * It supports the usual put, get, contains,\n * delete, size, and is-empty methods.\n * It also provides ordered methods for finding the minimum,\n * maximum, floor, select, and ceiling.\n * It also provides a keys method for iterating over all of the keys.\n * A symbol table implements the associative array abstraction:\n * when associating a value with a key that is already in the symbol table,\n * the convention is to replace the old value with the new value.\n * Unlike {@link java.util.Map}, this class uses the convention that\n * values cannot be {@code null}—setting the\n * value associated with a key to {@code null} is equivalent to deleting the key\n * from the symbol table.\n *

\n * It requires that\n * the key type implements the {@code Comparable} interface and calls the\n * {@code compareTo()} and method to compare two keys. It does not call either\n * {@code equals()} or {@code hashCode()}.\n *

\n * This implementation uses a sorted array.\n * The put and remove operations take Θ(n)\n * time in the worst case.\n * The contains, ceiling, floor,\n * and rank operations take Θ(log n) time in the worst\n * case.\n * The size, is-empty, minimum, maximum,\n * and select operations take Θ(1) time.\n * Construction takes Θ(1) time.\n *

\n * For alternative implementations of the symbol table API,\n * see {@link ST}, {@link BST}, {@link SequentialSearchST}, {@link RedBlackBST},\n * {@link SeparateChainingHashST}, and {@link LinearProbingHashST},\n * For additional documentation,\n * see Section 3.1 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n */\npublic class BinarySearchST, Value> {\n private static final int INIT_CAPACITY = 2;\n private Key[] keys;\n private Value[] vals;\n private int n = 0;\n\n /**\n * Initializes an empty symbol table.\n */\n public BinarySearchST() {\n this(INIT_CAPACITY);\n }\n\n /**\n * Initializes an empty symbol table with the specified initial capacity.\n * @param capacity the maximum capacity\n */\n public BinarySearchST(int capacity) {\n keys = (Key[]) new Comparable[capacity];\n vals = (Value[]) new Object[capacity];\n }\n\n // resize the underlying arrays\n private void resize(int capacity) {\n assert capacity >= n;\n Key[] tempk = (Key[]) new Comparable[capacity];\n Value[] tempv = (Value[]) new Object[capacity];\n for (int i = 0; i < n; i++) {\n tempk[i] = keys[i];\n tempv[i] = vals[i];\n }\n vals = tempv;\n keys = tempk;\n }\n\n /**\n * Returns the number of key-value pairs in this symbol table.\n *\n * @return the number of key-value pairs in this symbol table\n */\n public int size() {\n return n;\n }\n\n /**\n * Returns true if this symbol table is empty.\n *\n * @return {@code true} if this symbol table is empty;\n * {@code false} otherwise\n */\n public boolean isEmpty() {\n return size() == 0;\n }\n\n\n /**\n * Does this symbol table contain the given key?\n *\n * @param key the key\n * @return {@code true} if this symbol table contains {@code key} and\n * {@code false} otherwise\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public boolean contains(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to contains() is null\");\n return get(key) != null;\n }\n\n /**\n * Returns the value associated with the given key in this symbol table.\n *\n * @param key the key\n * @return the value associated with the given key if the key is in the symbol table\n * and {@code null} if the key is not in the symbol table\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Value get(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to get() is null\");\n if (isEmpty()) return null;\n int i = rank(key);\n if (i < n && keys[i].compareTo(key) == 0) return vals[i];\n return null;\n }\n\n /**\n * Returns the number of keys in this symbol table strictly less than {@code key}.\n *\n * @param key the key\n * @return the number of keys in the symbol table strictly less than {@code key}\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public int rank(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to rank() is null\");\n\n int lo = 0, hi = n-1;\n while (lo <= hi) {\n int mid = lo + (hi - lo) / 2;\n int cmp = key.compareTo(keys[mid]);\n if (cmp < 0) hi = mid - 1;\n else if (cmp > 0) lo = mid + 1;\n else return mid;\n }\n return lo;\n }\n\n\n\n /**\n * Inserts the specified key-value pair into the symbol table, overwriting the old\n * value with the new value if the symbol table already contains the specified key.\n * Deletes the specified key (and its associated value) from this symbol table\n * if the specified value is {@code null}.\n *\n * @param key the key\n * @param val the value\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public void put(Key key, Value val) {\n if (key == null) throw new IllegalArgumentException(\"first argument to put() is null\");\n\n if (val == null) {\n delete(key);\n return;\n }\n\n int i = rank(key);\n\n // key is already in table\n if (i < n && keys[i].compareTo(key) == 0) {\n vals[i] = val;\n return;\n }\n\n // insert new key-value pair\n if (n == keys.length) resize(2*keys.length);\n\n for (int j = n; j > i; j--) {\n keys[j] = keys[j-1];\n vals[j] = vals[j-1];\n }\n keys[i] = key;\n vals[i] = val;\n n++;\n\n assert check();\n }\n\n /**\n * Removes the specified key and associated value from this symbol table\n * (if the key is in the symbol table).\n *\n * @param key the key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public void delete(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to delete() is null\");\n if (isEmpty()) return;\n\n // compute rank\n int i = rank(key);\n\n // key not in table\n if (i == n || keys[i].compareTo(key) != 0) {\n return;\n }\n\n for (int j = i; j < n-1; j++) {\n keys[j] = keys[j+1];\n vals[j] = vals[j+1];\n }\n\n n--;\n keys[n] = null; // to avoid loitering\n vals[n] = null;\n\n // resize if 1/4 full\n if (n > 0 && n == keys.length/4) resize(keys.length/2);\n\n assert check();\n }\n\n /**\n * Removes the smallest key and associated value from this symbol table.\n *\n * @throws NoSuchElementException if the symbol table is empty\n */\n public void deleteMin() {\n if (isEmpty()) throw new NoSuchElementException(\"Symbol table underflow error\");\n delete(min());\n }\n\n /**\n * Removes the largest key and associated value from this symbol table.\n *\n * @throws NoSuchElementException if the symbol table is empty\n */\n public void deleteMax() {\n if (isEmpty()) throw new NoSuchElementException(\"Symbol table underflow error\");\n delete(max());\n }\n\n\n /***************************************************************************\n * Ordered symbol table methods.\n ***************************************************************************/\n\n /**\n * Returns the smallest key in this symbol table.\n *\n * @return the smallest key in this symbol table\n * @throws NoSuchElementException if this symbol table is empty\n */\n public Key min() {\n if (isEmpty()) throw new NoSuchElementException(\"called min() with empty symbol table\");\n return keys[0];\n }\n\n /**\n * Returns the largest key in this symbol table.\n *\n * @return the largest key in this symbol table\n * @throws NoSuchElementException if this symbol table is empty\n */\n public Key max() {\n if (isEmpty()) throw new NoSuchElementException(\"called max() with empty symbol table\");\n return keys[n-1];\n }\n\n /**\n * Return the kth smallest key in this symbol table.\n *\n * @param k the order statistic\n * @return the {@code k}th smallest key in this symbol table\n * @throws IllegalArgumentException unless {@code k} is between 0 and\n * n–1\n */\n public Key select(int k) {\n if (k < 0 || k >= size()) {\n throw new IllegalArgumentException(\"called select() with invalid argument: \" + k);\n }\n return keys[k];\n }\n\n /**\n * Returns the largest key in this symbol table less than or equal to {@code key}.\n *\n * @param key the key\n * @return the largest key in this symbol table less than or equal to {@code key}\n * @throws NoSuchElementException if there is no such key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Key floor(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to floor() is null\");\n int i = rank(key);\n if (i < n && key.compareTo(keys[i]) == 0) return keys[i];\n if (i == 0) throw new NoSuchElementException(\"argument to floor() is too small\");\n else return keys[i-1];\n }\n\n /**\n * Returns the smallest key in this symbol table greater than or equal to {@code key}.\n *\n * @param key the key\n * @return the smallest key in this symbol table greater than or equal to {@code key}\n * @throws NoSuchElementException if there is no such key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Key ceiling(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to ceiling() is null\");\n int i = rank(key);\n if (i == n) throw new NoSuchElementException(\"argument to ceiling() is too large\");\n else return keys[i];\n }\n\n /**\n * Returns the number of keys in this symbol table in the specified range.\n *\n * @param lo minimum endpoint\n * @param hi maximum endpoint\n * @return the number of keys in this symbol table between {@code lo}\n * (inclusive) and {@code hi} (inclusive)\n * @throws IllegalArgumentException if either {@code lo} or {@code hi}\n * is {@code null}\n */\n public int size(Key lo, Key hi) {\n if (lo == null) throw new IllegalArgumentException(\"first argument to size() is null\");\n if (hi == null) throw new IllegalArgumentException(\"second argument to size() is null\");\n\n if (lo.compareTo(hi) > 0) return 0;\n if (contains(hi)) return rank(hi) - rank(lo) + 1;\n else return rank(hi) - rank(lo);\n }\n\n /**\n * Returns all keys in this symbol table as an {@code Iterable}.\n * To iterate over all of the keys in the symbol table named {@code st},\n * use the foreach notation: {@code for (Key key : st.keys())}.\n *\n * @return all keys in this symbol table\n */\n public Iterable keys() {\n return keys(min(), max());\n }\n\n /**\n * Returns all keys in this symbol table in the given range,\n * as an {@code Iterable}.\n *\n * @param lo minimum endpoint\n * @param hi maximum endpoint\n * @return all keys in this symbol table between {@code lo}\n * (inclusive) and {@code hi} (inclusive)\n * @throws IllegalArgumentException if either {@code lo} or {@code hi}\n * is {@code null}\n */\n public Iterable keys(Key lo, Key hi) {\n if (lo == null) throw new IllegalArgumentException(\"first argument to keys() is null\");\n if (hi == null) throw new IllegalArgumentException(\"second argument to keys() is null\");\n\n Queue queue = new Queue();\n if (lo.compareTo(hi) > 0) return queue;\n for (int i = rank(lo); i < rank(hi); i++)\n queue.enqueue(keys[i]);\n if (contains(hi)) queue.enqueue(keys[rank(hi)]);\n return queue;\n }\n\n\n /***************************************************************************\n * Check internal invariants.\n ***************************************************************************/\n\n private boolean check() {\n return isSorted() && rankCheck();\n }\n\n // are the items in the array in ascending order?\n private boolean isSorted() {\n for (int i = 1; i < size(); i++)\n if (keys[i].compareTo(keys[i-1]) < 0) return false;\n return true;\n }\n\n // check that rank(select(i)) = i\n private boolean rankCheck() {\n for (int i = 0; i < size(); i++)\n if (i != rank(select(i))) return false;\n for (int i = 0; i < size(); i++)\n if (keys[i].compareTo(select(rank(keys[i]))) != 0) return false;\n return true;\n }\n\n\n /**\n * Unit tests the {@code BinarySearchST} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n BinarySearchST st = new BinarySearchST();\n for (int i = 0; !StdIn.isEmpty(); i++) {\n String key = StdIn.readString();\n st.put(key, i);\n }\n for (String s : st.keys())\n StdOut.println(s + \" \" + st.get(s));\n }\n}\n", "support_files": ["https://algs4.cs.princeton.edu/31elementary/tinyST.txt"], "metadata": {"number": "3.1.17", "code_execution": true, "url": "https://algs4.cs.princeton.edu/31elementary/BinarySearchST.java", "params": ["< tinyST.txt"], "dependencies": ["StdIn.java", "StdOut.java"]}} {"question": "Certification. Add assert statements to BinarySearchST.java to check algorithm invariants and data structure integrity after every \ninsertion and deletion. For example, every index i should always be equal to rank(select(i)) and the array should \nalways be in order.", "answer": "/******************************************************************************\n * Compilation: javac BinarySearchST.java\n * Execution: java BinarySearchST\n * Dependencies: StdIn.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/31elementary/tinyST.txt\n *\n * Symbol table implementation with binary search in an ordered array.\n *\n * % more tinyST.txt\n * S E A R C H E X A M P L E\n *\n * % java BinarySearchST < tinyST.txt\n * A 8\n * C 4\n * E 12\n * H 5\n * L 11\n * M 9\n * P 10\n * R 3\n * S 0\n * X 7\n *\n ******************************************************************************/\n\nimport java.util.NoSuchElementException;\n\n/**\n * The {@code BST} class represents an ordered symbol table of generic\n * key-value pairs.\n * It supports the usual put, get, contains,\n * delete, size, and is-empty methods.\n * It also provides ordered methods for finding the minimum,\n * maximum, floor, select, and ceiling.\n * It also provides a keys method for iterating over all of the keys.\n * A symbol table implements the associative array abstraction:\n * when associating a value with a key that is already in the symbol table,\n * the convention is to replace the old value with the new value.\n * Unlike {@link java.util.Map}, this class uses the convention that\n * values cannot be {@code null}—setting the\n * value associated with a key to {@code null} is equivalent to deleting the key\n * from the symbol table.\n *

\n * It requires that\n * the key type implements the {@code Comparable} interface and calls the\n * {@code compareTo()} and method to compare two keys. It does not call either\n * {@code equals()} or {@code hashCode()}.\n *

\n * This implementation uses a sorted array.\n * The put and remove operations take Θ(n)\n * time in the worst case.\n * The contains, ceiling, floor,\n * and rank operations take Θ(log n) time in the worst\n * case.\n * The size, is-empty, minimum, maximum,\n * and select operations take Θ(1) time.\n * Construction takes Θ(1) time.\n *

\n * For alternative implementations of the symbol table API,\n * see {@link ST}, {@link BST}, {@link SequentialSearchST}, {@link RedBlackBST},\n * {@link SeparateChainingHashST}, and {@link LinearProbingHashST},\n * For additional documentation,\n * see Section 3.1 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n */\npublic class BinarySearchST, Value> {\n private static final int INIT_CAPACITY = 2;\n private Key[] keys;\n private Value[] vals;\n private int n = 0;\n\n /**\n * Initializes an empty symbol table.\n */\n public BinarySearchST() {\n this(INIT_CAPACITY);\n }\n\n /**\n * Initializes an empty symbol table with the specified initial capacity.\n * @param capacity the maximum capacity\n */\n public BinarySearchST(int capacity) {\n keys = (Key[]) new Comparable[capacity];\n vals = (Value[]) new Object[capacity];\n }\n\n // resize the underlying arrays\n private void resize(int capacity) {\n assert capacity >= n;\n Key[] tempk = (Key[]) new Comparable[capacity];\n Value[] tempv = (Value[]) new Object[capacity];\n for (int i = 0; i < n; i++) {\n tempk[i] = keys[i];\n tempv[i] = vals[i];\n }\n vals = tempv;\n keys = tempk;\n }\n\n /**\n * Returns the number of key-value pairs in this symbol table.\n *\n * @return the number of key-value pairs in this symbol table\n */\n public int size() {\n return n;\n }\n\n /**\n * Returns true if this symbol table is empty.\n *\n * @return {@code true} if this symbol table is empty;\n * {@code false} otherwise\n */\n public boolean isEmpty() {\n return size() == 0;\n }\n\n\n /**\n * Does this symbol table contain the given key?\n *\n * @param key the key\n * @return {@code true} if this symbol table contains {@code key} and\n * {@code false} otherwise\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public boolean contains(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to contains() is null\");\n return get(key) != null;\n }\n\n /**\n * Returns the value associated with the given key in this symbol table.\n *\n * @param key the key\n * @return the value associated with the given key if the key is in the symbol table\n * and {@code null} if the key is not in the symbol table\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Value get(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to get() is null\");\n if (isEmpty()) return null;\n int i = rank(key);\n if (i < n && keys[i].compareTo(key) == 0) return vals[i];\n return null;\n }\n\n /**\n * Returns the number of keys in this symbol table strictly less than {@code key}.\n *\n * @param key the key\n * @return the number of keys in the symbol table strictly less than {@code key}\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public int rank(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to rank() is null\");\n\n int lo = 0, hi = n-1;\n while (lo <= hi) {\n int mid = lo + (hi - lo) / 2;\n int cmp = key.compareTo(keys[mid]);\n if (cmp < 0) hi = mid - 1;\n else if (cmp > 0) lo = mid + 1;\n else return mid;\n }\n return lo;\n }\n\n\n\n /**\n * Inserts the specified key-value pair into the symbol table, overwriting the old\n * value with the new value if the symbol table already contains the specified key.\n * Deletes the specified key (and its associated value) from this symbol table\n * if the specified value is {@code null}.\n *\n * @param key the key\n * @param val the value\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public void put(Key key, Value val) {\n if (key == null) throw new IllegalArgumentException(\"first argument to put() is null\");\n\n if (val == null) {\n delete(key);\n return;\n }\n\n int i = rank(key);\n\n // key is already in table\n if (i < n && keys[i].compareTo(key) == 0) {\n vals[i] = val;\n return;\n }\n\n // insert new key-value pair\n if (n == keys.length) resize(2*keys.length);\n\n for (int j = n; j > i; j--) {\n keys[j] = keys[j-1];\n vals[j] = vals[j-1];\n }\n keys[i] = key;\n vals[i] = val;\n n++;\n\n assert check();\n }\n\n /**\n * Removes the specified key and associated value from this symbol table\n * (if the key is in the symbol table).\n *\n * @param key the key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public void delete(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to delete() is null\");\n if (isEmpty()) return;\n\n // compute rank\n int i = rank(key);\n\n // key not in table\n if (i == n || keys[i].compareTo(key) != 0) {\n return;\n }\n\n for (int j = i; j < n-1; j++) {\n keys[j] = keys[j+1];\n vals[j] = vals[j+1];\n }\n\n n--;\n keys[n] = null; // to avoid loitering\n vals[n] = null;\n\n // resize if 1/4 full\n if (n > 0 && n == keys.length/4) resize(keys.length/2);\n\n assert check();\n }\n\n /**\n * Removes the smallest key and associated value from this symbol table.\n *\n * @throws NoSuchElementException if the symbol table is empty\n */\n public void deleteMin() {\n if (isEmpty()) throw new NoSuchElementException(\"Symbol table underflow error\");\n delete(min());\n }\n\n /**\n * Removes the largest key and associated value from this symbol table.\n *\n * @throws NoSuchElementException if the symbol table is empty\n */\n public void deleteMax() {\n if (isEmpty()) throw new NoSuchElementException(\"Symbol table underflow error\");\n delete(max());\n }\n\n\n /***************************************************************************\n * Ordered symbol table methods.\n ***************************************************************************/\n\n /**\n * Returns the smallest key in this symbol table.\n *\n * @return the smallest key in this symbol table\n * @throws NoSuchElementException if this symbol table is empty\n */\n public Key min() {\n if (isEmpty()) throw new NoSuchElementException(\"called min() with empty symbol table\");\n return keys[0];\n }\n\n /**\n * Returns the largest key in this symbol table.\n *\n * @return the largest key in this symbol table\n * @throws NoSuchElementException if this symbol table is empty\n */\n public Key max() {\n if (isEmpty()) throw new NoSuchElementException(\"called max() with empty symbol table\");\n return keys[n-1];\n }\n\n /**\n * Return the kth smallest key in this symbol table.\n *\n * @param k the order statistic\n * @return the {@code k}th smallest key in this symbol table\n * @throws IllegalArgumentException unless {@code k} is between 0 and\n * n–1\n */\n public Key select(int k) {\n if (k < 0 || k >= size()) {\n throw new IllegalArgumentException(\"called select() with invalid argument: \" + k);\n }\n return keys[k];\n }\n\n /**\n * Returns the largest key in this symbol table less than or equal to {@code key}.\n *\n * @param key the key\n * @return the largest key in this symbol table less than or equal to {@code key}\n * @throws NoSuchElementException if there is no such key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Key floor(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to floor() is null\");\n int i = rank(key);\n if (i < n && key.compareTo(keys[i]) == 0) return keys[i];\n if (i == 0) throw new NoSuchElementException(\"argument to floor() is too small\");\n else return keys[i-1];\n }\n\n /**\n * Returns the smallest key in this symbol table greater than or equal to {@code key}.\n *\n * @param key the key\n * @return the smallest key in this symbol table greater than or equal to {@code key}\n * @throws NoSuchElementException if there is no such key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Key ceiling(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to ceiling() is null\");\n int i = rank(key);\n if (i == n) throw new NoSuchElementException(\"argument to ceiling() is too large\");\n else return keys[i];\n }\n\n /**\n * Returns the number of keys in this symbol table in the specified range.\n *\n * @param lo minimum endpoint\n * @param hi maximum endpoint\n * @return the number of keys in this symbol table between {@code lo}\n * (inclusive) and {@code hi} (inclusive)\n * @throws IllegalArgumentException if either {@code lo} or {@code hi}\n * is {@code null}\n */\n public int size(Key lo, Key hi) {\n if (lo == null) throw new IllegalArgumentException(\"first argument to size() is null\");\n if (hi == null) throw new IllegalArgumentException(\"second argument to size() is null\");\n\n if (lo.compareTo(hi) > 0) return 0;\n if (contains(hi)) return rank(hi) - rank(lo) + 1;\n else return rank(hi) - rank(lo);\n }\n\n /**\n * Returns all keys in this symbol table as an {@code Iterable}.\n * To iterate over all of the keys in the symbol table named {@code st},\n * use the foreach notation: {@code for (Key key : st.keys())}.\n *\n * @return all keys in this symbol table\n */\n public Iterable keys() {\n return keys(min(), max());\n }\n\n /**\n * Returns all keys in this symbol table in the given range,\n * as an {@code Iterable}.\n *\n * @param lo minimum endpoint\n * @param hi maximum endpoint\n * @return all keys in this symbol table between {@code lo}\n * (inclusive) and {@code hi} (inclusive)\n * @throws IllegalArgumentException if either {@code lo} or {@code hi}\n * is {@code null}\n */\n public Iterable keys(Key lo, Key hi) {\n if (lo == null) throw new IllegalArgumentException(\"first argument to keys() is null\");\n if (hi == null) throw new IllegalArgumentException(\"second argument to keys() is null\");\n\n Queue queue = new Queue();\n if (lo.compareTo(hi) > 0) return queue;\n for (int i = rank(lo); i < rank(hi); i++)\n queue.enqueue(keys[i]);\n if (contains(hi)) queue.enqueue(keys[rank(hi)]);\n return queue;\n }\n\n\n /***************************************************************************\n * Check internal invariants.\n ***************************************************************************/\n\n private boolean check() {\n return isSorted() && rankCheck();\n }\n\n // are the items in the array in ascending order?\n private boolean isSorted() {\n for (int i = 1; i < size(); i++)\n if (keys[i].compareTo(keys[i-1]) < 0) return false;\n return true;\n }\n\n // check that rank(select(i)) = i\n private boolean rankCheck() {\n for (int i = 0; i < size(); i++)\n if (i != rank(select(i))) return false;\n for (int i = 0; i < size(); i++)\n if (keys[i].compareTo(select(rank(keys[i]))) != 0) return false;\n return true;\n }\n\n\n /**\n * Unit tests the {@code BinarySearchST} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n BinarySearchST st = new BinarySearchST();\n for (int i = 0; !StdIn.isEmpty(); i++) {\n String key = StdIn.readString();\n st.put(key, i);\n }\n for (String s : st.keys())\n StdOut.println(s + \" \" + st.get(s));\n }\n}\n", "support_files": ["https://algs4.cs.princeton.edu/31elementary/tinyST.txt"], "metadata": {"number": "3.1.30", "code_execution": true, "url": "https://algs4.cs.princeton.edu/31elementary/BinarySearchST.java", "params": ["< tinyST.txt"], "dependencies": ["StdIn.java", "StdOut.java"]}} {"question": "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).", "answer": "Use the same convention as the textbook implementation: an empty tree has height -1 and a one-node tree has height 0.\n\nRecursive implementation:\n\n```java\npublic int height() {\n return height(root);\n}\n\nprivate int height(Node x) {\n if (x == null) return -1;\n return 1 + Math.max(height(x.left), height(x.right));\n}\n```\n\nConstant-time query implementation: add `int height;` to `Node`, initialize it to 0 for a new node, and update it after every insertion/deletion exactly as `size` is updated:\n\n```java\nx.height = 1 + Math.max(height(x.left), height(x.right));\n\nprivate int height(Node x) {\n return x == null ? -1 : x.height;\n}\n\npublic int height() {\n return height(root);\n}\n```", "support_files": ["https://algs4.cs.princeton.edu/32bst/tinyST.txt"], "metadata": {"number": "3.2.6", "code_execution": false}} {"question": "Give nonrecursive implementations of get() , put() , and keys() for BST.", "answer": "/******************************************************************************\n * Compilation: javac NonrecursiveBST.java\n * Execution: java NonrecursiveBST < input.txt\n * Dependencies: StdOut.java StdIn.java\n *\n * A symbol table implemented with a binary search tree using\n * iteration instead of recursion for put(), get(), and keys().\n *\n * % more tinyST.txt\n * S E A R C H E X A M P L E\n *\n * % java NonrecursiveBST < tinyST.txt\n * A 8\n * C 4\n * E 12\n * H 5\n * L 11\n * M 9\n * P 10\n * R 3\n * S 0\n * X 7\n *\n ******************************************************************************/\n\npublic class NonrecursiveBST, Value> {\n\n // root of BST\n private Node root;\n\n private class Node {\n private Key key; // sorted by key\n private Value val; // associated value\n private Node left, right; // left and right subtrees\n\n public Node(Key key, Value val) {\n this.key = key;\n this.val = val;\n }\n }\n\n\n /***************************************************************************\n * Insert key-value pair into symbol table (nonrecursive version).\n ***************************************************************************/\n public void put(Key key, Value val) {\n Node z = new Node(key, val);\n if (root == null) {\n root = z;\n return;\n }\n\n Node parent = null, x = root;\n while (x != null) {\n parent = x;\n int cmp = key.compareTo(x.key);\n if (cmp < 0) x = x.left;\n else if (cmp > 0) x = x.right;\n else {\n x.val = val;\n return;\n }\n }\n int cmp = key.compareTo(parent.key);\n if (cmp < 0) parent.left = z;\n else parent.right = z;\n }\n\n\n /***************************************************************************\n * Search BST for given key, nonrecursive version.\n ***************************************************************************/\n Value get(Key key) {\n Node x = root;\n while (x != null) {\n int cmp = key.compareTo(x.key);\n if (cmp < 0) x = x.left;\n else if (cmp > 0) x = x.right;\n else return x.val;\n }\n return null;\n }\n\n /***************************************************************************\n * Inorder traversal.\n ***************************************************************************/\n public Iterable keys() {\n Stack stack = new Stack();\n Queue queue = new Queue();\n Node x = root;\n while (x != null || !stack.isEmpty()) {\n if (x != null) {\n stack.push(x);\n x = x.left;\n }\n else {\n x = stack.pop();\n queue.enqueue(x.key);\n x = x.right;\n }\n }\n return queue;\n }\n\n\n /***************************************************************************\n * Test client.\n ***************************************************************************/\n public static void main(String[] args) {\n String[] a = StdIn.readAllStrings();\n int n = a.length;\n NonrecursiveBST st = new NonrecursiveBST();\n for (int i = 0; i < n; i++)\n st.put(a[i], i);\n for (String s : st.keys())\n StdOut.println(s + \" \" + st.get(s));\n }\n\n}\n", "support_files": ["https://algs4.cs.princeton.edu/32bst/tinyST.txt"], "metadata": {"number": "3.2.13", "code_execution": true, "url": "https://algs4.cs.princeton.edu/32bst/NonrecursiveBST.java", "params": ["< tinyST.txt"], "dependencies": ["StdOut.java", "StdIn.java"]}} {"question": "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.", "answer": "/******************************************************************************\n * Compilation: javac PerfectBalance.java\n * Execution: java PerfectBalance < input.txt\n * Dependencies: StdOut.java\n *\n * Read sequence of strings from standard input (no duplicates),\n * and insert into a BST so that BST is perfectly balanced.\n *\n * % java PerfectBalance\n * P E R F C T B I N A R Y S R H\n * N E B A C H F I R R P R T S Y\n *\n ******************************************************************************/\n\nimport java.util.Arrays;\n\npublic class PerfectBalance {\n\n // precondition: a[] has no duplicates\n private static void perfect(BST bst, String[] a) {\n Arrays.sort(a);\n perfect(bst, a, 0, a.length - 1);\n StdOut.println();\n }\n\n // precondition: a[lo..hi] is sorted\n private static void perfect(BST bst, String[] a, int lo, int hi) {\n if (hi < lo) return;\n int mid = lo + (hi - lo) / 2;\n bst.put(a[mid], mid);\n StdOut.print(a[mid] + \" \");\n perfect(bst, a, lo, mid-1);\n perfect(bst, a, mid+1, hi);\n }\n\n public static void main(String[] args) {\n String[] words = StdIn.readAllStrings();\n BST bst = new BST();\n perfect(bst, words);\n }\n}\n", "support_files": [], "metadata": {"number": "3.2.25", "code_execution": true, "url": "https://algs4.cs.princeton.edu/32bst/PerfectBalance.java", "params": ["<put, get, contains,\n * delete, size, and is-empty methods.\n * It also provides ordered methods for finding the minimum,\n * maximum, floor, select, ceiling.\n * It also provides a keys method for iterating over all of the keys.\n * A symbol table implements the associative array abstraction:\n * when associating a value with a key that is already in the symbol table,\n * the convention is to replace the old value with the new value.\n * Unlike {@link java.util.Map}, this class uses the convention that\n * values cannot be {@code null}—setting the\n * value associated with a key to {@code null} is equivalent to deleting the key\n * from the symbol table.\n *

\n * It requires that\n * the key type implements the {@code Comparable} interface and calls the\n * {@code compareTo()} and method to compare two keys. It does not call either\n * {@code equals()} or {@code hashCode()}.\n *

\n * This implementation uses an (unbalanced) binary search tree.\n * The put, contains, remove, minimum,\n * maximum, ceiling, floor, select, and\n * rank operations each take Θ(n) time in the worst\n * case, where n is the number of key-value pairs.\n * The size and is-empty operations take Θ(1) time.\n * The keys method takes Θ(n) time in the worst case.\n * Construction takes Θ(1) time.\n *

\n * For alternative implementations of the symbol table API, see {@link ST},\n * {@link BinarySearchST}, {@link SequentialSearchST}, {@link RedBlackBST},\n * {@link SeparateChainingHashST}, and {@link LinearProbingHashST},\n * For additional documentation, see\n * Section 3.2 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class BST, Value> {\n private Node root; // root of BST\n\n private class Node {\n private Key key; // sorted by key\n private Value val; // associated data\n private Node left, right; // left and right subtrees\n private int size; // number of nodes in subtree\n\n public Node(Key key, Value val, int size) {\n this.key = key;\n this.val = val;\n this.size = size;\n }\n }\n\n /**\n * Initializes an empty symbol table.\n */\n public BST() {\n }\n\n /**\n * Returns true if this symbol table is empty.\n * @return {@code true} if this symbol table is empty; {@code false} otherwise\n */\n public boolean isEmpty() {\n return size() == 0;\n }\n\n /**\n * Returns the number of key-value pairs in this symbol table.\n * @return the number of key-value pairs in this symbol table\n */\n public int size() {\n return size(root);\n }\n\n // return number of key-value pairs in BST rooted at x\n private int size(Node node) {\n if (node == null) return 0;\n else return node.size;\n }\n\n /**\n * Does this symbol table contain the given key?\n *\n * @param key the key\n * @return {@code true} if this symbol table contains {@code key} and\n * {@code false} otherwise\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public boolean contains(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to contains() is null\");\n return get(key) != null;\n }\n\n /**\n * Returns the value associated with the given key.\n *\n * @param key the key\n * @return the value associated with the given key if the key is in the symbol table\n * and {@code null} if the key is not in the symbol table\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Value get(Key key) {\n return get(root, key);\n }\n\n private Value get(Node node, Key key) {\n if (key == null) throw new IllegalArgumentException(\"calls get() with a null key\");\n if (node == null) return null;\n int cmp = key.compareTo(node.key);\n if (cmp < 0) return get(node.left, key);\n else if (cmp > 0) return get(node.right, key);\n else return node.val;\n }\n\n /**\n * Inserts the specified key-value pair into the symbol table, overwriting the old\n * value with the new value if the symbol table already contains the specified key.\n * Deletes the specified key (and its associated value) from this symbol table\n * if the specified value is {@code null}.\n *\n * @param key the key\n * @param val the value\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public void put(Key key, Value val) {\n if (key == null) throw new IllegalArgumentException(\"calls put() with a null key\");\n if (val == null) {\n delete(key);\n return;\n }\n root = put(root, key, val);\n assert check();\n }\n\n private Node put(Node node, Key key, Value val) {\n if (node == null) return new Node(key, val, 1);\n int cmp = key.compareTo(node.key);\n if (cmp < 0) node.left = put(node.left, key, val);\n else if (cmp > 0) node.right = put(node.right, key, val);\n else node.val = val;\n node.size = 1 + size(node.left) + size(node.right);\n return node;\n }\n\n\n /**\n * Removes the smallest key and associated value from the symbol table.\n *\n * @throws NoSuchElementException if the symbol table is empty\n */\n public void deleteMin() {\n if (isEmpty()) throw new NoSuchElementException(\"Symbol table underflow\");\n root = deleteMin(root);\n assert check();\n }\n\n private Node deleteMin(Node node) {\n if (node.left == null) return node.right;\n node.left = deleteMin(node.left);\n node.size = size(node.left) + size(node.right) + 1;\n return node;\n }\n\n /**\n * Removes the largest key and associated value from the symbol table.\n *\n * @throws NoSuchElementException if the symbol table is empty\n */\n public void deleteMax() {\n if (isEmpty()) throw new NoSuchElementException(\"Symbol table underflow\");\n root = deleteMax(root);\n assert check();\n }\n\n private Node deleteMax(Node node) {\n if (node.right == null) return node.left;\n node.right = deleteMax(node.right);\n node.size = size(node.left) + size(node.right) + 1;\n return node;\n }\n\n /**\n * Removes the specified key and its associated value from this symbol table\n * (if the key is in this symbol table).\n *\n * @param key the key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public void delete(Key key) {\n if (key == null) throw new IllegalArgumentException(\"calls delete() with a null key\");\n root = delete(root, key);\n assert check();\n }\n\n private Node delete(Node node, Key key) {\n if (node == null) return null;\n\n int cmp = key.compareTo(node.key);\n if (cmp < 0) node.left = delete(node.left, key);\n else if (cmp > 0) node.right = delete(node.right, key);\n else {\n if (node.right == null) return node.left;\n if (node.left == null) return node.right;\n Node temp = node;\n node = min(temp.right);\n node.right = deleteMin(temp.right);\n node.left = temp.left;\n }\n node.size = size(node.left) + size(node.right) + 1;\n return node;\n }\n\n\n /**\n * Returns the smallest key in the symbol table.\n *\n * @return the smallest key in the symbol table\n * @throws NoSuchElementException if the symbol table is empty\n */\n public Key min() {\n if (isEmpty()) throw new NoSuchElementException(\"calls min() with empty symbol table\");\n return min(root).key;\n }\n\n private Node min(Node node) {\n if (node.left == null) return node;\n else return min(node.left);\n }\n\n /**\n * Returns the largest key in the symbol table.\n *\n * @return the largest key in the symbol table\n * @throws NoSuchElementException if the symbol table is empty\n */\n public Key max() {\n if (isEmpty()) throw new NoSuchElementException(\"calls max() with empty symbol table\");\n return max(root).key;\n }\n\n private Node max(Node node) {\n if (node.right == null) return node;\n else return max(node.right);\n }\n\n /**\n * Returns the largest key in the symbol table less than or equal to {@code key}.\n *\n * @param key the key\n * @return the largest key in the symbol table less than or equal to {@code key}\n * @throws NoSuchElementException if there is no such key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Key floor(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to floor() is null\");\n if (isEmpty()) throw new NoSuchElementException(\"calls floor() with empty symbol table\");\n Node node = floor(root, key);\n if (node == null) throw new NoSuchElementException(\"argument to floor() is too small\");\n else return node.key;\n }\n\n private Node floor(Node node, Key key) {\n if (node == null) return null;\n int cmp = key.compareTo(node.key);\n if (cmp == 0) return node;\n if (cmp < 0) return floor(node.left, key);\n Node t = floor(node.right, key);\n if (t != null) return t;\n else return node;\n }\n\n public Key floor2(Key key) {\n Key floor = floor2(root, key, null);\n if (floor == null) throw new NoSuchElementException(\"argument to floor() is too small\");\n else return floor;\n\n }\n\n private Key floor2(Node node, Key key, Key champ) {\n if (node == null) return champ;\n int cmp = key.compareTo(node.key);\n if (cmp < 0) return floor2(node.left, key, champ);\n else if (cmp > 0) return floor2(node.right, key, node.key);\n else return node.key;\n }\n\n /**\n * Returns the smallest key in the symbol table greater than or equal to {@code key}.\n *\n * @param key the key\n * @return the smallest key in the symbol table greater than or equal to {@code key}\n * @throws NoSuchElementException if there is no such key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Key ceiling(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to ceiling() is null\");\n if (isEmpty()) throw new NoSuchElementException(\"calls ceiling() with empty symbol table\");\n Node node = ceiling(root, key);\n if (node == null) throw new NoSuchElementException(\"argument to ceiling() is too large\");\n else return node.key;\n }\n\n private Node ceiling(Node node, Key key) {\n if (node == null) return null;\n int cmp = key.compareTo(node.key);\n if (cmp == 0) return node;\n if (cmp < 0) {\n Node t = ceiling(node.left, key);\n if (t != null) return t;\n else return node;\n }\n return ceiling(node.right, key);\n }\n\n /**\n * Return the key in the symbol table of a given {@code rank}.\n * This key has the property that there are {@code rank} keys in\n * the symbol table that are smaller. In other words, this key is the\n * ({@code rank}+1)st smallest key in the symbol table.\n *\n * @param rank the order statistic\n * @return the key in the symbol table of given {@code rank}\n * @throws IllegalArgumentException unless {@code rank} is between 0 and\n * n–1\n */\n public Key select(int rank) {\n if (rank < 0 || rank >= size()) {\n throw new IllegalArgumentException(\"argument to select() is invalid: \" + rank);\n }\n return select(root, rank);\n }\n\n // Return key in BST rooted at x of given rank.\n // Precondition: rank is in legal range.\n private Key select(Node node, int rank) {\n if (node == null) return null;\n int leftSize = size(node.left);\n if (leftSize > rank) return select(node.left, rank);\n else if (leftSize < rank) return select(node.right, rank - leftSize - 1);\n else return node.key;\n }\n\n /**\n * Return the number of keys in the symbol table strictly less than {@code key}.\n *\n * @param key the key\n * @return the number of keys in the symbol table strictly less than {@code key}\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public int rank(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to rank() is null\");\n return rank(key, root);\n }\n\n // Number of keys in the subtree less than key.\n private int rank(Key key, Node node) {\n if (node == null) return 0;\n int cmp = key.compareTo(node.key);\n if (cmp < 0) return rank(key, node.left);\n else if (cmp > 0) return 1 + size(node.left) + rank(key, node.right);\n else return size(node.left);\n }\n\n /**\n * Returns all keys in the symbol table in ascending order,\n * as an {@code Iterable}.\n * To iterate over all of the keys in the symbol table named {@code st},\n * use the foreach notation: {@code for (Key key : st.keys())}.\n *\n * @return all keys in the symbol table in ascending order\n */\n public Iterable keys() {\n if (isEmpty()) return new Queue();\n return keys(min(), max());\n }\n\n /**\n * Returns all keys in the symbol table in the given range\n * in ascending order, as an {@code Iterable}.\n *\n * @param lo minimum endpoint\n * @param hi maximum endpoint\n * @return all keys in the symbol table between {@code lo}\n * (inclusive) and {@code hi} (inclusive) in ascending order\n * @throws IllegalArgumentException if either {@code lo} or {@code hi}\n * is {@code null}\n */\n public Iterable keys(Key lo, Key hi) {\n if (lo == null) throw new IllegalArgumentException(\"first argument to keys() is null\");\n if (hi == null) throw new IllegalArgumentException(\"second argument to keys() is null\");\n\n Queue queue = new Queue();\n keys(root, queue, lo, hi);\n return queue;\n }\n\n private void keys(Node node, Queue queue, Key lo, Key hi) {\n if (node == null) return;\n int cmplo = lo.compareTo(node.key);\n int cmphi = hi.compareTo(node.key);\n if (cmplo < 0) keys(node.left, queue, lo, hi);\n if (cmplo <= 0 && cmphi >= 0) queue.enqueue(node.key);\n if (cmphi > 0) keys(node.right, queue, lo, hi);\n }\n\n /**\n * Returns the number of keys in the symbol table in the given range.\n *\n * @param lo minimum endpoint\n * @param hi maximum endpoint\n * @return the number of keys in the symbol table between {@code lo}\n * (inclusive) and {@code hi} (inclusive)\n * @throws IllegalArgumentException if either {@code lo} or {@code hi}\n * is {@code null}\n */\n public int size(Key lo, Key hi) {\n if (lo == null) throw new IllegalArgumentException(\"first argument to size() is null\");\n if (hi == null) throw new IllegalArgumentException(\"second argument to size() is null\");\n\n if (lo.compareTo(hi) > 0) return 0;\n if (contains(hi)) return rank(hi) - rank(lo) + 1;\n else return rank(hi) - rank(lo);\n }\n\n /**\n * Returns the height of the BST (for debugging).\n *\n * @return the height of the BST (a 1-node tree has height 0)\n */\n public int height() {\n return height(root);\n }\n private int height(Node node) {\n if (node == null) return -1;\n return 1 + Math.max(height(node.left), height(node.right));\n }\n\n /**\n * Returns the keys in the BST in level order (for debugging).\n *\n * @return the keys in the BST in level order traversal\n */\n public Iterable levelOrder() {\n Queue keys = new Queue();\n Queue queue = new Queue();\n queue.enqueue(root);\n while (!queue.isEmpty()) {\n Node node = queue.dequeue();\n if (node == null) continue;\n keys.enqueue(node.key);\n queue.enqueue(node.left);\n queue.enqueue(node.right);\n }\n return keys;\n }\n\n /*************************************************************************\n * Check integrity of BST data structure.\n ***************************************************************************/\n private boolean check() {\n if (!isBST()) StdOut.println(\"Not in symmetric order\");\n if (!isSizeConsistent()) StdOut.println(\"Subtree counts not consistent\");\n if (!isRankConsistent()) StdOut.println(\"Ranks not consistent\");\n return isBST() && isSizeConsistent() && isRankConsistent();\n }\n\n // does this binary tree satisfy symmetric order?\n // Note: this test also ensures that data structure is a binary tree since order is strict\n private boolean isBST() {\n return isBST(root, null, null);\n }\n\n // is the tree rooted at x a BST with all keys strictly between min and max\n // (if min or max is null, treat as empty constraint)\n // Credit: elegant solution due to Bob Dondero\n private boolean isBST(Node node, Key min, Key max) {\n if (node == null) return true;\n if (min != null && node.key.compareTo(min) <= 0) return false;\n if (max != null && node.key.compareTo(max) >= 0) return false;\n return isBST(node.left, min, node.key) && isBST(node.right, node.key, max);\n }\n\n // are the size fields correct?\n private boolean isSizeConsistent() { return isSizeConsistent(root); }\n private boolean isSizeConsistent(Node node) {\n if (node == null) return true;\n if (node.size != size(node.left) + size(node.right) + 1) return false;\n return isSizeConsistent(node.left) && isSizeConsistent(node.right);\n }\n\n // check that ranks are consistent\n private boolean isRankConsistent() {\n for (int i = 0; i < size(); i++)\n if (i != rank(select(i))) return false;\n for (Key key : keys())\n if (key.compareTo(select(rank(key))) != 0) return false;\n return true;\n }\n\n\n /**\n * Unit tests the {@code BST} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n BST st = new BST();\n for (int i = 0; !StdIn.isEmpty(); i++) {\n String key = StdIn.readString();\n st.put(key, i);\n }\n\n for (String s : st.levelOrder())\n StdOut.println(s + \" \" + st.get(s));\n\n StdOut.println();\n\n for (String s : st.keys())\n StdOut.println(s + \" \" + st.get(s));\n }\n}\n", "support_files": ["https://algs4.cs.princeton.edu/32bst/tinyST.txt"], "metadata": {"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"]}} {"question": "Select/rank check. Write a method isRankConsistent() in BST.java that checks, for all i from 0 to size() - 1 ,\nwhether i is equal to rank(select(i)) and, for all keys\nin the BST, whether key is equal to select(rank(key)) .", "answer": "/******************************************************************************\n * Compilation: javac BST.java\n * Execution: java BST\n * Dependencies: StdIn.java StdOut.java Queue.java\n * Data files: https://algs4.cs.princeton.edu/32bst/tinyST.txt\n *\n * A symbol table implemented with a binary search tree.\n *\n * % more tinyST.txt\n * S E A R C H E X A M P L E\n *\n * % java BST < tinyST.txt\n * A 8\n * C 4\n * E 12\n * H 5\n * L 11\n * M 9\n * P 10\n * R 3\n * S 0\n * X 7\n *\n ******************************************************************************/\n\nimport java.util.NoSuchElementException;\n\n/**\n * The {@code BST} class represents an ordered symbol table of generic\n * key-value pairs.\n * It supports the usual put, get, contains,\n * delete, size, and is-empty methods.\n * It also provides ordered methods for finding the minimum,\n * maximum, floor, select, ceiling.\n * It also provides a keys method for iterating over all of the keys.\n * A symbol table implements the associative array abstraction:\n * when associating a value with a key that is already in the symbol table,\n * the convention is to replace the old value with the new value.\n * Unlike {@link java.util.Map}, this class uses the convention that\n * values cannot be {@code null}—setting the\n * value associated with a key to {@code null} is equivalent to deleting the key\n * from the symbol table.\n *

\n * It requires that\n * the key type implements the {@code Comparable} interface and calls the\n * {@code compareTo()} and method to compare two keys. It does not call either\n * {@code equals()} or {@code hashCode()}.\n *

\n * This implementation uses an (unbalanced) binary search tree.\n * The put, contains, remove, minimum,\n * maximum, ceiling, floor, select, and\n * rank operations each take Θ(n) time in the worst\n * case, where n is the number of key-value pairs.\n * The size and is-empty operations take Θ(1) time.\n * The keys method takes Θ(n) time in the worst case.\n * Construction takes Θ(1) time.\n *

\n * For alternative implementations of the symbol table API, see {@link ST},\n * {@link BinarySearchST}, {@link SequentialSearchST}, {@link RedBlackBST},\n * {@link SeparateChainingHashST}, and {@link LinearProbingHashST},\n * For additional documentation, see\n * Section 3.2 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class BST, Value> {\n private Node root; // root of BST\n\n private class Node {\n private Key key; // sorted by key\n private Value val; // associated data\n private Node left, right; // left and right subtrees\n private int size; // number of nodes in subtree\n\n public Node(Key key, Value val, int size) {\n this.key = key;\n this.val = val;\n this.size = size;\n }\n }\n\n /**\n * Initializes an empty symbol table.\n */\n public BST() {\n }\n\n /**\n * Returns true if this symbol table is empty.\n * @return {@code true} if this symbol table is empty; {@code false} otherwise\n */\n public boolean isEmpty() {\n return size() == 0;\n }\n\n /**\n * Returns the number of key-value pairs in this symbol table.\n * @return the number of key-value pairs in this symbol table\n */\n public int size() {\n return size(root);\n }\n\n // return number of key-value pairs in BST rooted at x\n private int size(Node node) {\n if (node == null) return 0;\n else return node.size;\n }\n\n /**\n * Does this symbol table contain the given key?\n *\n * @param key the key\n * @return {@code true} if this symbol table contains {@code key} and\n * {@code false} otherwise\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public boolean contains(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to contains() is null\");\n return get(key) != null;\n }\n\n /**\n * Returns the value associated with the given key.\n *\n * @param key the key\n * @return the value associated with the given key if the key is in the symbol table\n * and {@code null} if the key is not in the symbol table\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Value get(Key key) {\n return get(root, key);\n }\n\n private Value get(Node node, Key key) {\n if (key == null) throw new IllegalArgumentException(\"calls get() with a null key\");\n if (node == null) return null;\n int cmp = key.compareTo(node.key);\n if (cmp < 0) return get(node.left, key);\n else if (cmp > 0) return get(node.right, key);\n else return node.val;\n }\n\n /**\n * Inserts the specified key-value pair into the symbol table, overwriting the old\n * value with the new value if the symbol table already contains the specified key.\n * Deletes the specified key (and its associated value) from this symbol table\n * if the specified value is {@code null}.\n *\n * @param key the key\n * @param val the value\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public void put(Key key, Value val) {\n if (key == null) throw new IllegalArgumentException(\"calls put() with a null key\");\n if (val == null) {\n delete(key);\n return;\n }\n root = put(root, key, val);\n assert check();\n }\n\n private Node put(Node node, Key key, Value val) {\n if (node == null) return new Node(key, val, 1);\n int cmp = key.compareTo(node.key);\n if (cmp < 0) node.left = put(node.left, key, val);\n else if (cmp > 0) node.right = put(node.right, key, val);\n else node.val = val;\n node.size = 1 + size(node.left) + size(node.right);\n return node;\n }\n\n\n /**\n * Removes the smallest key and associated value from the symbol table.\n *\n * @throws NoSuchElementException if the symbol table is empty\n */\n public void deleteMin() {\n if (isEmpty()) throw new NoSuchElementException(\"Symbol table underflow\");\n root = deleteMin(root);\n assert check();\n }\n\n private Node deleteMin(Node node) {\n if (node.left == null) return node.right;\n node.left = deleteMin(node.left);\n node.size = size(node.left) + size(node.right) + 1;\n return node;\n }\n\n /**\n * Removes the largest key and associated value from the symbol table.\n *\n * @throws NoSuchElementException if the symbol table is empty\n */\n public void deleteMax() {\n if (isEmpty()) throw new NoSuchElementException(\"Symbol table underflow\");\n root = deleteMax(root);\n assert check();\n }\n\n private Node deleteMax(Node node) {\n if (node.right == null) return node.left;\n node.right = deleteMax(node.right);\n node.size = size(node.left) + size(node.right) + 1;\n return node;\n }\n\n /**\n * Removes the specified key and its associated value from this symbol table\n * (if the key is in this symbol table).\n *\n * @param key the key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public void delete(Key key) {\n if (key == null) throw new IllegalArgumentException(\"calls delete() with a null key\");\n root = delete(root, key);\n assert check();\n }\n\n private Node delete(Node node, Key key) {\n if (node == null) return null;\n\n int cmp = key.compareTo(node.key);\n if (cmp < 0) node.left = delete(node.left, key);\n else if (cmp > 0) node.right = delete(node.right, key);\n else {\n if (node.right == null) return node.left;\n if (node.left == null) return node.right;\n Node temp = node;\n node = min(temp.right);\n node.right = deleteMin(temp.right);\n node.left = temp.left;\n }\n node.size = size(node.left) + size(node.right) + 1;\n return node;\n }\n\n\n /**\n * Returns the smallest key in the symbol table.\n *\n * @return the smallest key in the symbol table\n * @throws NoSuchElementException if the symbol table is empty\n */\n public Key min() {\n if (isEmpty()) throw new NoSuchElementException(\"calls min() with empty symbol table\");\n return min(root).key;\n }\n\n private Node min(Node node) {\n if (node.left == null) return node;\n else return min(node.left);\n }\n\n /**\n * Returns the largest key in the symbol table.\n *\n * @return the largest key in the symbol table\n * @throws NoSuchElementException if the symbol table is empty\n */\n public Key max() {\n if (isEmpty()) throw new NoSuchElementException(\"calls max() with empty symbol table\");\n return max(root).key;\n }\n\n private Node max(Node node) {\n if (node.right == null) return node;\n else return max(node.right);\n }\n\n /**\n * Returns the largest key in the symbol table less than or equal to {@code key}.\n *\n * @param key the key\n * @return the largest key in the symbol table less than or equal to {@code key}\n * @throws NoSuchElementException if there is no such key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Key floor(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to floor() is null\");\n if (isEmpty()) throw new NoSuchElementException(\"calls floor() with empty symbol table\");\n Node node = floor(root, key);\n if (node == null) throw new NoSuchElementException(\"argument to floor() is too small\");\n else return node.key;\n }\n\n private Node floor(Node node, Key key) {\n if (node == null) return null;\n int cmp = key.compareTo(node.key);\n if (cmp == 0) return node;\n if (cmp < 0) return floor(node.left, key);\n Node t = floor(node.right, key);\n if (t != null) return t;\n else return node;\n }\n\n public Key floor2(Key key) {\n Key floor = floor2(root, key, null);\n if (floor == null) throw new NoSuchElementException(\"argument to floor() is too small\");\n else return floor;\n\n }\n\n private Key floor2(Node node, Key key, Key champ) {\n if (node == null) return champ;\n int cmp = key.compareTo(node.key);\n if (cmp < 0) return floor2(node.left, key, champ);\n else if (cmp > 0) return floor2(node.right, key, node.key);\n else return node.key;\n }\n\n /**\n * Returns the smallest key in the symbol table greater than or equal to {@code key}.\n *\n * @param key the key\n * @return the smallest key in the symbol table greater than or equal to {@code key}\n * @throws NoSuchElementException if there is no such key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Key ceiling(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to ceiling() is null\");\n if (isEmpty()) throw new NoSuchElementException(\"calls ceiling() with empty symbol table\");\n Node node = ceiling(root, key);\n if (node == null) throw new NoSuchElementException(\"argument to ceiling() is too large\");\n else return node.key;\n }\n\n private Node ceiling(Node node, Key key) {\n if (node == null) return null;\n int cmp = key.compareTo(node.key);\n if (cmp == 0) return node;\n if (cmp < 0) {\n Node t = ceiling(node.left, key);\n if (t != null) return t;\n else return node;\n }\n return ceiling(node.right, key);\n }\n\n /**\n * Return the key in the symbol table of a given {@code rank}.\n * This key has the property that there are {@code rank} keys in\n * the symbol table that are smaller. In other words, this key is the\n * ({@code rank}+1)st smallest key in the symbol table.\n *\n * @param rank the order statistic\n * @return the key in the symbol table of given {@code rank}\n * @throws IllegalArgumentException unless {@code rank} is between 0 and\n * n–1\n */\n public Key select(int rank) {\n if (rank < 0 || rank >= size()) {\n throw new IllegalArgumentException(\"argument to select() is invalid: \" + rank);\n }\n return select(root, rank);\n }\n\n // Return key in BST rooted at x of given rank.\n // Precondition: rank is in legal range.\n private Key select(Node node, int rank) {\n if (node == null) return null;\n int leftSize = size(node.left);\n if (leftSize > rank) return select(node.left, rank);\n else if (leftSize < rank) return select(node.right, rank - leftSize - 1);\n else return node.key;\n }\n\n /**\n * Return the number of keys in the symbol table strictly less than {@code key}.\n *\n * @param key the key\n * @return the number of keys in the symbol table strictly less than {@code key}\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public int rank(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to rank() is null\");\n return rank(key, root);\n }\n\n // Number of keys in the subtree less than key.\n private int rank(Key key, Node node) {\n if (node == null) return 0;\n int cmp = key.compareTo(node.key);\n if (cmp < 0) return rank(key, node.left);\n else if (cmp > 0) return 1 + size(node.left) + rank(key, node.right);\n else return size(node.left);\n }\n\n /**\n * Returns all keys in the symbol table in ascending order,\n * as an {@code Iterable}.\n * To iterate over all of the keys in the symbol table named {@code st},\n * use the foreach notation: {@code for (Key key : st.keys())}.\n *\n * @return all keys in the symbol table in ascending order\n */\n public Iterable keys() {\n if (isEmpty()) return new Queue();\n return keys(min(), max());\n }\n\n /**\n * Returns all keys in the symbol table in the given range\n * in ascending order, as an {@code Iterable}.\n *\n * @param lo minimum endpoint\n * @param hi maximum endpoint\n * @return all keys in the symbol table between {@code lo}\n * (inclusive) and {@code hi} (inclusive) in ascending order\n * @throws IllegalArgumentException if either {@code lo} or {@code hi}\n * is {@code null}\n */\n public Iterable keys(Key lo, Key hi) {\n if (lo == null) throw new IllegalArgumentException(\"first argument to keys() is null\");\n if (hi == null) throw new IllegalArgumentException(\"second argument to keys() is null\");\n\n Queue queue = new Queue();\n keys(root, queue, lo, hi);\n return queue;\n }\n\n private void keys(Node node, Queue queue, Key lo, Key hi) {\n if (node == null) return;\n int cmplo = lo.compareTo(node.key);\n int cmphi = hi.compareTo(node.key);\n if (cmplo < 0) keys(node.left, queue, lo, hi);\n if (cmplo <= 0 && cmphi >= 0) queue.enqueue(node.key);\n if (cmphi > 0) keys(node.right, queue, lo, hi);\n }\n\n /**\n * Returns the number of keys in the symbol table in the given range.\n *\n * @param lo minimum endpoint\n * @param hi maximum endpoint\n * @return the number of keys in the symbol table between {@code lo}\n * (inclusive) and {@code hi} (inclusive)\n * @throws IllegalArgumentException if either {@code lo} or {@code hi}\n * is {@code null}\n */\n public int size(Key lo, Key hi) {\n if (lo == null) throw new IllegalArgumentException(\"first argument to size() is null\");\n if (hi == null) throw new IllegalArgumentException(\"second argument to size() is null\");\n\n if (lo.compareTo(hi) > 0) return 0;\n if (contains(hi)) return rank(hi) - rank(lo) + 1;\n else return rank(hi) - rank(lo);\n }\n\n /**\n * Returns the height of the BST (for debugging).\n *\n * @return the height of the BST (a 1-node tree has height 0)\n */\n public int height() {\n return height(root);\n }\n private int height(Node node) {\n if (node == null) return -1;\n return 1 + Math.max(height(node.left), height(node.right));\n }\n\n /**\n * Returns the keys in the BST in level order (for debugging).\n *\n * @return the keys in the BST in level order traversal\n */\n public Iterable levelOrder() {\n Queue keys = new Queue();\n Queue queue = new Queue();\n queue.enqueue(root);\n while (!queue.isEmpty()) {\n Node node = queue.dequeue();\n if (node == null) continue;\n keys.enqueue(node.key);\n queue.enqueue(node.left);\n queue.enqueue(node.right);\n }\n return keys;\n }\n\n /*************************************************************************\n * Check integrity of BST data structure.\n ***************************************************************************/\n private boolean check() {\n if (!isBST()) StdOut.println(\"Not in symmetric order\");\n if (!isSizeConsistent()) StdOut.println(\"Subtree counts not consistent\");\n if (!isRankConsistent()) StdOut.println(\"Ranks not consistent\");\n return isBST() && isSizeConsistent() && isRankConsistent();\n }\n\n // does this binary tree satisfy symmetric order?\n // Note: this test also ensures that data structure is a binary tree since order is strict\n private boolean isBST() {\n return isBST(root, null, null);\n }\n\n // is the tree rooted at x a BST with all keys strictly between min and max\n // (if min or max is null, treat as empty constraint)\n // Credit: elegant solution due to Bob Dondero\n private boolean isBST(Node node, Key min, Key max) {\n if (node == null) return true;\n if (min != null && node.key.compareTo(min) <= 0) return false;\n if (max != null && node.key.compareTo(max) >= 0) return false;\n return isBST(node.left, min, node.key) && isBST(node.right, node.key, max);\n }\n\n // are the size fields correct?\n private boolean isSizeConsistent() { return isSizeConsistent(root); }\n private boolean isSizeConsistent(Node node) {\n if (node == null) return true;\n if (node.size != size(node.left) + size(node.right) + 1) return false;\n return isSizeConsistent(node.left) && isSizeConsistent(node.right);\n }\n\n // check that ranks are consistent\n private boolean isRankConsistent() {\n for (int i = 0; i < size(); i++)\n if (i != rank(select(i))) return false;\n for (Key key : keys())\n if (key.compareTo(select(rank(key))) != 0) return false;\n return true;\n }\n\n\n /**\n * Unit tests the {@code BST} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n BST st = new BST();\n for (int i = 0; !StdIn.isEmpty(); i++) {\n String key = StdIn.readString();\n st.put(key, i);\n }\n\n for (String s : st.levelOrder())\n StdOut.println(s + \" \" + st.get(s));\n\n StdOut.println();\n\n for (String s : st.keys())\n StdOut.println(s + \" \" + st.get(s));\n }\n}\n", "support_files": ["https://algs4.cs.princeton.edu/32bst/tinyST.txt"], "metadata": {"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"]}} {"question": "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. ", "answer": "/******************************************************************************\n * Compilation: javac Graph.java\n * Execution: java Graph input.txt\n * Dependencies: Bag.java Stack.java In.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/41graph/tinyG.txt\n * https://algs4.cs.princeton.edu/41graph/mediumG.txt\n * https://algs4.cs.princeton.edu/41graph/largeG.txt\n *\n * A graph, implemented using an array of sets.\n * Parallel edges and self-loops allowed.\n *\n * % java Graph tinyG.txt\n * 13 vertices, 13 edges\n * 0: 6 2 1 5\n * 1: 0\n * 2: 0\n * 3: 5 4\n * 4: 5 6 3\n * 5: 3 4 0\n * 6: 0 4\n * 7: 8\n * 8: 7\n * 9: 11 10 12\n * 10: 9\n * 11: 9 12\n * 12: 11 9\n *\n * % java Graph mediumG.txt\n * 250 vertices, 1273 edges\n * 0: 225 222 211 209 204 202 191 176 163 160 149 114 97 80 68 59 58 49 44 24 15\n * 1: 220 203 200 194 189 164 150 130 107 72\n * 2: 141 110 108 86 79 51 42 18 14\n * ...\n *\n ******************************************************************************/\n\nimport java.util.NoSuchElementException;\n\n/**\n * The {@code Graph} class represents an undirected graph of vertices\n * named 0 through V – 1.\n * It supports the following two primary operations: add an edge to the graph,\n * iterate over all of the vertices adjacent with a given vertex. It also provides\n * methods for returning the degree of a vertex, the number of vertices\n * V in the graph, and the number of edges E in the graph.\n * Parallel edges and self-loops are permitted.\n * By convention, a self-loop v-v appears in the\n * adjacency list of v twice and contributes two to the degree\n * of v.\n *

\n * This implementation uses an adjacency-lists representation, which\n * is a vertex-indexed array of {@link Bag} objects.\n * It uses Θ(E + V) space, where E is\n * the number of edges and V is the number of vertices.\n * All instance methods take Θ(1) time. (Though, iterating over\n * the vertices returned by {@link #adj(int)} takes time proportional\n * to the degree of the vertex.)\n * Constructing an empty graph with V vertices takes\n * Θ(V) time; constructing a graph with E edges\n * and V vertices takes Θ(E + V) time.\n *

\n * For additional documentation, see\n * Section 4.1\n * of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class Graph {\n private static final String NEWLINE = System.getProperty(\"line.separator\");\n\n private final int V;\n private int E;\n private Bag[] adj;\n\n /**\n * Initializes an empty graph with {@code V} vertices and 0 edges.\n * param V the number of vertices\n *\n * @param V number of vertices\n * @throws IllegalArgumentException if {@code V < 0}\n */\n public Graph(int V) {\n if (V < 0) throw new IllegalArgumentException(\"Number of vertices must be non-negative\");\n this.V = V;\n this.E = 0;\n adj = (Bag[]) new Bag[V];\n for (int v = 0; v < V; v++) {\n adj[v] = new Bag();\n }\n }\n\n /**\n * Initializes a graph from the specified input stream.\n * The format is the number of vertices V,\n * followed by the number of edges E,\n * followed by E pairs of vertices, with each entry separated by whitespace.\n *\n * @param in the input stream\n * @throws IllegalArgumentException if {@code in} is {@code null}\n * @throws IllegalArgumentException if the endpoints of any edge are not in prescribed range\n * @throws IllegalArgumentException if the number of vertices or edges is negative\n * @throws IllegalArgumentException if the input stream is in the wrong format\n */\n public Graph(In in) {\n if (in == null) throw new IllegalArgumentException(\"argument is null\");\n try {\n this.V = in.readInt();\n if (V < 0) throw new IllegalArgumentException(\"number of vertices in a Graph must be non-negative\");\n adj = (Bag[]) new Bag[V];\n for (int v = 0; v < V; v++) {\n adj[v] = new Bag();\n }\n int E = in.readInt();\n if (E < 0) throw new IllegalArgumentException(\"number of edges in a Graph must be non-negative\");\n for (int i = 0; i < E; i++) {\n int v = in.readInt();\n int w = in.readInt();\n validateVertex(v);\n validateVertex(w);\n addEdge(v, w);\n }\n }\n catch (NoSuchElementException e) {\n throw new IllegalArgumentException(\"invalid input format in Graph constructor\", e);\n }\n }\n\n\n /**\n * Initializes a new graph that is a deep copy of {@code graph}.\n *\n * @param graph the graph to copy\n * @throws IllegalArgumentException if {@code graph} is {@code null}\n */\n public Graph(Graph graph) {\n this.V = graph.V();\n this.E = graph.E();\n if (V < 0) throw new IllegalArgumentException(\"Number of vertices must be non-negative\");\n\n // update adjacency lists\n adj = (Bag[]) new Bag[V];\n for (int v = 0; v < V; v++) {\n adj[v] = new Bag();\n }\n\n for (int v = 0; v < graph.V(); v++) {\n // reverse so that adjacency list is in same order as original\n Stack reverse = new Stack();\n for (int w : graph.adj[v]) {\n reverse.push(w);\n }\n for (int w : reverse) {\n adj[v].add(w);\n }\n }\n }\n\n /**\n * Returns the number of vertices in this graph.\n *\n * @return the number of vertices in this graph\n */\n public int V() {\n return V;\n }\n\n /**\n * Returns the number of edges in this graph.\n *\n * @return the number of edges in this graph\n */\n public int E() {\n return E;\n }\n\n // throw an IllegalArgumentException unless {@code 0 <= v < V}\n private void validateVertex(int v) {\n if (v < 0 || v >= V)\n throw new IllegalArgumentException(\"vertex \" + v + \" is not between 0 and \" + (V-1));\n }\n\n /**\n * Adds the undirected edge v-w to this graph.\n *\n * @param v one vertex in the edge\n * @param w the other vertex in the edge\n * @throws IllegalArgumentException unless both {@code 0 <= v < V} and {@code 0 <= w < V}\n */\n public void addEdge(int v, int w) {\n validateVertex(v);\n validateVertex(w);\n E++;\n adj[v].add(w);\n adj[w].add(v);\n }\n\n\n /**\n * Returns the vertices adjacent with vertex {@code v}.\n *\n * @param v the vertex\n * @return the vertices adjacent with vertex {@code v}, as an iterable\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public Iterable adj(int v) {\n validateVertex(v);\n return adj[v];\n }\n\n /**\n * Returns the degree of vertex {@code v}.\n *\n * @param v the vertex\n * @return the degree of vertex {@code v}\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public int degree(int v) {\n validateVertex(v);\n return adj[v].size();\n }\n\n\n /**\n * Returns a string representation of this graph.\n *\n * @return the number of vertices V, followed by the number of edges E,\n * followed by the V adjacency lists\n */\n public String toString() {\n StringBuilder s = new StringBuilder();\n s.append(V + \" vertices, \" + E + \" edges \" + NEWLINE);\n for (int v = 0; v < V; v++) {\n s.append(v + \": \");\n for (int w : adj[v]) {\n s.append(w + \" \");\n }\n s.append(NEWLINE);\n }\n return s.toString();\n }\n\n /**\n * Returns a string representation of this graph in DOT format,\n * suitable for visualization with Graphviz.\n *\n * To visualize the graph, install Graphviz (e.g., \"brew install graphviz\").\n * Then use one of the graph visualization tools\n * - dot (hierarchical or layer drawing)\n * - neato (spring model)\n * - fdp (force-directed placement)\n * - sfdp (scalable force-directed placement)\n * - twopi (radial layout)\n *\n * For example, the following commands will create graph drawings in SVG\n * and PDF formats\n * - dot input.dot -Tsvg -o output.svg\n * - dot input.dot -Tpdf -o output.pdf\n *\n * To change the graph attributes (e.g., vertex and edge shapes, arrows, colors)\n * in the DOT format, see https://graphviz.org/doc/info/lang.html\n *\n * @return a string representation of this graph in DOT format\n */\n public String toDot() {\n StringBuilder s = new StringBuilder();\n s.append(\"graph {\" + NEWLINE);\n s.append(\"node[shape=circle, style=filled, fixedsize=true, width=0.3, fontsize=\\\"10pt\\\"]\" + NEWLINE);\n int selfLoops = 0;\n for (int v = 0; v < V; v++) {\n for (int w : adj[v]) {\n if (v < w) {\n s.append(v + \" -- \" + w + NEWLINE);\n }\n else if (v == w) {\n // include only one copy of each self loop (self loops will be consecutive)\n if (selfLoops % 2 == 0) {\n s.append(v + \" -- \" + w + NEWLINE);\n }\n selfLoops++;\n }\n }\n }\n s.append(\"}\" + NEWLINE);\n return s.toString();\n }\n\n /**\n * Unit tests the {@code Graph} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n In in = new In(args[0]);\n Graph graph = new Graph(in);\n StdOut.println(graph);\n }\n\n}\n", "support_files": ["https://algs4.cs.princeton.edu/41graph/mediumG.txt", "https://algs4.cs.princeton.edu/41graph/largeG.txt", "https://algs4.cs.princeton.edu/41graph/tinyG.txt"], "metadata": {"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"]}} {"question": "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.", "answer": "/******************************************************************************\n * Compilation: javac BreadthFirstPaths.java\n * Execution: java BreadthFirstPaths G s\n * Dependencies: Graph.java Queue.java Stack.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/41graph/tinyCG.txt\n * https://algs4.cs.princeton.edu/41graph/tinyG.txt\n * https://algs4.cs.princeton.edu/41graph/mediumG.txt\n * https://algs4.cs.princeton.edu/41graph/largeG.txt\n *\n * Run breadth first search on an undirected graph.\n * Runs in O(E + V) time.\n *\n * % java Graph tinyCG.txt\n * 6 8\n * 0: 2 1 5\n * 1: 0 2\n * 2: 0 1 3 4\n * 3: 5 4 2\n * 4: 3 2\n * 5: 3 0\n *\n * % java BreadthFirstPaths tinyCG.txt 0\n * 0 to 0 (0): 0\n * 0 to 1 (1): 0-1\n * 0 to 2 (1): 0-2\n * 0 to 3 (2): 0-2-3\n * 0 to 4 (2): 0-2-4\n * 0 to 5 (1): 0-5\n *\n * % java BreadthFirstPaths largeG.txt 0\n * 0 to 0 (0): 0\n * 0 to 1 (418): 0-932942-474885-82707-879889-971961-...\n * 0 to 2 (323): 0-460790-53370-594358-780059-287921-...\n * 0 to 3 (168): 0-713461-75230-953125-568284-350405-...\n * 0 to 4 (144): 0-460790-53370-310931-440226-380102-...\n * 0 to 5 (566): 0-932942-474885-82707-879889-971961-...\n * 0 to 6 (349): 0-932942-474885-82707-879889-971961-...\n *\n ******************************************************************************/\n\n\n/**\n * The {@code BreadthFirstPaths} class represents a data type for finding\n * shortest paths (number of edges) from a source vertex s\n * (or a set of source vertices)\n * to every other vertex in an undirected graph.\n *

\n * This implementation uses breadth-first search.\n * The constructor takes Θ(V + E) time in the\n * worst case, where V is the number of vertices and E\n * is the number of edges.\n * Each instance method takes Θ(1) time.\n * It uses Θ(V) extra space (not including the graph).\n *

\n * For additional documentation,\n * see Section 4.1\n * of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class BreadthFirstPaths {\n private static final int INFINITY = Integer.MAX_VALUE;\n private boolean[] marked; // marked[v] = is there an s-v path\n private int[] edgeTo; // edgeTo[v] = previous edge on shortest s-v path\n private int[] distTo; // distTo[v] = number of edges shortest s-v path\n\n /**\n * Computes the shortest path between the source vertex {@code s}\n * and every other vertex in the undirected graph {@code graph}.\n * @param graph the graph\n * @param s the source vertex\n * @throws IllegalArgumentException unless {@code 0 <= s < V}\n */\n public BreadthFirstPaths(Graph graph, int s) {\n marked = new boolean[graph.V()];\n distTo = new int[graph.V()];\n edgeTo = new int[graph.V()];\n validateVertex(s);\n bfs(graph, s);\n\n assert check(graph, s);\n }\n\n /**\n * Computes the shortest path between any one of the source vertices in {@code sources}\n * and every other vertex in {@code graph}.\n * @param graph the graph\n * @param sources the source vertices\n * @throws IllegalArgumentException if {@code sources} is {@code null}\n * @throws IllegalArgumentException if {@code sources} contains no vertices\n * @throws IllegalArgumentException unless {@code 0 <= s < V} for each vertex\n * {@code s} in {@code sources}\n */\n public BreadthFirstPaths(Graph graph, Iterable sources) {\n marked = new boolean[graph.V()];\n distTo = new int[graph.V()];\n edgeTo = new int[graph.V()];\n for (int v = 0; v < graph.V(); v++)\n distTo[v] = INFINITY;\n validateVertices(sources);\n bfs(graph, sources);\n }\n\n\n // breadth-first search from a single source\n private void bfs(Graph graph, int s) {\n Queue q = new Queue();\n for (int v = 0; v < graph.V(); v++)\n distTo[v] = INFINITY;\n distTo[s] = 0;\n marked[s] = true;\n q.enqueue(s);\n\n while (!q.isEmpty()) {\n int v = q.dequeue();\n for (int w : graph.adj(v)) {\n if (!marked[w]) {\n edgeTo[w] = v;\n distTo[w] = distTo[v] + 1;\n marked[w] = true;\n q.enqueue(w);\n }\n }\n }\n }\n\n // breadth-first search from multiple sources\n private void bfs(Graph graph, Iterable sources) {\n Queue q = new Queue();\n for (int s : sources) {\n marked[s] = true;\n distTo[s] = 0;\n q.enqueue(s);\n }\n while (!q.isEmpty()) {\n int v = q.dequeue();\n for (int w : graph.adj(v)) {\n if (!marked[w]) {\n edgeTo[w] = v;\n distTo[w] = distTo[v] + 1;\n marked[w] = true;\n q.enqueue(w);\n }\n }\n }\n }\n\n /**\n * Is there a path between the source vertex {@code s} (or sources) and vertex {@code v}?\n * @param v the vertex\n * @return {@code true} if there is a path, and {@code false} otherwise\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public boolean hasPathTo(int v) {\n validateVertex(v);\n return marked[v];\n }\n\n /**\n * Returns the number of edges in a shortest path between the source vertex {@code s}\n * (or sources) and vertex {@code v}?\n * @param v the vertex\n * @return the number of edges in such a shortest path\n * (or {@code Integer.MAX_VALUE} if there is no such path)\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public int distTo(int v) {\n validateVertex(v);\n return distTo[v];\n }\n\n /**\n * Returns a shortest path between the source vertex {@code s} (or sources)\n * and {@code v}, or {@code null} if no such path.\n * @param v the vertex\n * @return the sequence of vertices on a shortest path, as an Iterable\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public Iterable pathTo(int v) {\n validateVertex(v);\n if (!hasPathTo(v)) return null;\n Stack path = new Stack();\n int x;\n for (x = v; distTo[x] != 0; x = edgeTo[x])\n path.push(x);\n path.push(x);\n return path;\n }\n\n\n // check optimality conditions for single source\n private boolean check(Graph graph, int s) {\n\n // check that the distance of s = 0\n if (distTo[s] != 0) {\n StdOut.println(\"distance of source \" + s + \" to itself = \" + distTo[s]);\n return false;\n }\n\n // check that for each edge v-w dist[w] <= dist[v] + 1\n // provided v is reachable from s\n for (int v = 0; v < graph.V(); v++) {\n for (int w : graph.adj(v)) {\n if (hasPathTo(v) != hasPathTo(w)) {\n StdOut.println(\"edge \" + v + \"-\" + w);\n StdOut.println(\"hasPathTo(\" + v + \") = \" + hasPathTo(v));\n StdOut.println(\"hasPathTo(\" + w + \") = \" + hasPathTo(w));\n return false;\n }\n if (hasPathTo(v) && (distTo[w] > distTo[v] + 1)) {\n StdOut.println(\"edge \" + v + \"-\" + w);\n StdOut.println(\"distTo[\" + v + \"] = \" + distTo[v]);\n StdOut.println(\"distTo[\" + w + \"] = \" + distTo[w]);\n return false;\n }\n }\n }\n\n // check that v = edgeTo[w] satisfies distTo[w] = distTo[v] + 1\n // provided v is reachable from s\n for (int w = 0; w < graph.V(); w++) {\n if (!hasPathTo(w) || w == s) continue;\n int v = edgeTo[w];\n if (distTo[w] != distTo[v] + 1) {\n StdOut.println(\"shortest path edge \" + v + \"-\" + w);\n StdOut.println(\"distTo[\" + v + \"] = \" + distTo[v]);\n StdOut.println(\"distTo[\" + w + \"] = \" + distTo[w]);\n return false;\n }\n }\n\n return true;\n }\n\n // throw an IllegalArgumentException unless {@code 0 <= v < V}\n private void validateVertex(int v) {\n int V = marked.length;\n if (v < 0 || v >= V)\n throw new IllegalArgumentException(\"vertex \" + v + \" is not between 0 and \" + (V-1));\n }\n\n // throw an IllegalArgumentException if vertices is null, has zero vertices,\n // or has a vertex not between 0 and V-1\n private void validateVertices(Iterable vertices) {\n if (vertices == null) {\n throw new IllegalArgumentException(\"argument is null\");\n }\n int vertexCount = 0;\n for (Integer v : vertices) {\n vertexCount++;\n if (v == null) {\n throw new IllegalArgumentException(\"vertex is null\");\n }\n validateVertex(v);\n }\n if (vertexCount == 0) {\n throw new IllegalArgumentException(\"zero vertices\");\n }\n }\n\n /**\n * Unit tests the {@code BreadthFirstPaths} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n In in = new In(args[0]);\n Graph graph = new Graph(in);\n // StdOut.println(graph);\n\n int s = Integer.parseInt(args[1]);\n BreadthFirstPaths bfs = new BreadthFirstPaths(graph, s);\n\n for (int v = 0; v < graph.V(); v++) {\n if (bfs.hasPathTo(v)) {\n StdOut.printf(\"%d to %d (%d): \", s, v, bfs.distTo(v));\n for (int x : bfs.pathTo(v)) {\n if (x == s) StdOut.print(x);\n else StdOut.print(\"-\" + x);\n }\n StdOut.println();\n }\n\n else {\n StdOut.printf(\"%d to %d (-): not connected\", s, v);\n }\n\n }\n }\n\n\n}\n", "support_files": ["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"], "metadata": {"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"]}} {"question": "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).", "answer": "/******************************************************************************\n * Compilation: javac BaconHistogram.java\n * Execution: java BaconHistogram input.txt delimiter actor\n * Dependencies: SymbolGraph.java Graph.java In.java BreadthFirstPaths.java\n * Data files: https://algs4.cs.princeton.edu/41graph/movies.txt\n *\n * Reads in a data file containing movie records (a movie followed by a list\n * of actors appearing in that movie), and runs breadth first search to\n * find the shortest distance from the source (Kevin Bacon) to each other\n * actor and movie. After computing the Kevin Bacon numbers, the programs\n * prints a histogram of the number of actors with each Kevin Bacon number.\n *\n *\n * % java BaconHistogram movies.txt \"/\" \"Bacon, Kevin\"\n * 0 1\n * 1 1324\n * 2 70717\n * 3 40862\n * 4 1591\n * 5 125\n * Inf 0\n *\n * Remark: hard to identify actors with infinite bacon numbers because\n * we can't tell whether an unreachable vertex is an actor or movie.\n *\n ******************************************************************************/\n\npublic class BaconHistogram {\n public static void main(String[] args) {\n String filename = args[0];\n String delimiter = args[1];\n String source = args[2];\n\n SymbolGraph sg = new SymbolGraph(filename, delimiter);\n Graph G = sg.graph();\n if (!sg.contains(source)) {\n StdOut.println(source + \" not in database.\");\n return;\n }\n\n // run breadth-first search from s\n int s = sg.indexOf(source);\n BreadthFirstPaths bfs = new BreadthFirstPaths(G, s);\n\n\n // compute histogram of Kevin Bacon numbers - 100 for infinity\n int MAX_BACON = 100;\n int[] hist = new int[MAX_BACON + 1];\n for (int v = 0; v < G.V(); v++) {\n int bacon = Math.min(MAX_BACON, bfs.distTo(v));\n hist[bacon]++;\n\n // to print actors and movies with large bacon numbers\n if (bacon/2 >= 7 && bacon < MAX_BACON)\n StdOut.printf(\"%d %s\\n\", bacon/2, sg.nameOf(v));\n }\n\n // print out histogram - even indices are actors\n for (int i = 0; i < MAX_BACON; i += 2) {\n if (hist[i] == 0) break;\n StdOut.printf(\"%3d %8d\\n\", i/2, hist[i]);\n }\n StdOut.printf(\"Inf %8d\\n\", hist[MAX_BACON]);\n }\n}\n", "support_files": ["https://algs4.cs.princeton.edu/41graph/movies.txt"], "metadata": {"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"]}} {"question": "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. ", "answer": "/******************************************************************************\n * Compilation: javac Digraph.java\n * Execution: java Digraph filename.txt\n * Dependencies: Bag.java In.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/42digraph/tinyDG.txt\n * https://algs4.cs.princeton.edu/42digraph/mediumDG.txt\n * https://algs4.cs.princeton.edu/42digraph/largeDG.txt\n *\n * A graph, implemented using an array of lists.\n * Parallel edges and self-loops are permitted.\n *\n * % java Digraph tinyDG.txt\n * 13 vertices, 22 edges\n * 0: 5 1\n * 1:\n * 2: 0 3\n * 3: 5 2\n * 4: 3 2\n * 5: 4\n * 6: 9 4 8 0\n * 7: 6 9\n * 8: 6\n * 9: 11 10\n * 10: 12\n * 11: 4 12\n * 12: 9\n *\n ******************************************************************************/\n\nimport java.util.NoSuchElementException;\n\n/**\n * The {@code Digraph} class represents a directed graph of vertices\n * named 0 through V - 1.\n * It supports the following two primary operations: add an edge to the digraph,\n * iterate over all of the vertices adjacent from a given vertex.\n * It also provides\n * methods for returning the indegree or outdegree of a vertex,\n * the number of vertices V in the digraph,\n * the number of edges E in the digraph, and the reverse digraph.\n * Parallel edges and self-loops are permitted.\n *

\n * This implementation uses an adjacency-lists representation, which\n * is a vertex-indexed array of {@link Bag} objects.\n * It uses Θ(E + V) space, where E is\n * the number of edges and V is the number of vertices.\n * The reverse() method takes Θ(E + V) time\n * and space; all other instance methods take Θ(1) time. (Though, iterating over\n * the vertices returned by {@link #adj(int)} takes time proportional\n * to the outdegree of the vertex.)\n * Constructing an empty digraph with V vertices takes\n * Θ(V) time; constructing a digraph with E edges\n * and V vertices takes Θ(E + V) time.\n *

\n * For additional documentation,\n * see Section 4.2 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\n\npublic class Digraph {\n private static final String NEWLINE = System.getProperty(\"line.separator\");\n\n private final int V; // number of vertices in this digraph\n private int E; // number of edges in this digraph\n private Bag[] adj; // adj[v] = adjacency list for vertex v\n private int[] indegree; // indegree[v] = indegree of vertex v\n\n /**\n * Initializes an empty digraph with V vertices.\n *\n * @param V the number of vertices\n * @throws IllegalArgumentException if {@code V < 0}\n */\n public Digraph(int V) {\n if (V < 0) throw new IllegalArgumentException(\"Number of vertices in a Digraph must be non-negative\");\n this.V = V;\n this.E = 0;\n indegree = new int[V];\n adj = (Bag[]) new Bag[V];\n for (int v = 0; v < V; v++) {\n adj[v] = new Bag();\n }\n }\n\n /**\n * Initializes a digraph from the specified input stream.\n * The format is the number of vertices V,\n * followed by the number of edges E,\n * followed by E pairs of vertices, with each entry separated by whitespace.\n *\n * @param in the input stream\n * @throws IllegalArgumentException if {@code in} is {@code null}\n * @throws IllegalArgumentException if the endpoints of any edge are not in prescribed range\n * @throws IllegalArgumentException if the number of vertices or edges is negative\n * @throws IllegalArgumentException if the input stream is in the wrong format\n */\n public Digraph(In in) {\n if (in == null) throw new IllegalArgumentException(\"argument is null\");\n try {\n this.V = in.readInt();\n if (V < 0) throw new IllegalArgumentException(\"number of vertices in a Digraph must be non-negative\");\n indegree = new int[V];\n adj = (Bag[]) new Bag[V];\n for (int v = 0; v < V; v++) {\n adj[v] = new Bag();\n }\n int E = in.readInt();\n if (E < 0) throw new IllegalArgumentException(\"number of edges in a Digraph must be non-negative\");\n for (int i = 0; i < E; i++) {\n int v = in.readInt();\n int w = in.readInt();\n addEdge(v, w);\n }\n }\n catch (NoSuchElementException e) {\n throw new IllegalArgumentException(\"invalid input format in Digraph constructor\", e);\n }\n }\n\n /**\n * Initializes a new digraph that is a deep copy of the specified digraph.\n *\n * @param digraph the digraph to copy\n * @throws IllegalArgumentException if {@code digraph} is {@code null}\n */\n public Digraph(Digraph digraph) {\n if (digraph == null) throw new IllegalArgumentException(\"argument is null\");\n\n this.V = digraph.V();\n this.E = digraph.E();\n if (V < 0) throw new IllegalArgumentException(\"Number of vertices in a Digraph must be non-negative\");\n\n // update indegrees\n indegree = new int[V];\n for (int v = 0; v < V; v++)\n this.indegree[v] = digraph.indegree(v);\n\n // update adjacency lists\n adj = (Bag[]) new Bag[V];\n for (int v = 0; v < V; v++) {\n adj[v] = new Bag();\n }\n\n for (int v = 0; v < digraph.V(); v++) {\n // reverse so that adjacency list is in same order as original\n Stack reverse = new Stack();\n for (int w : digraph.adj[v]) {\n reverse.push(w);\n }\n for (int w : reverse) {\n adj[v].add(w);\n }\n }\n }\n\n /**\n * Returns the number of vertices in this digraph.\n *\n * @return the number of vertices in this digraph\n */\n public int V() {\n return V;\n }\n\n /**\n * Returns the number of edges in this digraph.\n *\n * @return the number of edges in this digraph\n */\n public int E() {\n return E;\n }\n\n\n // throw an IllegalArgumentException unless {@code 0 <= v < V}\n private void validateVertex(int v) {\n if (v < 0 || v >= V)\n throw new IllegalArgumentException(\"vertex \" + v + \" is not between 0 and \" + (V-1));\n }\n\n /**\n * Adds the directed edge v→w to this digraph.\n *\n * @param v the tail vertex\n * @param w the head vertex\n * @throws IllegalArgumentException unless both {@code 0 <= v < V} and {@code 0 <= w < V}\n */\n public void addEdge(int v, int w) {\n validateVertex(v);\n validateVertex(w);\n adj[v].add(w);\n indegree[w]++;\n E++;\n }\n\n /**\n * Returns the vertices adjacent from vertex {@code v} in this digraph.\n *\n * @param v the vertex\n * @return the vertices adjacent from vertex {@code v} in this digraph, as an iterable\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public Iterable adj(int v) {\n validateVertex(v);\n return adj[v];\n }\n\n /**\n * Returns the number of directed edges incident from vertex {@code v}.\n * This is known as the outdegree of vertex {@code v}.\n *\n * @param v the vertex\n * @return the outdegree of vertex {@code v}\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public int outdegree(int v) {\n validateVertex(v);\n return adj[v].size();\n }\n\n /**\n * Returns the number of directed edges incident to vertex {@code v}.\n * This is known as the indegree of vertex {@code v}.\n *\n * @param v the vertex\n * @return the indegree of vertex {@code v}\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public int indegree(int v) {\n validateVertex(v);\n return indegree[v];\n }\n\n /**\n * Returns the reverse of the digraph.\n *\n * @return the reverse of the digraph\n */\n public Digraph reverse() {\n Digraph reverse = new Digraph(V);\n for (int v = 0; v < V; v++) {\n for (int w : adj(v)) {\n reverse.addEdge(w, v);\n }\n }\n return reverse;\n }\n\n /**\n * Returns a string representation of the graph.\n *\n * @return the number of vertices V, followed by the number of edges E,\n * followed by the V adjacency lists\n */\n public String toString() {\n StringBuilder s = new StringBuilder();\n s.append(V + \" vertices, \" + E + \" edges \" + NEWLINE);\n for (int v = 0; v < V; v++) {\n s.append(String.format(\"%d: \", v));\n for (int w : adj[v]) {\n s.append(String.format(\"%d \", w));\n }\n s.append(NEWLINE);\n }\n return s.toString();\n }\n\n /**\n * Returns a string representation of this digraph in DOT format,\n * suitable for visualization with Graphviz.\n *\n * To visualize the digraph, install Graphviz (e.g., \"brew install graphviz\").\n * Then use one of the graph visualization tools\n * - dot (hierarchical or layer drawing)\n * - neato (spring model)\n * - fdp (force-directed placement)\n * - sfdp (scalable force-directed placement)\n * - twopi (radial layout)\n *\n * For example, the following commands will create graph drawings in SVG\n * and PDF formats\n * - dot input.dot -Tsvg -o output.svg\n * - dot input.dot -Tpdf -o output.pdf\n *\n * To change the digraph attributes (e.g., vertex and edge shapes, arrows, colors)\n * in the DOT format, see https://graphviz.org/doc/info/lang.html\n *\n * @return a string representation of this digraph in DOT format\n */\n public String toDot() {\n StringBuilder s = new StringBuilder();\n s.append(\"digraph {\" + NEWLINE);\n s.append(\"node[shape=circle, style=filled, fixedsize=true, width=0.3, fontsize=\\\"10pt\\\"]\" + NEWLINE);\n s.append(\"edge[arrowhead=normal]\" + NEWLINE);\n for (int v = 0; v < V; v++) {\n for (int w : adj[v]) {\n s.append(v + \" -> \" + w + NEWLINE);\n }\n }\n s.append(\"}\" + NEWLINE);\n return s.toString();\n }\n\n /**\n * Unit tests the {@code Digraph} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n In in = new In(args[0]);\n Digraph graph = new Digraph(in);\n StdOut.println(graph);\n }\n\n}\n", "support_files": ["https://algs4.cs.princeton.edu/42digraph/largeDG.txt", "https://algs4.cs.princeton.edu/42digraph/tinyDG.txt", "https://algs4.cs.princeton.edu/42digraph/mediumDG.txt"], "metadata": {"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"]}} {"question": "Implement the constructor for EdgeWeightedGraph.java that reads an edge-weighted graph from an input stream.", "answer": "/******************************************************************************\n * Compilation: javac EdgeWeightedGraph.java\n * Execution: java EdgeWeightedGraph filename.txt\n * Dependencies: Bag.java Edge.java In.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/43mst/tinyEWG.txt\n * https://algs4.cs.princeton.edu/43mst/mediumEWG.txt\n * https://algs4.cs.princeton.edu/43mst/largeEWG.txt\n *\n * An edge-weighted undirected graph, implemented using adjacency lists.\n * Parallel edges and self-loops are permitted.\n *\n * % java EdgeWeightedGraph tinyEWG.txt\n * 8 16\n * 0: 6-0 0.58000 0-2 0.26000 0-4 0.38000 0-7 0.16000\n * 1: 1-3 0.29000 1-2 0.36000 1-7 0.19000 1-5 0.32000\n * 2: 6-2 0.40000 2-7 0.34000 1-2 0.36000 0-2 0.26000 2-3 0.17000\n * 3: 3-6 0.52000 1-3 0.29000 2-3 0.17000\n * 4: 6-4 0.93000 0-4 0.38000 4-7 0.37000 4-5 0.35000\n * 5: 1-5 0.32000 5-7 0.28000 4-5 0.35000\n * 6: 6-4 0.93000 6-0 0.58000 3-6 0.52000 6-2 0.40000\n * 7: 2-7 0.34000 1-7 0.19000 0-7 0.16000 5-7 0.28000 4-7 0.37000\n *\n ******************************************************************************/\n\nimport java.util.NoSuchElementException;\n\n/**\n * The {@code EdgeWeightedGraph} class represents an edge-weighted\n * graph of vertices named 0 through V – 1, where each\n * undirected edge is of type {@link Edge} and has a real-valued weight.\n * It supports the following two primary operations: add an edge to the graph,\n * iterate over all of the edges incident with a vertex. It also provides\n * methods for returning the degree of a vertex, the number of vertices\n * V in the graph, and the number of edges E in the graph.\n * Parallel edges and self-loops are permitted.\n * By convention, a self-loop v-v appears in the\n * adjacency list of v twice and contributes two to the degree\n * of v.\n *

\n * This implementation uses an adjacency-lists representation, which\n * is a vertex-indexed array of {@link Bag} objects.\n * It uses Θ(E + V) space, where E is\n * the number of edges and V is the number of vertices.\n * All instance methods take Θ(1) time. (Though, iterating over\n * the edges returned by {@link #adj(int)} takes time proportional\n * to the degree of the vertex.)\n * Constructing an empty edge-weighted graph with V vertices takes\n * Θ(V) time; constructing an edge-weighted graph with\n * E edges and V vertices takes\n * Θ(E + V) time.\n *

\n * For additional documentation,\n * see Section 4.3 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class EdgeWeightedGraph {\n private static final String NEWLINE = System.getProperty(\"line.separator\");\n\n private final int V;\n private int E;\n private Bag[] adj;\n\n /**\n * Initializes an empty edge-weighted graph with {@code V} vertices and 0 edges.\n *\n * @param V the number of vertices\n * @throws IllegalArgumentException if {@code V < 0}\n */\n public EdgeWeightedGraph(int V) {\n if (V < 0) throw new IllegalArgumentException(\"Number of vertices must be non-negative\");\n this.V = V;\n this.E = 0;\n adj = (Bag[]) new Bag[V];\n for (int v = 0; v < V; v++) {\n adj[v] = new Bag();\n }\n }\n\n /**\n * Initializes a random edge-weighted graph with {@code V} vertices and E edges.\n *\n * @param V the number of vertices\n * @param E the number of edges\n * @throws IllegalArgumentException if {@code V < 0}\n * @throws IllegalArgumentException if {@code E < 0}\n */\n public EdgeWeightedGraph(int V, int E) {\n this(V);\n if (E < 0) throw new IllegalArgumentException(\"Number of edges must be non-negative\");\n for (int i = 0; i < E; i++) {\n int v = StdRandom.uniformInt(V);\n int w = StdRandom.uniformInt(V);\n double weight = 0.01 * StdRandom.uniformInt(0, 100);\n Edge e = new Edge(v, w, weight);\n addEdge(e);\n }\n }\n\n /**\n * Initializes an edge-weighted graph from an input stream.\n * The format is the number of vertices V,\n * followed by the number of edges E,\n * followed by E pairs of vertices and edge weights,\n * with each entry separated by whitespace.\n *\n * @param in the input stream\n * @throws IllegalArgumentException if {@code in} is {@code null}\n * @throws IllegalArgumentException if the endpoints of any edge are not in prescribed range\n * @throws IllegalArgumentException if the number of vertices or edges is negative\n */\n public EdgeWeightedGraph(In in) {\n if (in == null) throw new IllegalArgumentException(\"argument is null\");\n\n try {\n V = in.readInt();\n adj = (Bag[]) new Bag[V];\n for (int v = 0; v < V; v++) {\n adj[v] = new Bag();\n }\n\n int E = in.readInt();\n if (E < 0) throw new IllegalArgumentException(\"Number of edges must be non-negative\");\n for (int i = 0; i < E; i++) {\n int v = in.readInt();\n int w = in.readInt();\n validateVertex(v);\n validateVertex(w);\n double weight = in.readDouble();\n Edge e = new Edge(v, w, weight);\n addEdge(e);\n }\n }\n catch (NoSuchElementException e) {\n throw new IllegalArgumentException(\"invalid input format in EdgeWeightedGraph constructor\", e);\n }\n\n }\n\n /**\n * Initializes a new edge-weighted graph that is a deep copy of {@code G}.\n *\n * @param G the edge-weighted graph to copy\n */\n public EdgeWeightedGraph(EdgeWeightedGraph G) {\n this(G.V());\n this.E = G.E();\n for (int v = 0; v < G.V(); v++) {\n // reverse so that adjacency list is in same order as original\n Stack reverse = new Stack();\n for (Edge e : G.adj[v]) {\n reverse.push(e);\n }\n for (Edge e : reverse) {\n adj[v].add(e);\n }\n }\n }\n\n\n /**\n * Returns the number of vertices in this edge-weighted graph.\n *\n * @return the number of vertices in this edge-weighted graph\n */\n public int V() {\n return V;\n }\n\n /**\n * Returns the number of edges in this edge-weighted graph.\n *\n * @return the number of edges in this edge-weighted graph\n */\n public int E() {\n return E;\n }\n\n // throw an IllegalArgumentException unless {@code 0 <= v < V}\n private void validateVertex(int v) {\n if (v < 0 || v >= V)\n throw new IllegalArgumentException(\"vertex \" + v + \" is not between 0 and \" + (V-1));\n }\n\n /**\n * Adds the undirected edge {@code e} to this edge-weighted graph.\n *\n * @param e the edge\n * @throws IllegalArgumentException unless both endpoints are between {@code 0} and {@code V-1}\n */\n public void addEdge(Edge e) {\n int v = e.either();\n int w = e.other(v);\n validateVertex(v);\n validateVertex(w);\n adj[v].add(e);\n adj[w].add(e);\n E++;\n }\n\n /**\n * Returns the edges incident with vertex {@code v}.\n *\n * @param v the vertex\n * @return the edges incident with vertex {@code v} as an Iterable\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public Iterable adj(int v) {\n validateVertex(v);\n return adj[v];\n }\n\n /**\n * Returns the degree of vertex {@code v}.\n *\n * @param v the vertex\n * @return the degree of vertex {@code v}\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public int degree(int v) {\n validateVertex(v);\n return adj[v].size();\n }\n\n /**\n * Returns all edges in this edge-weighted graph.\n * To iterate over the edges in this edge-weighted graph, use foreach notation:\n * {@code for (Edge e : G.edges())}.\n *\n * @return all edges in this edge-weighted graph, as an iterable\n */\n public Iterable edges() {\n Bag list = new Bag();\n for (int v = 0; v < V; v++) {\n int selfLoops = 0;\n for (Edge e : adj(v)) {\n if (e.other(v) > v) {\n list.add(e);\n }\n // add only one copy of each self loop (self loops will be consecutive)\n else if (e.other(v) == v) {\n if (selfLoops % 2 == 0) list.add(e);\n selfLoops++;\n }\n }\n }\n return list;\n }\n\n /**\n * Returns a string representation of the edge-weighted graph.\n * This method takes time proportional to E + V.\n *\n * @return the number of vertices V, followed by the number of edges E,\n * followed by the V adjacency lists of edges\n */\n public String toString() {\n StringBuilder s = new StringBuilder();\n s.append(V + \" \" + E + NEWLINE);\n for (int v = 0; v < V; v++) {\n s.append(v + \": \");\n for (Edge e : adj[v]) {\n s.append(e + \" \");\n }\n s.append(NEWLINE);\n }\n return s.toString();\n }\n\n /**\n * Returns a string representation of this edge-weighted graph in DOT format,\n * suitable for visualization with Graphviz.\n *\n * To visualize the graph, install Graphviz (e.g., \"brew install graphviz\").\n * Then use one of the graph visualization tools\n * - dot (hierarchical or layer drawing)\n * - neato (spring model)\n * - fdp (force-directed placement)\n * - sfdp (scalable force-directed placement)\n * - twopi (radial layout)\n *\n * For example, the following commands will create graph drawings in SVG\n * and PDF formats\n * - dot input.dot -Tsvg -o output.svg\n * - dot input.dot -Tpdf -o output.pdf\n *\n * To change the graph attributes (e.g., vertex and edge shapes, arrows, colors)\n * in the DOT format, see https://graphviz.org/doc/info/lang.html\n *\n * @return a string representation of this edge-weighted graph in DOT format\n */\n public String toDot() {\n StringBuilder s = new StringBuilder();\n s.append(\"graph {\" + NEWLINE);\n s.append(\"node[shape=circle, style=filled, fixedsize=true, width=0.3, fontsize=\\\"10pt\\\"]\" + NEWLINE);\n s.append(\"edge[arrowhead=normal, fontsize=\\\"9pt\\\"]\" + NEWLINE);\n for (Edge e : edges()) {\n int v = e.either();\n int w = e.other(v);\n s.append(v + \" --\" + w + \" [label=\\\"\" + e.weight() + \"\\\"]\" + NEWLINE);\n }\n s.append(\"}\" + NEWLINE);\n return s.toString();\n }\n\n /**\n * Unit tests the {@code EdgeWeightedGraph} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n In in = new In(args[0]);\n EdgeWeightedGraph graph = new EdgeWeightedGraph(in);\n StdOut.println(graph);\n }\n\n}\n", "support_files": ["https://algs4.cs.princeton.edu/43mst/mediumEWG.txt", "https://algs4.cs.princeton.edu/43mst/tinyEWG.txt", "https://algs4.cs.princeton.edu/43mst/largeEWG.txt"], "metadata": {"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"]}} {"question": "Implement toString() for EdgeWeightedGraph.java.", "answer": "/******************************************************************************\n * Compilation: javac EdgeWeightedGraph.java\n * Execution: java EdgeWeightedGraph filename.txt\n * Dependencies: Bag.java Edge.java In.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/43mst/tinyEWG.txt\n * https://algs4.cs.princeton.edu/43mst/mediumEWG.txt\n * https://algs4.cs.princeton.edu/43mst/largeEWG.txt\n *\n * An edge-weighted undirected graph, implemented using adjacency lists.\n * Parallel edges and self-loops are permitted.\n *\n * % java EdgeWeightedGraph tinyEWG.txt\n * 8 16\n * 0: 6-0 0.58000 0-2 0.26000 0-4 0.38000 0-7 0.16000\n * 1: 1-3 0.29000 1-2 0.36000 1-7 0.19000 1-5 0.32000\n * 2: 6-2 0.40000 2-7 0.34000 1-2 0.36000 0-2 0.26000 2-3 0.17000\n * 3: 3-6 0.52000 1-3 0.29000 2-3 0.17000\n * 4: 6-4 0.93000 0-4 0.38000 4-7 0.37000 4-5 0.35000\n * 5: 1-5 0.32000 5-7 0.28000 4-5 0.35000\n * 6: 6-4 0.93000 6-0 0.58000 3-6 0.52000 6-2 0.40000\n * 7: 2-7 0.34000 1-7 0.19000 0-7 0.16000 5-7 0.28000 4-7 0.37000\n *\n ******************************************************************************/\n\nimport java.util.NoSuchElementException;\n\n/**\n * The {@code EdgeWeightedGraph} class represents an edge-weighted\n * graph of vertices named 0 through V – 1, where each\n * undirected edge is of type {@link Edge} and has a real-valued weight.\n * It supports the following two primary operations: add an edge to the graph,\n * iterate over all of the edges incident with a vertex. It also provides\n * methods for returning the degree of a vertex, the number of vertices\n * V in the graph, and the number of edges E in the graph.\n * Parallel edges and self-loops are permitted.\n * By convention, a self-loop v-v appears in the\n * adjacency list of v twice and contributes two to the degree\n * of v.\n *

\n * This implementation uses an adjacency-lists representation, which\n * is a vertex-indexed array of {@link Bag} objects.\n * It uses Θ(E + V) space, where E is\n * the number of edges and V is the number of vertices.\n * All instance methods take Θ(1) time. (Though, iterating over\n * the edges returned by {@link #adj(int)} takes time proportional\n * to the degree of the vertex.)\n * Constructing an empty edge-weighted graph with V vertices takes\n * Θ(V) time; constructing an edge-weighted graph with\n * E edges and V vertices takes\n * Θ(E + V) time.\n *

\n * For additional documentation,\n * see Section 4.3 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class EdgeWeightedGraph {\n private static final String NEWLINE = System.getProperty(\"line.separator\");\n\n private final int V;\n private int E;\n private Bag[] adj;\n\n /**\n * Initializes an empty edge-weighted graph with {@code V} vertices and 0 edges.\n *\n * @param V the number of vertices\n * @throws IllegalArgumentException if {@code V < 0}\n */\n public EdgeWeightedGraph(int V) {\n if (V < 0) throw new IllegalArgumentException(\"Number of vertices must be non-negative\");\n this.V = V;\n this.E = 0;\n adj = (Bag[]) new Bag[V];\n for (int v = 0; v < V; v++) {\n adj[v] = new Bag();\n }\n }\n\n /**\n * Initializes a random edge-weighted graph with {@code V} vertices and E edges.\n *\n * @param V the number of vertices\n * @param E the number of edges\n * @throws IllegalArgumentException if {@code V < 0}\n * @throws IllegalArgumentException if {@code E < 0}\n */\n public EdgeWeightedGraph(int V, int E) {\n this(V);\n if (E < 0) throw new IllegalArgumentException(\"Number of edges must be non-negative\");\n for (int i = 0; i < E; i++) {\n int v = StdRandom.uniformInt(V);\n int w = StdRandom.uniformInt(V);\n double weight = 0.01 * StdRandom.uniformInt(0, 100);\n Edge e = new Edge(v, w, weight);\n addEdge(e);\n }\n }\n\n /**\n * Initializes an edge-weighted graph from an input stream.\n * The format is the number of vertices V,\n * followed by the number of edges E,\n * followed by E pairs of vertices and edge weights,\n * with each entry separated by whitespace.\n *\n * @param in the input stream\n * @throws IllegalArgumentException if {@code in} is {@code null}\n * @throws IllegalArgumentException if the endpoints of any edge are not in prescribed range\n * @throws IllegalArgumentException if the number of vertices or edges is negative\n */\n public EdgeWeightedGraph(In in) {\n if (in == null) throw new IllegalArgumentException(\"argument is null\");\n\n try {\n V = in.readInt();\n adj = (Bag[]) new Bag[V];\n for (int v = 0; v < V; v++) {\n adj[v] = new Bag();\n }\n\n int E = in.readInt();\n if (E < 0) throw new IllegalArgumentException(\"Number of edges must be non-negative\");\n for (int i = 0; i < E; i++) {\n int v = in.readInt();\n int w = in.readInt();\n validateVertex(v);\n validateVertex(w);\n double weight = in.readDouble();\n Edge e = new Edge(v, w, weight);\n addEdge(e);\n }\n }\n catch (NoSuchElementException e) {\n throw new IllegalArgumentException(\"invalid input format in EdgeWeightedGraph constructor\", e);\n }\n\n }\n\n /**\n * Initializes a new edge-weighted graph that is a deep copy of {@code G}.\n *\n * @param G the edge-weighted graph to copy\n */\n public EdgeWeightedGraph(EdgeWeightedGraph G) {\n this(G.V());\n this.E = G.E();\n for (int v = 0; v < G.V(); v++) {\n // reverse so that adjacency list is in same order as original\n Stack reverse = new Stack();\n for (Edge e : G.adj[v]) {\n reverse.push(e);\n }\n for (Edge e : reverse) {\n adj[v].add(e);\n }\n }\n }\n\n\n /**\n * Returns the number of vertices in this edge-weighted graph.\n *\n * @return the number of vertices in this edge-weighted graph\n */\n public int V() {\n return V;\n }\n\n /**\n * Returns the number of edges in this edge-weighted graph.\n *\n * @return the number of edges in this edge-weighted graph\n */\n public int E() {\n return E;\n }\n\n // throw an IllegalArgumentException unless {@code 0 <= v < V}\n private void validateVertex(int v) {\n if (v < 0 || v >= V)\n throw new IllegalArgumentException(\"vertex \" + v + \" is not between 0 and \" + (V-1));\n }\n\n /**\n * Adds the undirected edge {@code e} to this edge-weighted graph.\n *\n * @param e the edge\n * @throws IllegalArgumentException unless both endpoints are between {@code 0} and {@code V-1}\n */\n public void addEdge(Edge e) {\n int v = e.either();\n int w = e.other(v);\n validateVertex(v);\n validateVertex(w);\n adj[v].add(e);\n adj[w].add(e);\n E++;\n }\n\n /**\n * Returns the edges incident with vertex {@code v}.\n *\n * @param v the vertex\n * @return the edges incident with vertex {@code v} as an Iterable\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public Iterable adj(int v) {\n validateVertex(v);\n return adj[v];\n }\n\n /**\n * Returns the degree of vertex {@code v}.\n *\n * @param v the vertex\n * @return the degree of vertex {@code v}\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public int degree(int v) {\n validateVertex(v);\n return adj[v].size();\n }\n\n /**\n * Returns all edges in this edge-weighted graph.\n * To iterate over the edges in this edge-weighted graph, use foreach notation:\n * {@code for (Edge e : G.edges())}.\n *\n * @return all edges in this edge-weighted graph, as an iterable\n */\n public Iterable edges() {\n Bag list = new Bag();\n for (int v = 0; v < V; v++) {\n int selfLoops = 0;\n for (Edge e : adj(v)) {\n if (e.other(v) > v) {\n list.add(e);\n }\n // add only one copy of each self loop (self loops will be consecutive)\n else if (e.other(v) == v) {\n if (selfLoops % 2 == 0) list.add(e);\n selfLoops++;\n }\n }\n }\n return list;\n }\n\n /**\n * Returns a string representation of the edge-weighted graph.\n * This method takes time proportional to E + V.\n *\n * @return the number of vertices V, followed by the number of edges E,\n * followed by the V adjacency lists of edges\n */\n public String toString() {\n StringBuilder s = new StringBuilder();\n s.append(V + \" \" + E + NEWLINE);\n for (int v = 0; v < V; v++) {\n s.append(v + \": \");\n for (Edge e : adj[v]) {\n s.append(e + \" \");\n }\n s.append(NEWLINE);\n }\n return s.toString();\n }\n\n /**\n * Returns a string representation of this edge-weighted graph in DOT format,\n * suitable for visualization with Graphviz.\n *\n * To visualize the graph, install Graphviz (e.g., \"brew install graphviz\").\n * Then use one of the graph visualization tools\n * - dot (hierarchical or layer drawing)\n * - neato (spring model)\n * - fdp (force-directed placement)\n * - sfdp (scalable force-directed placement)\n * - twopi (radial layout)\n *\n * For example, the following commands will create graph drawings in SVG\n * and PDF formats\n * - dot input.dot -Tsvg -o output.svg\n * - dot input.dot -Tpdf -o output.pdf\n *\n * To change the graph attributes (e.g., vertex and edge shapes, arrows, colors)\n * in the DOT format, see https://graphviz.org/doc/info/lang.html\n *\n * @return a string representation of this edge-weighted graph in DOT format\n */\n public String toDot() {\n StringBuilder s = new StringBuilder();\n s.append(\"graph {\" + NEWLINE);\n s.append(\"node[shape=circle, style=filled, fixedsize=true, width=0.3, fontsize=\\\"10pt\\\"]\" + NEWLINE);\n s.append(\"edge[arrowhead=normal, fontsize=\\\"9pt\\\"]\" + NEWLINE);\n for (Edge e : edges()) {\n int v = e.either();\n int w = e.other(v);\n s.append(v + \" --\" + w + \" [label=\\\"\" + e.weight() + \"\\\"]\" + NEWLINE);\n }\n s.append(\"}\" + NEWLINE);\n return s.toString();\n }\n\n /**\n * Unit tests the {@code EdgeWeightedGraph} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n In in = new In(args[0]);\n EdgeWeightedGraph graph = new EdgeWeightedGraph(in);\n StdOut.println(graph);\n }\n\n}\n", "support_files": ["https://algs4.cs.princeton.edu/43mst/mediumEWG.txt", "https://algs4.cs.princeton.edu/43mst/tinyEWG.txt", "https://algs4.cs.princeton.edu/43mst/largeEWG.txt"], "metadata": {"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"]}} {"question": "Provide an implementation of edges() for PrimMST.java .", "answer": "/******************************************************************************\n * Compilation: javac PrimMST.java\n * Execution: java PrimMST filename.txt\n * Dependencies: EdgeWeightedGraph.java Edge.java Queue.java\n * IndexMinPQ.java UF.java In.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/43mst/tinyEWG.txt\n * https://algs4.cs.princeton.edu/43mst/mediumEWG.txt\n * https://algs4.cs.princeton.edu/43mst/largeEWG.txt\n *\n * Compute a minimum spanning forest using Prim's algorithm.\n *\n * % java PrimMST tinyEWG.txt\n * 1-7 0.19000\n * 0-2 0.26000\n * 2-3 0.17000\n * 4-5 0.35000\n * 5-7 0.28000\n * 6-2 0.40000\n * 0-7 0.16000\n * 1.81000\n *\n * % java PrimMST mediumEWG.txt\n * 1-72 0.06506\n * 2-86 0.05980\n * 3-67 0.09725\n * 4-55 0.06425\n * 5-102 0.03834\n * 6-129 0.05363\n * 7-157 0.00516\n * ...\n * 10.46351\n *\n * % java PrimMST largeEWG.txt\n * ...\n * 647.66307\n *\n ******************************************************************************/\n\n/**\n * The {@code PrimMST} class represents a data type for computing a\n * minimum spanning tree in an edge-weighted graph.\n * The edge weights can be positive, zero, or negative and need not\n * be distinct. If the graph is not connected, it computes a minimum\n * spanning forest, which is the union of minimum spanning trees\n * in each connected component. The {@code weight()} method returns the\n * weight of a minimum spanning tree and the {@code edges()} method\n * returns its edges.\n *

\n * This implementation uses Prim's algorithm with an indexed\n * binary heap.\n * The constructor takes Θ(E log V) time in\n * the worst case, where V is the number of\n * vertices and E is the number of edges.\n * Each instance method takes Θ(1) time.\n * It uses Θ(V) extra space (not including the\n * edge-weighted graph).\n *

\n * This {@code weight()} method correctly computes the weight of the MST\n * if all arithmetic performed is without floating-point rounding error\n * or arithmetic overflow.\n * This is the case if all edge weights are non-negative integers\n * and the weight of the MST does not exceed 252.\n *

\n * For additional documentation,\n * see Section 4.3 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n * For alternate implementations, see {@link LazyPrimMST}, {@link KruskalMST},\n * and {@link BoruvkaMST}.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class PrimMST {\n private static final double FLOATING_POINT_EPSILON = 1.0E-12;\n\n private Edge[] edgeTo; // edgeTo[v] = shortest edge from tree vertex to non-tree vertex\n private double[] distTo; // distTo[v] = weight of shortest such edge\n private boolean[] marked; // marked[v] = true if v on tree, false otherwise\n private IndexMinPQ pq;\n\n /**\n * Compute a minimum spanning tree (or forest) of an edge-weighted graph.\n * @param graph the edge-weighted graph\n */\n public PrimMST(EdgeWeightedGraph graph) {\n edgeTo = new Edge[graph.V()];\n distTo = new double[graph.V()];\n marked = new boolean[graph.V()];\n pq = new IndexMinPQ(graph.V());\n for (int v = 0; v < graph.V(); v++)\n distTo[v] = Double.POSITIVE_INFINITY;\n\n for (int v = 0; v < graph.V(); v++) // run from each vertex to find\n if (!marked[v]) prim(graph, v); // minimum spanning forest\n\n // check optimality conditions\n assert check(graph);\n }\n\n // run Prim's algorithm in graph, starting from vertex s\n private void prim(EdgeWeightedGraph graph, int s) {\n distTo[s] = 0.0;\n pq.insert(s, distTo[s]);\n while (!pq.isEmpty()) {\n int v = pq.delMin();\n scan(graph, v);\n }\n }\n\n // scan vertex v\n private void scan(EdgeWeightedGraph graph, int v) {\n marked[v] = true;\n for (Edge e : graph.adj(v)) {\n int w = e.other(v);\n if (marked[w]) continue; // v-w is obsolete edge\n if (e.weight() < distTo[w]) {\n distTo[w] = e.weight();\n edgeTo[w] = e;\n if (pq.contains(w)) pq.decreaseKey(w, distTo[w]);\n else pq.insert(w, distTo[w]);\n }\n }\n }\n\n /**\n * Returns the edges in a minimum spanning tree (or forest).\n * @return the edges in a minimum spanning tree (or forest) as\n * an iterable of edges\n */\n public Iterable edges() {\n Queue mst = new Queue();\n for (int v = 0; v < edgeTo.length; v++) {\n Edge e = edgeTo[v];\n if (e != null) {\n mst.enqueue(e);\n }\n }\n return mst;\n }\n\n /**\n * Returns the sum of the edge weights in a minimum spanning tree (or forest).\n * @return the sum of the edge weights in a minimum spanning tree (or forest)\n */\n public double weight() {\n double weight = 0.0;\n for (Edge e : edges())\n weight += e.weight();\n return weight;\n }\n\n\n // check optimality conditions (takes time proportional to E V lg* V)\n private boolean check(EdgeWeightedGraph graph) {\n\n // check weight\n double totalWeight = 0.0;\n for (Edge e : edges()) {\n totalWeight += e.weight();\n }\n if (Math.abs(totalWeight - weight()) > FLOATING_POINT_EPSILON) {\n System.err.printf(\"Weight of edges does not equal weight(): %f vs. %f\", totalWeight, weight());\n return false;\n }\n\n // check that it is acyclic\n UF uf = new UF(graph.V());\n for (Edge e : edges()) {\n int v = e.either(), w = e.other(v);\n if (uf.find(v) == uf.find(w)) {\n System.err.println(\"Not a forest\");\n return false;\n }\n uf.union(v, w);\n }\n\n // check that it is a spanning forest\n for (Edge e : graph.edges()) {\n int v = e.either(), w = e.other(v);\n if (uf.find(v) != uf.find(w)) {\n System.err.println(\"Not a spanning forest\");\n return false;\n }\n }\n\n // check that it is a minimal spanning forest (cut optimality conditions)\n for (Edge e : edges()) {\n\n // all edges in MST except e\n uf = new UF(graph.V());\n for (Edge f : edges()) {\n int x = f.either(), y = f.other(x);\n if (f != e) uf.union(x, y);\n }\n\n // check that e is min weight edge in crossing cut\n for (Edge f : graph.edges()) {\n int x = f.either(), y = f.other(x);\n if (uf.find(x) != uf.find(y)) {\n if (f.weight() < e.weight()) {\n System.err.println(\"Edge \" + f + \" violates cut optimality conditions\");\n return false;\n }\n }\n }\n\n }\n\n return true;\n }\n\n /**\n * Unit tests the {@code PrimMST} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n In in = new In(args[0]);\n EdgeWeightedGraph graph = new EdgeWeightedGraph(in);\n PrimMST mst = new PrimMST(graph);\n for (Edge e : mst.edges()) {\n StdOut.println(e);\n }\n StdOut.printf(\"%.5f\", mst.weight());\n }\n\n\n}\n", "support_files": ["https://algs4.cs.princeton.edu/43mst/mediumEWG.txt", "https://algs4.cs.princeton.edu/43mst/tinyEWG.txt", "https://algs4.cs.princeton.edu/43mst/largeEWG.txt"], "metadata": {"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"]}} {"question": "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. ", "answer": "/******************************************************************************\n * Compilation: javac PrimMST.java\n * Execution: java PrimMST filename.txt\n * Dependencies: EdgeWeightedGraph.java Edge.java Queue.java\n * IndexMinPQ.java UF.java In.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/43mst/tinyEWG.txt\n * https://algs4.cs.princeton.edu/43mst/mediumEWG.txt\n * https://algs4.cs.princeton.edu/43mst/largeEWG.txt\n *\n * Compute a minimum spanning forest using Prim's algorithm.\n *\n * % java PrimMST tinyEWG.txt\n * 1-7 0.19000\n * 0-2 0.26000\n * 2-3 0.17000\n * 4-5 0.35000\n * 5-7 0.28000\n * 6-2 0.40000\n * 0-7 0.16000\n * 1.81000\n *\n * % java PrimMST mediumEWG.txt\n * 1-72 0.06506\n * 2-86 0.05980\n * 3-67 0.09725\n * 4-55 0.06425\n * 5-102 0.03834\n * 6-129 0.05363\n * 7-157 0.00516\n * ...\n * 10.46351\n *\n * % java PrimMST largeEWG.txt\n * ...\n * 647.66307\n *\n ******************************************************************************/\n\n/**\n * The {@code PrimMST} class represents a data type for computing a\n * minimum spanning tree in an edge-weighted graph.\n * The edge weights can be positive, zero, or negative and need not\n * be distinct. If the graph is not connected, it computes a minimum\n * spanning forest, which is the union of minimum spanning trees\n * in each connected component. The {@code weight()} method returns the\n * weight of a minimum spanning tree and the {@code edges()} method\n * returns its edges.\n *

\n * This implementation uses Prim's algorithm with an indexed\n * binary heap.\n * The constructor takes Θ(E log V) time in\n * the worst case, where V is the number of\n * vertices and E is the number of edges.\n * Each instance method takes Θ(1) time.\n * It uses Θ(V) extra space (not including the\n * edge-weighted graph).\n *

\n * This {@code weight()} method correctly computes the weight of the MST\n * if all arithmetic performed is without floating-point rounding error\n * or arithmetic overflow.\n * This is the case if all edge weights are non-negative integers\n * and the weight of the MST does not exceed 252.\n *

\n * For additional documentation,\n * see Section 4.3 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n * For alternate implementations, see {@link LazyPrimMST}, {@link KruskalMST},\n * and {@link BoruvkaMST}.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class PrimMST {\n private static final double FLOATING_POINT_EPSILON = 1.0E-12;\n\n private Edge[] edgeTo; // edgeTo[v] = shortest edge from tree vertex to non-tree vertex\n private double[] distTo; // distTo[v] = weight of shortest such edge\n private boolean[] marked; // marked[v] = true if v on tree, false otherwise\n private IndexMinPQ pq;\n\n /**\n * Compute a minimum spanning tree (or forest) of an edge-weighted graph.\n * @param graph the edge-weighted graph\n */\n public PrimMST(EdgeWeightedGraph graph) {\n edgeTo = new Edge[graph.V()];\n distTo = new double[graph.V()];\n marked = new boolean[graph.V()];\n pq = new IndexMinPQ(graph.V());\n for (int v = 0; v < graph.V(); v++)\n distTo[v] = Double.POSITIVE_INFINITY;\n\n for (int v = 0; v < graph.V(); v++) // run from each vertex to find\n if (!marked[v]) prim(graph, v); // minimum spanning forest\n\n // check optimality conditions\n assert check(graph);\n }\n\n // run Prim's algorithm in graph, starting from vertex s\n private void prim(EdgeWeightedGraph graph, int s) {\n distTo[s] = 0.0;\n pq.insert(s, distTo[s]);\n while (!pq.isEmpty()) {\n int v = pq.delMin();\n scan(graph, v);\n }\n }\n\n // scan vertex v\n private void scan(EdgeWeightedGraph graph, int v) {\n marked[v] = true;\n for (Edge e : graph.adj(v)) {\n int w = e.other(v);\n if (marked[w]) continue; // v-w is obsolete edge\n if (e.weight() < distTo[w]) {\n distTo[w] = e.weight();\n edgeTo[w] = e;\n if (pq.contains(w)) pq.decreaseKey(w, distTo[w]);\n else pq.insert(w, distTo[w]);\n }\n }\n }\n\n /**\n * Returns the edges in a minimum spanning tree (or forest).\n * @return the edges in a minimum spanning tree (or forest) as\n * an iterable of edges\n */\n public Iterable edges() {\n Queue mst = new Queue();\n for (int v = 0; v < edgeTo.length; v++) {\n Edge e = edgeTo[v];\n if (e != null) {\n mst.enqueue(e);\n }\n }\n return mst;\n }\n\n /**\n * Returns the sum of the edge weights in a minimum spanning tree (or forest).\n * @return the sum of the edge weights in a minimum spanning tree (or forest)\n */\n public double weight() {\n double weight = 0.0;\n for (Edge e : edges())\n weight += e.weight();\n return weight;\n }\n\n\n // check optimality conditions (takes time proportional to E V lg* V)\n private boolean check(EdgeWeightedGraph graph) {\n\n // check weight\n double totalWeight = 0.0;\n for (Edge e : edges()) {\n totalWeight += e.weight();\n }\n if (Math.abs(totalWeight - weight()) > FLOATING_POINT_EPSILON) {\n System.err.printf(\"Weight of edges does not equal weight(): %f vs. %f\", totalWeight, weight());\n return false;\n }\n\n // check that it is acyclic\n UF uf = new UF(graph.V());\n for (Edge e : edges()) {\n int v = e.either(), w = e.other(v);\n if (uf.find(v) == uf.find(w)) {\n System.err.println(\"Not a forest\");\n return false;\n }\n uf.union(v, w);\n }\n\n // check that it is a spanning forest\n for (Edge e : graph.edges()) {\n int v = e.either(), w = e.other(v);\n if (uf.find(v) != uf.find(w)) {\n System.err.println(\"Not a spanning forest\");\n return false;\n }\n }\n\n // check that it is a minimal spanning forest (cut optimality conditions)\n for (Edge e : edges()) {\n\n // all edges in MST except e\n uf = new UF(graph.V());\n for (Edge f : edges()) {\n int x = f.either(), y = f.other(x);\n if (f != e) uf.union(x, y);\n }\n\n // check that e is min weight edge in crossing cut\n for (Edge f : graph.edges()) {\n int x = f.either(), y = f.other(x);\n if (uf.find(x) != uf.find(y)) {\n if (f.weight() < e.weight()) {\n System.err.println(\"Edge \" + f + \" violates cut optimality conditions\");\n return false;\n }\n }\n }\n\n }\n\n return true;\n }\n\n /**\n * Unit tests the {@code PrimMST} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n In in = new In(args[0]);\n EdgeWeightedGraph graph = new EdgeWeightedGraph(in);\n PrimMST mst = new PrimMST(graph);\n for (Edge e : mst.edges()) {\n StdOut.println(e);\n }\n StdOut.printf(\"%.5f\", mst.weight());\n }\n\n\n}\n", "support_files": ["https://algs4.cs.princeton.edu/43mst/mediumEWG.txt", "https://algs4.cs.princeton.edu/43mst/tinyEWG.txt", "https://algs4.cs.princeton.edu/43mst/largeEWG.txt"], "metadata": {"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"]}} {"question": "Minimum spanning forest. Develop versions of Kruskal's algorithms that compute \nthe minimum spanning forest of an edge-weighted graph that\nis not necessarily connected.", "answer": "/******************************************************************************\n * Compilation: javac KruskalMST.java\n * Execution: java KruskalMST filename.txt\n * Dependencies: EdgeWeightedGraph.java Edge.java Queue.java MinPQ.java\n * UF.java In.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/43mst/tinyEWG.txt\n * https://algs4.cs.princeton.edu/43mst/mediumEWG.txt\n * https://algs4.cs.princeton.edu/43mst/largeEWG.txt\n *\n * Compute a minimum spanning forest using Kruskal's algorithm.\n *\n * % java KruskalMST tinyEWG.txt\n * 0-7 0.16000\n * 2-3 0.17000\n * 1-7 0.19000\n * 0-2 0.26000\n * 5-7 0.28000\n * 4-5 0.35000\n * 6-2 0.40000\n * 1.81000\n *\n * % java KruskalMST mediumEWG.txt\n * 168-231 0.00268\n * 151-208 0.00391\n * 7-157 0.00516\n * 122-205 0.00647\n * 8-152 0.00702\n * 156-219 0.00745\n * 28-198 0.00775\n * 38-126 0.00845\n * 10-123 0.00886\n * ...\n * 10.46351\n *\n ******************************************************************************/\n\nimport java.util.Arrays;\n\n/**\n * The {@code KruskalMST} class represents a data type for computing a\n * minimum spanning tree in an edge-weighted graph.\n * The edge weights can be positive, zero, or negative and need not\n * be distinct. If the graph is not connected, it computes a minimum\n * spanning forest, which is the union of minimum spanning trees\n * in each connected component. The {@code weight()} method returns the\n * weight of a minimum spanning tree and the {@code edges()} method\n * returns its edges.\n *

\n * This implementation uses Kruskal's algorithm and the\n * union-find data type.\n * The constructor takes Θ(E log E) time in\n * the worst case.\n * Each instance method takes Θ(1) time.\n * It uses Θ(E) extra space (not including the graph).\n *

\n * This {@code weight()} method correctly computes the weight of the MST\n * if all arithmetic performed is without floating-point rounding error\n * or arithmetic overflow.\n * This is the case if all edge weights are non-negative integers\n * and the weight of the MST does not exceed 252.\n *

\n * For additional documentation,\n * see Section 4.3 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n * For alternate implementations, see {@link LazyPrimMST}, {@link PrimMST},\n * and {@link BoruvkaMST}.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class KruskalMST {\n private static final double FLOATING_POINT_EPSILON = 1.0E-12;\n\n private double weight; // weight of MST\n private Queue mst = new Queue(); // edges in MST\n\n /**\n * Compute a minimum spanning tree (or forest) of an edge-weighted graph.\n * @param graph the edge-weighted graph\n */\n public KruskalMST(EdgeWeightedGraph graph) {\n\n // create array of edges, sorted by weight\n Edge[] edges = new Edge[graph.E()];\n int t = 0;\n for (Edge e: graph.edges()) {\n edges[t++] = e;\n }\n Arrays.sort(edges);\n\n // run greedy algorithm\n UF uf = new UF(graph.V());\n for (int i = 0; i < graph.E() && mst.size() < graph.V() - 1; i++) {\n Edge e = edges[i];\n int v = e.either();\n int w = e.other(v);\n\n // v-w does not create a cycle\n if (uf.find(v) != uf.find(w)) {\n uf.union(v, w); // merge v and w components\n mst.enqueue(e); // add edge e to mst\n weight += e.weight();\n }\n }\n\n // check optimality conditions\n assert check(graph);\n }\n\n /**\n * Returns the edges in a minimum spanning tree (or forest).\n * @return the edges in a minimum spanning tree (or forest) as\n * an iterable of edges\n */\n public Iterable edges() {\n return mst;\n }\n\n /**\n * Returns the sum of the edge weights in a minimum spanning tree (or forest).\n * @return the sum of the edge weights in a minimum spanning tree (or forest)\n */\n public double weight() {\n return weight;\n }\n\n // check optimality conditions (takes time proportional to E V lg* V)\n private boolean check(EdgeWeightedGraph graph) {\n\n // check total weight\n double total = 0.0;\n for (Edge e : edges()) {\n total += e.weight();\n }\n if (Math.abs(total - weight()) > FLOATING_POINT_EPSILON) {\n System.err.printf(\"Weight of edges does not equal weight(): %f vs. %f\", total, weight());\n return false;\n }\n\n // check that it is acyclic\n UF uf = new UF(graph.V());\n for (Edge e : edges()) {\n int v = e.either(), w = e.other(v);\n if (uf.find(v) == uf.find(w)) {\n System.err.println(\"Not a forest\");\n return false;\n }\n uf.union(v, w);\n }\n\n // check that it is a spanning forest\n for (Edge e : graph.edges()) {\n int v = e.either(), w = e.other(v);\n if (uf.find(v) != uf.find(w)) {\n System.err.println(\"Not a spanning forest\");\n return false;\n }\n }\n\n // check that it is a minimal spanning forest (cut optimality conditions)\n for (Edge e : edges()) {\n\n // all edges in MST except e\n uf = new UF(graph.V());\n for (Edge f : mst) {\n int x = f.either(), y = f.other(x);\n if (f != e) uf.union(x, y);\n }\n\n // check that e is min weight edge in crossing cut\n for (Edge f : graph.edges()) {\n int x = f.either(), y = f.other(x);\n if (uf.find(x) != uf.find(y)) {\n if (f.weight() < e.weight()) {\n System.err.println(\"Edge \" + f + \" violates cut optimality conditions\");\n return false;\n }\n }\n }\n\n }\n\n return true;\n }\n\n\n /**\n * Unit tests the {@code KruskalMST} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n In in = new In(args[0]);\n EdgeWeightedGraph G = new EdgeWeightedGraph(in);\n KruskalMST mst = new KruskalMST(G);\n for (Edge e : mst.edges()) {\n StdOut.println(e);\n }\n StdOut.printf(\"%.5f\", mst.weight());\n }\n\n}\n\n", "support_files": ["https://algs4.cs.princeton.edu/43mst/mediumEWG.txt", "https://algs4.cs.princeton.edu/43mst/tinyEWG.txt", "https://algs4.cs.princeton.edu/43mst/largeEWG.txt"], "metadata": {"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"]}} {"question": "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? ", "answer": "/******************************************************************************\n * Compilation: javac KruskalMST.java\n * Execution: java KruskalMST filename.txt\n * Dependencies: EdgeWeightedGraph.java Edge.java Queue.java MinPQ.java\n * UF.java In.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/43mst/tinyEWG.txt\n * https://algs4.cs.princeton.edu/43mst/mediumEWG.txt\n * https://algs4.cs.princeton.edu/43mst/largeEWG.txt\n *\n * Compute a minimum spanning forest using Kruskal's algorithm.\n *\n * % java KruskalMST tinyEWG.txt\n * 0-7 0.16000\n * 2-3 0.17000\n * 1-7 0.19000\n * 0-2 0.26000\n * 5-7 0.28000\n * 4-5 0.35000\n * 6-2 0.40000\n * 1.81000\n *\n * % java KruskalMST mediumEWG.txt\n * 168-231 0.00268\n * 151-208 0.00391\n * 7-157 0.00516\n * 122-205 0.00647\n * 8-152 0.00702\n * 156-219 0.00745\n * 28-198 0.00775\n * 38-126 0.00845\n * 10-123 0.00886\n * ...\n * 10.46351\n *\n ******************************************************************************/\n\nimport java.util.Arrays;\n\n/**\n * The {@code KruskalMST} class represents a data type for computing a\n * minimum spanning tree in an edge-weighted graph.\n * The edge weights can be positive, zero, or negative and need not\n * be distinct. If the graph is not connected, it computes a minimum\n * spanning forest, which is the union of minimum spanning trees\n * in each connected component. The {@code weight()} method returns the\n * weight of a minimum spanning tree and the {@code edges()} method\n * returns its edges.\n *

\n * This implementation uses Kruskal's algorithm and the\n * union-find data type.\n * The constructor takes Θ(E log E) time in\n * the worst case.\n * Each instance method takes Θ(1) time.\n * It uses Θ(E) extra space (not including the graph).\n *

\n * This {@code weight()} method correctly computes the weight of the MST\n * if all arithmetic performed is without floating-point rounding error\n * or arithmetic overflow.\n * This is the case if all edge weights are non-negative integers\n * and the weight of the MST does not exceed 252.\n *

\n * For additional documentation,\n * see Section 4.3 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n * For alternate implementations, see {@link LazyPrimMST}, {@link PrimMST},\n * and {@link BoruvkaMST}.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class KruskalMST {\n private static final double FLOATING_POINT_EPSILON = 1.0E-12;\n\n private double weight; // weight of MST\n private Queue mst = new Queue(); // edges in MST\n\n /**\n * Compute a minimum spanning tree (or forest) of an edge-weighted graph.\n * @param graph the edge-weighted graph\n */\n public KruskalMST(EdgeWeightedGraph graph) {\n\n // create array of edges, sorted by weight\n Edge[] edges = new Edge[graph.E()];\n int t = 0;\n for (Edge e: graph.edges()) {\n edges[t++] = e;\n }\n Arrays.sort(edges);\n\n // run greedy algorithm\n UF uf = new UF(graph.V());\n for (int i = 0; i < graph.E() && mst.size() < graph.V() - 1; i++) {\n Edge e = edges[i];\n int v = e.either();\n int w = e.other(v);\n\n // v-w does not create a cycle\n if (uf.find(v) != uf.find(w)) {\n uf.union(v, w); // merge v and w components\n mst.enqueue(e); // add edge e to mst\n weight += e.weight();\n }\n }\n\n // check optimality conditions\n assert check(graph);\n }\n\n /**\n * Returns the edges in a minimum spanning tree (or forest).\n * @return the edges in a minimum spanning tree (or forest) as\n * an iterable of edges\n */\n public Iterable edges() {\n return mst;\n }\n\n /**\n * Returns the sum of the edge weights in a minimum spanning tree (or forest).\n * @return the sum of the edge weights in a minimum spanning tree (or forest)\n */\n public double weight() {\n return weight;\n }\n\n // check optimality conditions (takes time proportional to E V lg* V)\n private boolean check(EdgeWeightedGraph graph) {\n\n // check total weight\n double total = 0.0;\n for (Edge e : edges()) {\n total += e.weight();\n }\n if (Math.abs(total - weight()) > FLOATING_POINT_EPSILON) {\n System.err.printf(\"Weight of edges does not equal weight(): %f vs. %f\", total, weight());\n return false;\n }\n\n // check that it is acyclic\n UF uf = new UF(graph.V());\n for (Edge e : edges()) {\n int v = e.either(), w = e.other(v);\n if (uf.find(v) == uf.find(w)) {\n System.err.println(\"Not a forest\");\n return false;\n }\n uf.union(v, w);\n }\n\n // check that it is a spanning forest\n for (Edge e : graph.edges()) {\n int v = e.either(), w = e.other(v);\n if (uf.find(v) != uf.find(w)) {\n System.err.println(\"Not a spanning forest\");\n return false;\n }\n }\n\n // check that it is a minimal spanning forest (cut optimality conditions)\n for (Edge e : edges()) {\n\n // all edges in MST except e\n uf = new UF(graph.V());\n for (Edge f : mst) {\n int x = f.either(), y = f.other(x);\n if (f != e) uf.union(x, y);\n }\n\n // check that e is min weight edge in crossing cut\n for (Edge f : graph.edges()) {\n int x = f.either(), y = f.other(x);\n if (uf.find(x) != uf.find(y)) {\n if (f.weight() < e.weight()) {\n System.err.println(\"Edge \" + f + \" violates cut optimality conditions\");\n return false;\n }\n }\n }\n\n }\n\n return true;\n }\n\n\n /**\n * Unit tests the {@code KruskalMST} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n In in = new In(args[0]);\n EdgeWeightedGraph G = new EdgeWeightedGraph(in);\n KruskalMST mst = new KruskalMST(G);\n for (Edge e : mst.edges()) {\n StdOut.println(e);\n }\n StdOut.printf(\"%.5f\", mst.weight());\n }\n\n}\n\n", "support_files": ["https://algs4.cs.princeton.edu/43mst/mediumEWG.txt", "https://algs4.cs.princeton.edu/43mst/tinyEWG.txt", "https://algs4.cs.princeton.edu/43mst/largeEWG.txt"], "metadata": {"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"]}} {"question": "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. ", "answer": "/******************************************************************************\n * Compilation: javac BoruvkaMST.java\n * Execution: java BoruvkaMST filename.txt\n * Dependencies: EdgeWeightedGraph.java Edge.java Bag.java\n * UF.java In.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/43mst/tinyEWG.txt\n * https://algs4.cs.princeton.edu/43mst/mediumEWG.txt\n * https://algs4.cs.princeton.edu/43mst/largeEWG.txt\n *\n * Compute a minimum spanning forest using Boruvka's algorithm.\n *\n * % java BoruvkaMST tinyEWG.txt\n * 0-2 0.26000\n * 6-2 0.40000\n * 5-7 0.28000\n * 4-5 0.35000\n * 2-3 0.17000\n * 1-7 0.19000\n * 0-7 0.16000\n * 1.81000\n *\n ******************************************************************************/\n\n/**\n * The {@code BoruvkaMST} class represents a data type for computing a\n * minimum spanning tree in an edge-weighted graph.\n * The edge weights can be positive, zero, or negative and need not\n * be distinct. If the graph is not connected, it computes a minimum\n * spanning forest, which is the union of minimum spanning trees\n * in each connected component. The {@code weight()} method returns the\n * weight of a minimum spanning tree and the {@code edges()} method\n * returns its edges.\n *

\n * This implementation uses Boruvka's algorithm and the union-find\n * data type.\n * The constructor takes Θ(E log V) time in\n * the worst case, where V is the number of vertices and\n * E is the number of edges.\n * Each instance method takes Θ(1) time.\n * It uses Θ(V) extra space (not including the\n * edge-weighted graph).\n *

\n * This {@code weight()} method correctly computes the weight of the MST\n * if all arithmetic performed is without floating-point rounding error\n * or arithmetic overflow.\n * This is the case if all edge weights are non-negative integers\n * and the weight of the MST does not exceed 252.\n *

\n * For additional documentation,\n * see Section 4.3 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n * For alternate implementations, see {@link LazyPrimMST}, {@link PrimMST},\n * and {@link KruskalMST}.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class BoruvkaMST {\n private static final double FLOATING_POINT_EPSILON = 1.0E-12;\n\n private Bag mst = new Bag(); // edges in MST\n private double weight; // weight of MST\n\n /**\n * Compute a minimum spanning tree (or forest) of an edge-weighted graph.\n * @param graph the edge-weighted graph\n */\n public BoruvkaMST(EdgeWeightedGraph graph) {\n UF uf = new UF(graph.V());\n\n // repeat at most log V times or until we have V-1 edges\n for (int t = 1; t < graph.V() && mst.size() < graph.V() - 1; t = t + t) {\n\n // foreach tree in forest, find closest edge\n // if edge weights are equal, ties are broken in favor of first edge in graph.edges()\n Edge[] closest = new Edge[graph.V()];\n for (Edge e : graph.edges()) {\n int v = e.either(), w = e.other(v);\n int i = uf.find(v), j = uf.find(w);\n if (i == j) continue; // same tree\n if (closest[i] == null || less(e, closest[i])) closest[i] = e;\n if (closest[j] == null || less(e, closest[j])) closest[j] = e;\n }\n\n // add newly discovered edges to MST\n for (int i = 0; i < graph.V(); i++) {\n Edge e = closest[i];\n if (e != null) {\n int v = e.either(), w = e.other(v);\n // don't add the same edge twice\n if (uf.find(v) != uf.find(w)) {\n mst.add(e);\n weight += e.weight();\n uf.union(v, w);\n }\n }\n }\n }\n\n // check optimality conditions\n assert check(graph);\n }\n\n /**\n * Returns the edges in a minimum spanning tree (or forest).\n * @return the edges in a minimum spanning tree (or forest) as\n * an iterable of edges\n */\n public Iterable edges() {\n return mst;\n }\n\n\n /**\n * Returns the sum of the edge weights in a minimum spanning tree (or forest).\n * @return the sum of the edge weights in a minimum spanning tree (or forest)\n */\n public double weight() {\n return weight;\n }\n\n // is the weight of edge e strictly less than that of edge f?\n private static boolean less(Edge e, Edge f) {\n return e.compareTo(f) < 0;\n }\n\n // check optimality conditions (takes time proportional to E V lg* V)\n private boolean check(EdgeWeightedGraph graph) {\n\n // check weight\n double totalWeight = 0.0;\n for (Edge e : edges()) {\n totalWeight += e.weight();\n }\n if (Math.abs(totalWeight - weight()) > FLOATING_POINT_EPSILON) {\n System.err.printf(\"Weight of edges does not equal weight(): %f vs. %f\", totalWeight, weight());\n return false;\n }\n\n // check that it is acyclic\n UF uf = new UF(graph.V());\n for (Edge e : edges()) {\n int v = e.either(), w = e.other(v);\n if (uf.find(v) == uf.find(w)) {\n System.err.println(\"Not a forest\");\n return false;\n }\n uf.union(v, w);\n }\n\n // check that it is a spanning forest\n for (Edge e : graph.edges()) {\n int v = e.either(), w = e.other(v);\n if (uf.find(v) != uf.find(w)) {\n System.err.println(\"Not a spanning forest\");\n return false;\n }\n }\n\n // check that it is a minimal spanning forest (cut optimality conditions)\n for (Edge e : edges()) {\n\n // all edges in MST except e\n uf = new UF(graph.V());\n for (Edge f : mst) {\n int x = f.either(), y = f.other(x);\n if (f != e) uf.union(x, y);\n }\n\n // check that e is min weight edge in crossing cut\n for (Edge f : graph.edges()) {\n int x = f.either(), y = f.other(x);\n if (uf.find(x) != uf.find(y)) {\n if (f.weight() < e.weight()) {\n System.err.println(\"Edge \" + f + \" violates cut optimality conditions\");\n return false;\n }\n }\n }\n\n }\n\n return true;\n }\n\n /**\n * Unit tests the {@code BoruvkaMST} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n In in = new In(args[0]);\n EdgeWeightedGraph graph = new EdgeWeightedGraph(in);\n BoruvkaMST mst = new BoruvkaMST(graph);\n for (Edge e : mst.edges()) {\n StdOut.println(e);\n }\n StdOut.printf(\"%.5f\", mst.weight());\n }\n\n}\n", "support_files": ["https://algs4.cs.princeton.edu/43mst/mediumEWG.txt", "https://algs4.cs.princeton.edu/43mst/tinyEWG.txt", "https://algs4.cs.princeton.edu/43mst/largeEWG.txt"], "metadata": {"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"]}} {"question": "Provide an implementation of toString() for EdgeWeightedDigraph.java. ", "answer": "/******************************************************************************\n * Compilation: javac EdgeWeightedDigraph.java\n * Execution: java EdgeWeightedDigraph digraph.txt\n * Dependencies: Bag.java DirectedEdge.java\n * Data files: https://algs4.cs.princeton.edu/44sp/tinyEWD.txt\n * https://algs4.cs.princeton.edu/44sp/mediumEWD.txt\n * https://algs4.cs.princeton.edu/44sp/largeEWD.txt\n *\n * An edge-weighted digraph, implemented using adjacency lists.\n *\n ******************************************************************************/\n\nimport java.util.NoSuchElementException;\n\n/**\n * The {@code EdgeWeightedDigraph} class represents an edge-weighted\n * digraph of vertices named 0 through V - 1, where each\n * directed edge is of type {@link DirectedEdge} and has a real-valued weight.\n * It supports the following two primary operations: add a directed edge\n * to the digraph and iterate over all edges incident from a given vertex.\n * It also provides methods for returning the indegree or outdegree of a\n * vertex, the number of vertices V in the digraph, and\n * the number of edges E in the digraph.\n * Parallel edges and self-loops are permitted.\n *

\n * This implementation uses an adjacency-lists representation, which\n * is a vertex-indexed array of {@link Bag} objects.\n * It uses Θ(E + V) space, where E is\n * the number of edges and V is the number of vertices.\n * All instance methods take Θ(1) time. (Though, iterating over\n * the edges returned by {@link #adj(int)} takes time proportional\n * to the outdegree of the vertex.)\n * Constructing an empty edge-weighted digraph with V vertices\n * takes Θ(V) time; constructing an edge-weighted digraph\n * with E edges and V vertices takes\n * Θ(E + V) time.\n *

\n * For additional documentation,\n * see Section 4.4 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class EdgeWeightedDigraph {\n private static final String NEWLINE = System.getProperty(\"line.separator\");\n\n private final int V; // number of vertices in this digraph\n private int E; // number of edges in this digraph\n private Bag[] adj; // adj[v] = adjacency list for vertex v\n private int[] indegree; // indegree[v] = indegree of vertex v\n\n /**\n * Initializes an empty edge-weighted digraph with {@code V} vertices and 0 edges.\n *\n * @param V the number of vertices\n * @throws IllegalArgumentException if {@code V < 0}\n */\n public EdgeWeightedDigraph(int V) {\n if (V < 0) throw new IllegalArgumentException(\"Number of vertices in a Digraph must be non-negative\");\n this.V = V;\n this.E = 0;\n this.indegree = new int[V];\n adj = (Bag[]) new Bag[V];\n for (int v = 0; v < V; v++)\n adj[v] = new Bag();\n }\n\n /**\n * Initializes a random edge-weighted digraph with {@code V} vertices and E edges.\n *\n * @param V the number of vertices\n * @param E the number of edges\n * @throws IllegalArgumentException if {@code V < 0}\n * @throws IllegalArgumentException if {@code E < 0}\n */\n public EdgeWeightedDigraph(int V, int E) {\n this(V);\n if (E < 0) throw new IllegalArgumentException(\"Number of edges in a Digraph must be non-negative\");\n for (int i = 0; i < E; i++) {\n int v = StdRandom.uniformInt(V);\n int w = StdRandom.uniformInt(V);\n double weight = 0.01 * StdRandom.uniformInt(100);\n DirectedEdge e = new DirectedEdge(v, w, weight);\n addEdge(e);\n }\n }\n\n /**\n * Initializes an edge-weighted digraph from the specified input stream.\n * The format is the number of vertices V,\n * followed by the number of edges E,\n * followed by E pairs of vertices and edge weights,\n * with each entry separated by whitespace.\n *\n * @param in the input stream\n * @throws IllegalArgumentException if {@code in} is {@code null}\n * @throws IllegalArgumentException if the endpoints of any edge are not in prescribed range\n * @throws IllegalArgumentException if the number of vertices or edges is negative\n */\n public EdgeWeightedDigraph(In in) {\n if (in == null) throw new IllegalArgumentException(\"argument is null\");\n try {\n this.V = in.readInt();\n if (V < 0) throw new IllegalArgumentException(\"number of vertices in a Digraph must be non-negative\");\n indegree = new int[V];\n adj = (Bag[]) new Bag[V];\n for (int v = 0; v < V; v++) {\n adj[v] = new Bag();\n }\n\n int E = in.readInt();\n if (E < 0) throw new IllegalArgumentException(\"Number of edges must be non-negative\");\n for (int i = 0; i < E; i++) {\n int v = in.readInt();\n int w = in.readInt();\n validateVertex(v);\n validateVertex(w);\n double weight = in.readDouble();\n addEdge(new DirectedEdge(v, w, weight));\n }\n }\n catch (NoSuchElementException e) {\n throw new IllegalArgumentException(\"invalid input format in EdgeWeightedDigraph constructor\", e);\n }\n }\n\n /**\n * Initializes a new edge-weighted digraph that is a deep copy of {@code G}.\n *\n * @param G the edge-weighted digraph to copy\n */\n public EdgeWeightedDigraph(EdgeWeightedDigraph G) {\n this(G.V());\n this.E = G.E();\n for (int v = 0; v < G.V(); v++)\n this.indegree[v] = G.indegree(v);\n for (int v = 0; v < G.V(); v++) {\n // reverse so that adjacency list is in same order as original\n Stack reverse = new Stack();\n for (DirectedEdge e : G.adj[v]) {\n reverse.push(e);\n }\n for (DirectedEdge e : reverse) {\n adj[v].add(e);\n }\n }\n }\n\n /**\n * Returns the number of vertices in this edge-weighted digraph.\n *\n * @return the number of vertices in this edge-weighted digraph\n */\n public int V() {\n return V;\n }\n\n /**\n * Returns the number of edges in this edge-weighted digraph.\n *\n * @return the number of edges in this edge-weighted digraph\n */\n public int E() {\n return E;\n }\n\n // throw an IllegalArgumentException unless {@code 0 <= v < V}\n private void validateVertex(int v) {\n if (v < 0 || v >= V)\n throw new IllegalArgumentException(\"vertex \" + v + \" is not between 0 and \" + (V-1));\n }\n\n /**\n * Adds the directed edge {@code e} to this edge-weighted digraph.\n *\n * @param e the edge\n * @throws IllegalArgumentException unless endpoints of edge are between {@code 0}\n * and {@code V-1}\n */\n public void addEdge(DirectedEdge e) {\n int v = e.from();\n int w = e.to();\n validateVertex(v);\n validateVertex(w);\n adj[v].add(e);\n indegree[w]++;\n E++;\n }\n\n\n /**\n * Returns the directed edges incident from vertex {@code v}.\n *\n * @param v the vertex\n * @return the directed edges incident from vertex {@code v} as an Iterable\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public Iterable adj(int v) {\n validateVertex(v);\n return adj[v];\n }\n\n /**\n * Returns the number of directed edges incident from vertex {@code v}.\n * This is known as the outdegree of vertex {@code v}.\n *\n * @param v the vertex\n * @return the outdegree of vertex {@code v}\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public int outdegree(int v) {\n validateVertex(v);\n return adj[v].size();\n }\n\n /**\n * Returns the number of directed edges incident to vertex {@code v}.\n * This is known as the indegree of vertex {@code v}.\n *\n * @param v the vertex\n * @return the indegree of vertex {@code v}\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public int indegree(int v) {\n validateVertex(v);\n return indegree[v];\n }\n\n /**\n * Returns all directed edges in this edge-weighted digraph.\n * To iterate over the edges in this edge-weighted digraph, use foreach notation:\n * {@code for (DirectedEdge e : G.edges())}.\n *\n * @return all edges in this edge-weighted digraph, as an iterable\n */\n public Iterable edges() {\n Bag list = new Bag();\n for (int v = 0; v < V; v++) {\n for (DirectedEdge e : adj(v)) {\n list.add(e);\n }\n }\n return list;\n }\n\n /**\n * Returns a string representation of this edge-weighted digraph.\n *\n * @return the number of vertices V, followed by the number of edges E,\n * followed by the V adjacency lists of edges\n */\n public String toString() {\n StringBuilder s = new StringBuilder();\n s.append(V + \" \" + E + NEWLINE);\n for (int v = 0; v < V; v++) {\n s.append(v + \": \");\n for (DirectedEdge e : adj[v]) {\n s.append(e + \" \");\n }\n s.append(NEWLINE);\n }\n return s.toString();\n }\n\n /**\n * Returns a string representation of this edge-weighted digraph in DOT format,\n * suitable for visualization with Graphviz.\n *\n * To visualize the graph, install Graphviz (e.g., \"brew install graphviz\").\n * Then use one of the graph visualization tools\n * - dot (hierarchical or layer drawing)\n * - neato (spring model)\n * - fdp (force-directed placement)\n * - sfdp (scalable force-directed placement)\n * - twopi (radial layout)\n *\n * For example, the following commands will create graph drawings in SVG\n * and PDF formats\n * - dot input.dot -Tsvg -o output.svg\n * - dot input.dot -Tpdf -o output.pdf\n *\n * To change the digraph attributes (e.g., vertex and edge shapes, arrows, colors)\n * in the DOT format, see https://graphviz.org/doc/info/lang.html\n *\n * @return a string representation of this edge-weighted digraph in DOT format\n */\n public String toDot() {\n StringBuilder s = new StringBuilder();\n s.append(\"digraph {\" + NEWLINE);\n s.append(\"node[shape=circle, style=filled, fixedsize=true, width=0.3, fontsize=\\\"10pt\\\"]\" + NEWLINE);\n s.append(\"edge[arrowhead=normal, fontsize=\\\"9pt\\\"]\" + NEWLINE);\n for (int v = 0; v < V; v++) {\n for (DirectedEdge e : adj[v]) {\n int w = e.to();\n s.append(v + \" -> \" + w + \" [label=\\\"\" + e.weight() + \"\\\"]\" + NEWLINE);\n }\n }\n s.append(\"}\" + NEWLINE);\n return s.toString();\n }\n\n /**\n * Unit tests the {@code EdgeWeightedDigraph} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n In in = new In(args[0]);\n EdgeWeightedDigraph G = new EdgeWeightedDigraph(in);\n StdOut.println(G);\n }\n\n}\n", "support_files": ["https://algs4.cs.princeton.edu/44sp/largeEWD.txt", "https://algs4.cs.princeton.edu/44sp/tinyEWD.txt", "https://algs4.cs.princeton.edu/44sp/mediumEWD.txt"], "metadata": {"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"]}} {"question": "Adapt the Topological classes from Section 4.2 to use the EdgeweightedDigraph and DirectedEdge APIs of this section, thus implementing Topological.java.", "answer": "/******************************************************************************\n * Compilation: javac Topological.java\n * Execution: java Topological filename.txt delimiter\n * Dependencies: Digraph.java DepthFirstOrder.java DirectedCycle.java\n * EdgeWeightedDigraph.java EdgeWeightedDirectedCycle.java\n * SymbolDigraph.java\n * Data files: https://algs4.cs.princeton.edu/42digraph/jobs.txt\n *\n * Compute topological ordering of a DAG or edge-weighted DAG.\n * Runs in O(E + V) time.\n *\n * % java Topological jobs.txt \"/\"\n * Calculus\n * Linear Algebra\n * Introduction to CS\n * Advanced Programming\n * Algorithms\n * Theoretical CS\n * Artificial Intelligence\n * Robotics\n * Machine Learning\n * Neural Networks\n * Databases\n * Scientific Computing\n * Computational Biology\n *\n ******************************************************************************/\n\n/**\n * The {@code Topological} class represents a data type for\n * determining a topological order of a directed acyclic graph (DAG).\n * A digraph has a topological order if and only if it is a DAG.\n * The hasOrder operation determines whether the digraph has\n * a topological order, and if so, the order operation\n * returns one.\n *

\n * This implementation uses depth-first search.\n * The constructor takes Θ(V + E) time in the\n * worst case, where V is the number of vertices and E\n * is the number of edges.\n * Each instance method takes Θ(1) time.\n * It uses Θ(V) extra space (not including the digraph).\n *

\n * See {@link DirectedCycle}, {@link DirectedCycleX}, and\n * {@link EdgeWeightedDirectedCycle} for computing a directed cycle\n * if the digraph is not a DAG.\n * See {@link TopologicalX} for a nonrecursive, queue-based algorithm\n * for computing a topological order of a DAG.\n *

\n * For additional documentation,\n * see Section 4.2 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class Topological {\n private Iterable order; // topological order\n private int[] rank; // rank[v] = rank of vertex v in order\n\n /**\n * Determines whether the {@code digraph} has a topological order and, if so,\n * finds such a topological order.\n * @param digraph the digraph\n */\n public Topological(Digraph digraph) {\n DirectedCycle finder = new DirectedCycle(digraph);\n if (!finder.hasCycle()) {\n DepthFirstOrder dfs = new DepthFirstOrder(digraph);\n order = dfs.reversePost();\n rank = new int[digraph.V()];\n int i = 0;\n for (int v : order)\n rank[v] = i++;\n }\n }\n\n /**\n * Determines whether the edge-weighted digraph {@code digraph} has a topological\n * order and, if so, finds such an order.\n * @param digraph the edge-weighted digraph\n */\n public Topological(EdgeWeightedDigraph digraph) {\n EdgeWeightedDirectedCycle finder = new EdgeWeightedDirectedCycle(digraph);\n if (!finder.hasCycle()) {\n DepthFirstOrder dfs = new DepthFirstOrder(digraph);\n order = dfs.reversePost();\n rank = new int[digraph.V()];\n int i = 0;\n for (int v : order)\n rank[v] = i++;\n }\n }\n\n /**\n * Returns a topological order if the digraph has a topological order,\n * and {@code null} otherwise.\n * @return a topological order of the vertices (as an iterable) if the\n * digraph has a topological order (or equivalently, if the digraph is a DAG),\n * and {@code null} otherwise\n */\n public Iterable order() {\n return order;\n }\n\n /**\n * Does the digraph have a topological order?\n * @return {@code true} if the digraph has a topological order (or equivalently,\n * if the digraph is a DAG), and {@code false} otherwise\n */\n public boolean hasOrder() {\n return order != null;\n }\n\n /**\n * Does the digraph have a topological order?\n * @return {@code true} if the digraph has a topological order (or equivalently,\n * if the digraph is a DAG), and {@code false} otherwise\n * @deprecated Replaced by {@link #hasOrder()}.\n */\n @Deprecated\n public boolean isDAG() {\n return hasOrder();\n }\n\n /**\n * The rank of vertex {@code v} in the topological order;\n * -1 if the digraph is not a DAG\n *\n * @param v the vertex\n * @return the position of vertex {@code v} in a topological order\n * of the digraph; -1 if the digraph is not a DAG\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public int rank(int v) {\n validateVertex(v);\n if (hasOrder()) return rank[v];\n else return -1;\n }\n\n // throw an IllegalArgumentException unless {@code 0 <= v < V}\n private void validateVertex(int v) {\n int V = rank.length;\n if (v < 0 || v >= V)\n throw new IllegalArgumentException(\"vertex \" + v + \" is not between 0 and \" + (V-1));\n }\n\n /**\n * Unit tests the {@code Topological} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n String filename = args[0];\n String delimiter = args[1];\n SymbolDigraph sg = new SymbolDigraph(filename, delimiter);\n Topological topological = new Topological(sg.digraph());\n for (int v : topological.order()) {\n StdOut.println(sg.nameOf(v));\n }\n }\n\n}\n", "support_files": ["https://algs4.cs.princeton.edu/42digraph/jobs.txt"], "metadata": {"number": "4.4.12", "code_execution": true, "url": "https://algs4.cs.princeton.edu/44sp/Topological.java", "params": ["jobs.txt \"/\""], "dependencies": ["DepthFirstOrder.java", "Digraph.java", "DirectedCycle.java", "EdgeWeightedDigraph.java", "EdgeWeightedDirectedCycle.java"]}} {"question": "Longest paths in DAGs. Develop an implementation AcyclicLP.java that can solve the longest-paths problem in edge-weighted DAGs.", "answer": "/******************************************************************************\n * Compilation: javac AcyclicLP.java\n * Execution: java AcyclicLP V E\n * Dependencies: EdgeWeightedDigraph.java DirectedEdge.java Topological.java\n * Data files: https://algs4.cs.princeton.edu/44sp/tinyEWDAG.txt\n *\n * Computes longest paths in an edge-weighted acyclic digraph.\n *\n * Remark: should probably check that graph is a DAG before running\n *\n * % java AcyclicLP tinyEWDAG.txt 5\n * 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\n * 5 to 1 (0.32) 5->1 0.32\n * 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\n * 5 to 3 (0.61) 5->1 0.32 1->3 0.29\n * 5 to 4 (2.06) 5->1 0.32 1->3 0.29 3->6 0.52 6->4 0.93\n * 5 to 5 (0.00)\n * 5 to 6 (1.13) 5->1 0.32 1->3 0.29 3->6 0.52\n * 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\n *\n ******************************************************************************/\n\n/**\n * The {@code AcyclicLP} class represents a data type for solving the\n * single-source longest paths problem in edge-weighted directed\n * acyclic graphs (DAGs). The edge weights can be positive, negative, or zero.\n *

\n * This implementation uses a topological-sort based algorithm.\n * The constructor takes Θ(V + E) time in the\n * worst case, where V is the number of vertices and\n * E is the number of edges.\n * Each instance method takes Θ(1) time.\n * It uses Θ(V) extra space (not including the\n * edge-weighted digraph).\n *

\n * This correctly computes longest paths if all arithmetic performed is\n * without floating-point rounding error or arithmetic overflow.\n * This is the case if all edge weights are integers and if none of the\n * intermediate results exceeds 252. Since all intermediate\n * results are sums of edge weights, they are bounded by V C,\n * where V is the number of vertices and C is the maximum\n * absolute value of any edge weight.\n *

\n * For additional documentation,\n * see Section 4.4 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class AcyclicLP {\n private double[] distTo; // distTo[v] = distance of longest s->v path\n private DirectedEdge[] edgeTo; // edgeTo[v] = last edge on longest s->v path\n\n /**\n * Computes a longest paths tree from {@code s} to every other vertex in\n * the directed acyclic graph {@code digraph}.\n * @param digraph the acyclic digraph\n * @param s the source vertex\n * @throws IllegalArgumentException if the digraph is not acyclic\n * @throws IllegalArgumentException unless {@code 0 <= s < V}\n */\n public AcyclicLP(EdgeWeightedDigraph digraph, int s) {\n distTo = new double[digraph.V()];\n edgeTo = new DirectedEdge[digraph.V()];\n\n validateVertex(s);\n\n for (int v = 0; v < digraph.V(); v++)\n distTo[v] = Double.NEGATIVE_INFINITY;\n distTo[s] = 0.0;\n\n // relax vertices in topological order\n Topological topological = new Topological(digraph);\n if (!topological.hasOrder())\n throw new IllegalArgumentException(\"Digraph is not acyclic.\");\n for (int v : topological.order()) {\n for (DirectedEdge e : digraph.adj(v))\n relax(e);\n }\n }\n\n // relax edge e, but update if you find a *longer* path\n private void relax(DirectedEdge e) {\n int v = e.from(), w = e.to();\n if (distTo[w] < distTo[v] + e.weight()) {\n distTo[w] = distTo[v] + e.weight();\n edgeTo[w] = e;\n }\n }\n\n /**\n * Returns the length of a longest path from the source vertex {@code s} to vertex {@code v}.\n * @param v the destination vertex\n * @return the length of a longest path from the source vertex {@code s} to vertex {@code v};\n * {@code Double.NEGATIVE_INFINITY} if no such path\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public double distTo(int v) {\n validateVertex(v);\n return distTo[v];\n }\n\n /**\n * Is there a path from the source vertex {@code s} to vertex {@code v}?\n * @param v the destination vertex\n * @return {@code true} if there is a path from the source vertex\n * {@code s} to vertex {@code v}, and {@code false} otherwise\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public boolean hasPathTo(int v) {\n validateVertex(v);\n return distTo[v] > Double.NEGATIVE_INFINITY;\n }\n\n /**\n * Returns a longest path from the source vertex {@code s} to vertex {@code v}.\n * @param v the destination vertex\n * @return a longest path from the source vertex {@code s} to vertex {@code v}\n * as an iterable of edges, and {@code null} if no such path\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public Iterable pathTo(int v) {\n validateVertex(v);\n if (!hasPathTo(v)) return null;\n Stack path = new Stack();\n for (DirectedEdge e = edgeTo[v]; e != null; e = edgeTo[e.from()]) {\n path.push(e);\n }\n return path;\n }\n\n // throw an IllegalArgumentException unless {@code 0 <= v < V}\n private void validateVertex(int v) {\n int V = distTo.length;\n if (v < 0 || v >= V)\n throw new IllegalArgumentException(\"vertex \" + v + \" is not between 0 and \" + (V-1));\n }\n\n /**\n * Unit tests the {@code AcyclicLP} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n In in = new In(args[0]);\n int s = Integer.parseInt(args[1]);\n EdgeWeightedDigraph digraph = new EdgeWeightedDigraph(in);\n\n AcyclicLP lp = new AcyclicLP(digraph, s);\n\n for (int v = 0; v < digraph.V(); v++) {\n if (lp.hasPathTo(v)) {\n StdOut.printf(\"%d to %d (%.2f) \", s, v, lp.distTo(v));\n for (DirectedEdge e : lp.pathTo(v)) {\n StdOut.print(e + \" \");\n }\n StdOut.println();\n }\n else {\n StdOut.printf(\"%d to %d no path\", s, v);\n }\n }\n }\n}\n", "support_files": ["https://algs4.cs.princeton.edu/44sp/tinyEWDAG.txt"], "metadata": {"number": "4.4.28", "code_execution": true, "url": "https://algs4.cs.princeton.edu/44sp/AcyclicLP.java", "params": ["tinyEWDAG.txt 5"], "dependencies": ["DirectedEdge.java", "EdgeWeightedDigraph.java", "In.java", "Stack.java", "StdOut.java", "Topological.java"]}} {"question": "Give the value of each of the following expressions:\na. ( 0 + 15 ) / 2\nb. 2.0e-6 * 100000000.1\nc. true && false || true && true", "answer": "1.1.1\na) 7\nb) 200.0000002\nc) true\n", "support_files": [], "metadata": {"number": "1.1.1", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Exercise", "code_execution": false}} {"question": "Give the type and value of each of the following expressions:\na. (1 + 2.236)/2\nb. 1 + 2 + 3 + 4.0\nc. 4.1 >= 4\nd. 1 + 2 + \"3\"", "answer": "1.1.2\na) 1.618 -> double\nb) 10.0 -> double\nc) true -> boolean\nd) 33 -> String\n", "support_files": [], "metadata": {"number": "1.1.2", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Exercise", "code_execution": false}} {"question": "What (if anything) is wrong with each of the following statements?\na. if (a > b) then c = 0;\nb. if a > b { c = 0; }\nc. if (a > b) c = 0;\nd. if (a > b) c = 0 else b = 0;", "answer": "1.1.4\na) No such keyword as \"then\" in Java language\nb) Missing Parentheses on if conditional\nc) Nothing wrong\nd) Missing semicolon after the \"then\" clause\n", "support_files": [], "metadata": {"number": "1.1.4", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Exercise", "code_execution": false}} {"question": "What does the following program print?\nint f = 0; \nint g = 1; \nfor (int i = 0; i <= 15; i++) \n{\n StdOut.println(f);\n f = f + g;\n g = f - g; \n}", "answer": "1.1.6\n\n0\n1\n1\n2\n3\n5\n8\n13\n21\n34\n55\n89\n144\n233\n377\n610\n", "support_files": [], "metadata": {"number": "1.1.6", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Exercise", "code_execution": false}} {"question": "Give the value printed by each of the following code fragments:\na. double t = 9.0;\n while (Math.abs(t - 9.0/t) > .001)\n t = (9.0/t + t) / 2.0;\n StdOut.printf(\"%.5f\\n\", t);\nb. int sum = 0;\n for (int i = 1; i < 1000; i++)\n for (int j = 0; j < i; j++)\n sum++;\n StdOut.println(sum);\nc. int sum = 0;\n for (int i = 1; i < 1000; i *= 2)\n for (int j = 0; j < 1000; j++)\n sum++;\n StdOut.println(sum);", "answer": "1.1.7\na) 3.00009\nb) 499500\nc) 10000\n", "support_files": [], "metadata": {"number": "1.1.7", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Exercise", "code_execution": false}} {"question": "What do each of the following print?\na. System.out.println('b');\nb. System.out.println('b' + 'c');\nc. System.out.println((char) ('a' + 4));\nExplain each outcome.", "answer": "1.1.8\na) b -> converts the char \"b\" to String and prints it\nb) 197 -> sums the char codes of \"b\" and \"c\", converts to String and prints it\nc) e -> sums the char code of \"a\" with 4, converts it to char and prints it\n", "support_files": [], "metadata": {"number": "1.1.8", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Exercise", "code_execution": false}} {"question": "What is wrong with the following code fragment?\nint[] a; \nfor (int i = 0; i < 10; i++)\n a[i] = i * i;", "answer": "1.1.10\nThe array was not initialized and will generate a compile-time error.\n", "support_files": [], "metadata": {"number": "1.1.10", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Exercise", "code_execution": false}} {"question": "What does the following code fragment print?\nint[] a = new int[10]; \nfor (int i = 0; i < 10; i++)\n a[i] = 9 - i; \nfor (int i = 0; i < 10; i++)\n a[i] = a[a[i]]; \nfor (int i = 0; i < 10; i++)\n System.out.println(a[i]);", "answer": "1.1.12\n\n0\n1\n2\n3\n4\n4\n3\n2\n1\n0\n", "support_files": [], "metadata": {"number": "1.1.12", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Exercise", "code_execution": false}} {"question": "Give the value of exR1(6):\npublic static String exR1(int n) \n{\n if (n <= 0) return \"\";\n return exR1(n-3) + n + exR1(n-2) + n; \n}", "answer": "1.1.16\n\n311361142246\n", "support_files": [], "metadata": {"number": "1.1.16", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Exercise", "code_execution": false}} {"question": "Criticize the following recursive function:\npublic static String exR2(int n) \n{\n String s = exR2(n-3) + n + exR2(n-2) + n;\n if (n <= 0) return \"\";\n return s; \n}", "answer": "1.1.17\nThe function never stops because it keeps calling itself on the first line, until a StackOverflowError occurs.\n", "support_files": [], "metadata": {"number": "1.1.17", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Exercise", "code_execution": false}} {"question": "Consider the following recursive function:\npublic static int mystery(int a, int b) \n{\n if (b == 0) return 0;\n if (b % 2 == 0) return mystery(a+a, b/2);\n return mystery(a+a, b/2) + a; \n}\nWhat 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.", "answer": "1.1.18\n\nmystery(2,25) is equal to 50\nmystery(3,11) is equal to 33\nmystery(a,b) computes a * b\n\nmystery2(2,25) is equal to 33554432\nmystery2(3,11) is equal to 177147\nmystery2(a,b) computes a^b\n", "support_files": [], "metadata": {"number": "1.1.18", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Exercise", "code_execution": false}} {"question": "Run the following program on your computer:\npublic class Fibonacci \n{\n public static long F(int N)\n {\n if (N == 0) return 0;\n if (N == 1) return 1;\n return F(N-1) + F(N-2);\n }\n public static void main(String[] args)\n {\n for (int N = 0; N < 100; N++)\n StdOut.println(N + \" \" + F(N));\n } \n}\nWhat 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.", "answer": "// Exercise19.java\npackage chapter1.section1;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento\n */\n// Thanks to pmfer2016 (https://github.com/pmfer2016) for reporting that the int type is not enough for\n// holding all the Fibonacci values.\n// https://github.com/reneargento/algorithms-sedgewick-wayne/issues/283\npublic class Exercise19 {\n\n public static void main(String[] args) {\n//\t\tfor (int n = 0; n < 90; n++) {\n//\t\t\tStdOut.println(n + \" - \" + F(n));\n//\t\t}\n for (int n = 0; n < 90; n++) {\n long[] values;\n\n if (n == 0 || n == 1) {\n values = new long[2];\n } else {\n values = new long[n + 1];\n }\n\n values[0] = 0;\n values[1] = 1;\n StdOut.println(n + \": \" + enhancedF(n, values));\n }\n }\n\n private static int F(int n) {\n if (n == 0) return 0;\n if (n == 1) return 1;\n return F(n - 1) + F(n - 2);\n }\n\n private static long enhancedF(int n, long[] values) {\n if (n == 0) return values[0];\n if (n == 1) return values[1];\n\n for (int i = 2; i <= n; i++) {\n values[i] = values[i - 2] + values[i - 1];\n }\n return values[n];\n }\n}\n\nAdditional notes/results:\n1.1.19\n\nThe largest value of N that takes less than 1 hour to compute is 51.\n", "support_files": [], "metadata": {"number": "1.1.19", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Exercise", "code_execution": false}} {"question": "Use mathematical induction to prove that Euclid’s algorithm computes the greatest common divisor of any pair of nonnegative integers p and q.", "answer": "Euclid's algorithm is correct because the invariant gcd(p, q) = gcd(q, p % q) holds at every recursive step.\n\nLet p = aq + r, where r = p % q and 0 <= r < q. Any integer d that divides both p and q also divides r = p - aq. Conversely, any integer d that divides both q and r also divides p = aq + r. Therefore the common divisors of (p, q) and (q, r) are identical, so their greatest common divisor is identical.\n\nInduct on the second argument q. The base case is q = 0, where the algorithm returns p, and gcd(p, 0) = p. For q > 0, the algorithm replaces (p, q) with (q, p % q). The second argument strictly decreases because p % q < q, so by the induction hypothesis the recursive call returns gcd(q, p % q), which equals gcd(p, q) by the invariant above.\n", "support_files": [], "metadata": {"number": "1.1.25", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Exercise", "code_execution": false}} {"question": "Binomial distribution. Estimate the number of recursive calls that would be used by the code\npublic static double binomial(int N, int k, double p) \n{\n if ((N == 0) || (k < 0)) return 1.0;\n return (1.0 - p)*binomial(N-1, k) + p*binomial(N-1, k-1); \n}\nto compute binomial(100, 50). Develop a better implementation that is based on saving computed values in an array.", "answer": "The plain recursive implementation makes an enormous number of calls because it recomputes the same subproblems. For the code as written, the call count T(N, k) satisfies\n\nT(N, k) = 1 + T(N - 1, k) + T(N - 1, k - 1), with base cases T(0, k) = 1 and T(N, k < 0) = 1.\n\nFor binomial(100, 50), this is 1,566,368,110,549,409,660,193,893,148,231 calls, about 1.57e30.\n\nA memoized implementation stores each computed value in a two-dimensional array:\n\n```java\npublic static double binomial(int n, int k, double p) {\n double[][] memo = new double[n + 1][k + 1];\n boolean[][] seen = new boolean[n + 1][k + 1];\n return binomial(n, k, p, memo, seen);\n}\n\nprivate static double binomial(int n, int k, double p, double[][] memo, boolean[][] seen) {\n if (n == 0 && k == 0) {\n return 1.0;\n }\n if (n < 0 || k < 0) {\n return 0.0;\n }\n if (k >= memo[0].length) {\n return 0.0;\n }\n if (!seen[n][k]) {\n memo[n][k] = (1.0 - p) * binomial(n - 1, k, p, memo, seen)\n + p * binomial(n - 1, k - 1, p, memo, seen);\n seen[n][k] = true;\n }\n return memo[n][k];\n}\n```\n\nThis reduces the number of distinct computed states to O(Nk).\n", "support_files": [], "metadata": {"number": "1.1.27", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Creative Problem", "code_execution": false}} {"question": "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.\n- Print the maximum and minimum numbers.\n- Print the median of the numbers.\n- Print the k th smallest value, for k less than 100.\n- Print the sum of the squares of the numbers.\n- Print the average of the N numbers.\n- Print the percentage of numbers greater than the average.\n- Print the N numbers in increasing order.\n- Print the N numbers in random order.", "answer": "1.1.34 - Filtering\n\nPrint the maximum and minimum numbers -> Could be implemented as a filter\nPrint the median of the numbers -> Requires saving all values\nPrint the Kth smallest value, for K less than 100 -> Could be implemented as a filter with an array of size K\nPrint the sum of the squares of the numbers -> Could be implemented as a filter\nPrint the average of the N numbers -> Could be implemented as a filter\nPrint the percentage of numbers greater than the average -> Requires saving all values\nPrint the N numbers in increasing order -> Requires saving all values\nPrint the N numbers in random order -> Requires saving all values\n\nThanks to imyuewu (https://github.com/imyuewu) for suggesting a correction for the Kth smallest value case.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/175\n", "support_files": [], "metadata": {"number": "1.1.34", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Creative Problem", "code_execution": false}} {"question": "Dice simulation. The following code computes the exact probability distribution for the sum of two dice:\nint SIDES = 6; \ndouble[] dist = new double[2*SIDES+1]; \nfor (int i = 1; i <= SIDES; i++)\n for (int j = 1; j <= SIDES; j++)\n dist[i+j] += 1.0;\nfor (int k = 2; k <= 2*SIDES; k++)\n dist[k] /= 36.0; \nThe 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?", "answer": "1.1.35 - Dice simulation\n\nN has to be 6.000.000 before my empirical results match the exact results to three decimal places.\n", "support_files": [], "metadata": {"number": "1.1.35", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Experiment", "code_execution": false}} {"question": "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.", "answer": "`BruteForceSearch` should time linear search on the unsorted whitelist and binary search on a sorted copy of the same whitelist, using every key from `largeT.txt`.\n\n```java\nimport edu.princeton.cs.algs4.BinarySearch;\nimport edu.princeton.cs.algs4.In;\nimport edu.princeton.cs.algs4.StdOut;\nimport edu.princeton.cs.algs4.Stopwatch;\nimport java.util.Arrays;\n\npublic class BruteForceSearch {\n private static int bruteForceRank(int key, int[] a) {\n for (int i = 0; i < a.length; i++) {\n if (a[i] == key) return i;\n }\n return -1;\n }\n\n public static void main(String[] args) {\n int[] whitelist = new In(args[0]).readAllInts();\n int[] keys = new In(args[1]).readAllInts();\n\n Stopwatch bruteTimer = new Stopwatch();\n int bruteMisses = 0;\n for (int key : keys) {\n if (bruteForceRank(key, whitelist) == -1) bruteMisses++;\n }\n double bruteTime = bruteTimer.elapsedTime();\n\n int[] sorted = whitelist.clone();\n Arrays.sort(sorted);\n Stopwatch binaryTimer = new Stopwatch();\n int binaryMisses = 0;\n for (int key : keys) {\n if (BinarySearch.indexOf(sorted, key) == -1) binaryMisses++;\n }\n double binaryTime = binaryTimer.elapsedTime();\n\n StdOut.printf(\"brute force: %d misses, %.3f seconds\\n\", bruteMisses, bruteTime);\n StdOut.printf(\"binary search: %d misses, %.3f seconds\\n\", binaryMisses, binaryTime);\n }\n}\n```", "support_files": [], "metadata": {"number": "1.1.38", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.1, "section_title": "Basic Programming Model", "type": "Experiment", "code_execution": false}} {"question": "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.", "answer": "package chapter1.section2;\n\nimport edu.princeton.cs.algs4.Point2D;\nimport edu.princeton.cs.algs4.StdDraw;\nimport edu.princeton.cs.algs4.StdOut;\nimport edu.princeton.cs.algs4.StdRandom;\n\n/**\n * Created by Rene Argento\n */\n// Thanks to thiendao1407 (https://github.com/thiendao1407) for suggesting a correct solution to this exercise:\n// https://github.com/reneargento/algorithms-sedgewick-wayne/issues/75\npublic class Exercise1 {\n\n public static void main(String[] args) {\n int n = Integer.parseInt(args[0]); // 10\n\n Point2D[] points = new Point2D[n];\n drawAndCreatePoints(points);\n\n StdOut.printf(\"The shortest distance is: %.3f\", calculateShortestDistance(points));\n }\n\n private static void drawAndCreatePoints(Point2D[] points) {\n StdDraw.setCanvasSize(1024, 512);\n StdDraw.setPenRadius(.015);\n StdDraw.setXscale(0, 1);\n StdDraw.setYscale(0, 1);\n\n for (int i = 0; i < points.length; i++) {\n double pointX = StdRandom.uniform();\n double pointY = StdRandom.uniform();\n\n Point2D point = new Point2D(pointX, pointY);\n StdDraw.point(point.x(), point.y()); //The exercise doesn't require drawing, but it adds a nice touch\n\n points[i] = point;\n }\n }\n\n private static double calculateShortestDistance(Point2D[] points) {\n double shortestDistance = Double.MAX_VALUE;\n double currentDistance;\n\n for (int i = 0; i < points.length - 1; i++) {\n for (int j = i + 1; j < points.length; j++) {\n currentDistance = points[i].distanceTo(points[j]);\n\n if (currentDistance < shortestDistance) {\n shortestDistance = currentDistance;\n }\n }\n }\n return shortestDistance;\n }\n}\n", "support_files": [], "metadata": {"number": "1.2.1", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.2, "section_title": "Data Abstraction", "type": "Exercise", "code_execution": false}} {"question": "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.", "answer": "package chapter1.section2;\n\nimport edu.princeton.cs.algs4.Interval1D;\nimport edu.princeton.cs.algs4.StdIn;\nimport edu.princeton.cs.algs4.StdOut;\n\npublic class Exercise2 {\n public static void main(String[] args) {\n int n = Integer.parseInt(args[0]);\n Interval1D[] intervals = new Interval1D[n];\n\n for (int i = 0; i < n; i++) {\n double left = StdIn.readDouble();\n double right = StdIn.readDouble();\n if (right < left) {\n double temp = left;\n left = right;\n right = temp;\n }\n intervals[i] = new Interval1D(left, right);\n }\n\n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n if (intervals[i].intersects(intervals[j])) {\n StdOut.println(intervals[i] + \" intersects \" + intervals[j]);\n }\n }\n }\n }\n}\n", "support_files": [], "metadata": {"number": "1.2.2", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.2, "section_title": "Data Abstraction", "type": "Exercise", "code_execution": false}} {"question": "What does the following code fragment print?\nString string1 = \"hello\"; \nString string2 = string1; \nstring1 = \"world\"; \nStdOut.println(string1); \nStdOut.println(string2);", "answer": "1.2.4\nPrints:\n\nworld\nhello\n", "support_files": [], "metadata": {"number": "1.2.4", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.2, "section_title": "Data Abstraction", "type": "Exercise", "code_execution": false}} {"question": "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.", "answer": "package chapter1.section2;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento\n */\npublic class Exercise6 {\n\n public static void main(String[] args) {\n String s1 = \"abc\";\n String t1 = \"def\";\n\n StdOut.println(\"Is circular Shift 1: \" + isCircularShift(s1, t1) + \" Expected: false\");\n\n String s2 = \"rene\";\n String t2 = \"nere\";\n\n StdOut.println(\"Is circular Shift 2: \" + isCircularShift(s2, t2) + \" Expected: true\");\n }\n\n //One liner solution - does not safe check for null values\n private static boolean isCircularShift(String s, String t) {\n return s.length() == t.length() && (s + s).contains(t);\n }\n}\n", "support_files": [], "metadata": {"number": "1.2.6", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.2, "section_title": "Data Abstraction", "type": "Exercise", "code_execution": false}} {"question": "What does the following recursive function return?\npublic static String mystery(String s) \n{\n int N = s.length();\n if (N <= 1) return s;\n String a = s.substring(0, N/2);\n String b = s.substring(N/2, N);\n return mystery(b) + mystery(a); \n}", "answer": "1.2.7\nReturns the reverse of the provided String.\nExample: mystery(\"abcde\") returns edcba\n", "support_files": [], "metadata": {"number": "1.2.7", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.2, "section_title": "Data Abstraction", "type": "Exercise", "code_execution": false}} {"question": "Suppose that a[] and b[] are each integer arrays consisting of millions of integers. What does the follow code do? Is it reasonably efficient?\nint[] t = a; a = b; b = t;", "answer": "1.2.8\nThe code swaps a[] and b[] values.\nIt is very efficient because it only changes the references, instead of copying millions of elements, \nwith a complexity of O(1).\n", "support_files": [], "metadata": {"number": "1.2.8", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.2, "section_title": "Data Abstraction", "type": "Exercise", "code_execution": false}} {"question": "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.", "answer": "```java\nimport edu.princeton.cs.algs4.StdDraw;\n\npublic class VisualCounter {\n private final int maxOperations;\n private final int maxAbsoluteValue;\n private int operations;\n private int count;\n\n public VisualCounter(int n, int max) {\n maxOperations = n;\n maxAbsoluteValue = Math.abs(max);\n StdDraw.setXscale(0, n + 1);\n StdDraw.setYscale(-maxAbsoluteValue - 1, maxAbsoluteValue + 1);\n StdDraw.setPenRadius(0.01);\n plot();\n }\n\n public void increment() {\n if (operations == maxOperations || count == maxAbsoluteValue) return;\n operations++;\n count++;\n plot();\n }\n\n public void decrement() {\n if (operations == maxOperations || count == -maxAbsoluteValue) return;\n operations++;\n count--;\n plot();\n }\n\n public int tally() {\n return count;\n }\n\n private void plot() {\n StdDraw.point(operations, count);\n }\n}\n```", "support_files": [], "metadata": {"number": "1.2.10", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.2, "section_title": "Data Abstraction", "type": "Exercise", "code_execution": false}} {"question": "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.", "answer": "One simple implementation is Sakamoto's day-of-week algorithm. It handles leap years correctly, including century years.\n\n```java\npublic String dayOfTheWeek() {\n String[] name = {\n \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n \"Thursday\", \"Friday\", \"Saturday\"\n };\n int[] monthOffset = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};\n int y = year;\n if (month < 3) y--;\n int dayIndex = (y + y / 4 - y / 100 + y / 400 + monthOffset[month - 1] + day) % 7;\n return name[dayIndex];\n}\n```", "support_files": [], "metadata": {"number": "1.2.12", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.2, "section_title": "Data Abstraction", "type": "Exercise", "code_execution": false}} {"question": "Rational numbers. Implement an immutable data type Rational for rational numbers that supports addition, subtraction, multiplication, and division.\npublic class Rational \nRational(int numerator, int denominator) \nRational plus(Rational b) // sum of this number and b\nRational minus(Rational b) // difference of this number and b\nRational times(Rational b) // product of this number and b\nRational divides(Rational b) // quotient of this number and b\nboolean equals(Rational that) // is this number equal to that ?\nString toString() // string representation\nYou 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.", "answer": "```java\npublic final class Rational {\n private final long numerator;\n private final long denominator;\n\n public Rational(long numerator, long denominator) {\n if (denominator == 0) throw new IllegalArgumentException(\"denominator is zero\");\n if (denominator < 0) {\n numerator = -numerator;\n denominator = -denominator;\n }\n long g = gcd(Math.abs(numerator), denominator);\n this.numerator = numerator / g;\n this.denominator = denominator / g;\n }\n\n public Rational plus(Rational b) {\n return new Rational(numerator * b.denominator + b.numerator * denominator,\n denominator * b.denominator);\n }\n\n public Rational minus(Rational b) {\n return new Rational(numerator * b.denominator - b.numerator * denominator,\n denominator * b.denominator);\n }\n\n public Rational times(Rational b) {\n return new Rational(numerator * b.numerator, denominator * b.denominator);\n }\n\n public Rational divides(Rational b) {\n if (b.numerator == 0) throw new IllegalArgumentException(\"division by zero\");\n return new Rational(numerator * b.denominator, denominator * b.numerator);\n }\n\n public boolean equals(Object other) {\n if (this == other) return true;\n if (other == null || other.getClass() != getClass()) return false;\n Rational that = (Rational) other;\n return numerator == that.numerator && denominator == that.denominator;\n }\n\n public String toString() {\n return denominator == 1 ? Long.toString(numerator) : numerator + \"/\" + denominator;\n }\n\n private static long gcd(long a, long b) {\n while (b != 0) {\n long t = a % b;\n a = b;\n b = t;\n }\n return a;\n }\n}\n```", "support_files": [], "metadata": {"number": "1.2.16", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.2, "section_title": "Data Abstraction", "type": "Creative Problem", "code_execution": false}} {"question": "Robust implementation of rational numbers. Use assertions to develop an implementation of Rational (see Exercise 1.2.16) that is immune to overflow.", "answer": "Use the same immutable representation as Exercise 1.2.16, but assert that every intermediate arithmetic operation fits in a `long` before constructing the result.\n\n```java\npublic Rational plus(Rational b) {\n long left = Math.multiplyExact(numerator, b.denominator);\n long right = Math.multiplyExact(b.numerator, denominator);\n long n = Math.addExact(left, right);\n long d = Math.multiplyExact(denominator, b.denominator);\n assert n == left + right;\n return new Rational(n, d);\n}\n\npublic Rational minus(Rational b) {\n long left = Math.multiplyExact(numerator, b.denominator);\n long right = Math.multiplyExact(b.numerator, denominator);\n long n = Math.subtractExact(left, right);\n long d = Math.multiplyExact(denominator, b.denominator);\n return new Rational(n, d);\n}\n\npublic Rational times(Rational b) {\n return new Rational(Math.multiplyExact(numerator, b.numerator),\n Math.multiplyExact(denominator, b.denominator));\n}\n\npublic Rational divides(Rational b) {\n if (b.numerator == 0) throw new IllegalArgumentException(\"division by zero\");\n return new Rational(Math.multiplyExact(numerator, b.denominator),\n Math.multiplyExact(denominator, b.numerator));\n}\n```\n\n`Math.*Exact` throws `ArithmeticException` on overflow; with assertions enabled, the implementation also documents the no-overflow invariant at the operation boundary.", "support_files": [], "metadata": {"number": "1.2.17", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.2, "section_title": "Data Abstraction", "type": "Creative Problem", "code_execution": false}} {"question": "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():\npublic class Accumulator \n{\n private double m;\n private double s;\n private int N;\n public void addDataValue(double x)\n {\n N++;\n s = s + 1.0 * (N-1) / N * (x - m) * (x - m);\n m = m + (x - m) / N;\n }\n public double mean()\n { return m; }\n public double var()\n { return s/(N - 1); }\n public double stddev()\n { return Math.sqrt(this.var()); }\n}\nThis implementation is less susceptible to roundoff error than the straightforward implementation based on saving the sum of the squares of the numbers.", "answer": "package chapter1.section2;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento\n */\npublic class Exercise18_VarianceForAccumulator {\n\n private double m;\n private double s;\n private int N;\n\n public void addDataValue(double x) {\n N++;\n s = s + 1.0 * (N - 1) / N * (x - m) * (x - m);\n m = m + (x - m) / N;\n }\n\n public double mean() {\n return m;\n }\n\n public double var() {\n return s / (N - 1);\n }\n\n public double stddev() {\n return Math.sqrt(this.var());\n }\n\n public static void main(String... args) {\n //Code validation\n Exercise18_VarianceForAccumulator validation = new Exercise18_VarianceForAccumulator();\n validation.addDataValue(2);\n validation.addDataValue(4);\n validation.addDataValue(5);\n\n StdOut.println(\"Mean: \" + validation.mean() + \" Expected: 3.6666666666666665\");\n StdOut.println(\"Variance: \" + validation.var() + \" Expected: 2.333333333333333\");\n StdOut.println(\"Standard Deviation: \" + validation.stddev() + \" Expected: 1.5275252316519465\");\n }\n}\n", "support_files": [], "metadata": {"number": "1.2.18", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.2, "section_title": "Data Abstraction", "type": "Creative Problem", "code_execution": false}} {"question": "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.\n| type | format | example |\n|-------------|--------------------------------------------|------------------------|\n| Date | integers separated by slashes | 5/22/1939 |\n| Transaction | customer, date, and amount, separated by whitespace | Turing 5/22/1939 11.99 |", "answer": "// Exercise19_1_Parsing.java\npackage chapter1.section2;\n\nimport java.text.ParseException;\nimport java.text.SimpleDateFormat;\nimport java.util.Calendar;\nimport java.util.Date;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento\n */\npublic class Exercise19_1_Parsing {\n\n private final int month;\n private final int day;\n private final int year;\n\n public Exercise19_1_Parsing(int month, int day, int year) {\n if (!isDateValid(month, day, year)) {\n throw new RuntimeException(\"Invalid date!\");\n }\n\n this.month = month;\n this.day = day;\n this.year = year;\n }\n\n public Exercise19_1_Parsing(String date) {\n String[] values = date.split(\"/\");\n month = Integer.parseInt(values[0]);\n day = Integer.parseInt(values[1]);\n year = Integer.parseInt(values[2]);\n\n if (!isDateValid(month, day, year)) {\n throw new RuntimeException(\"Invalid date!\");\n }\n }\n\n public int month() {\n return month;\n }\n\n public int day() {\n return day;\n }\n\n public int year() {\n return year;\n }\n\n public String toString() {\n return month() + \"/\" + day() + \"/\" + year();\n }\n\n private boolean isDateValid(int month, int day, int year) {\n boolean valid = true;\n\n int[] maxNumberOfDaysPerMonth = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};\n if (year < 1 || month < 1 || month > 12 || day < 1 || day > maxNumberOfDaysPerMonth[month - 1]) {\n valid = false;\n }\n return valid;\n }\n\n private String dayOfTheWeek() {\n String[] days = {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"};\n Calendar calendar = Calendar.getInstance();\n Date date;\n\n try {\n date = new SimpleDateFormat(\"MM/dd/yyyy\").parse(this.toString());\n calendar.setTime(date);\n } catch (ParseException e) {\n e.printStackTrace();\n }\n int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);\n return days[dayOfWeek - 1];\n }\n\n public static void main(String[] args) {\n Exercise19_1_Parsing parsedDate = new Exercise19_1_Parsing(\"4/18/1989\");\n StdOut.println(\"Parsed date: \" + parsedDate);\n StdOut.println(\"Expected: 4/18/1989\");\n }\n}\n\n// Exercise19_2_Parsing.java\npackage chapter1.section2;\n\nimport edu.princeton.cs.algs4.Date;\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento\n */\npublic class Exercise19_2_Parsing {\n\n private final String who;\n private final Date when;\n private final double amount;\n\n public Exercise19_2_Parsing(String who, Date when, double amount) {\n this.who = who;\n this.when = when;\n this.amount = amount;\n }\n\n public Exercise19_2_Parsing(String transaction) {\n String[] values = transaction.trim().split(\"\\\\s+\");\n who = values[0];\n when = new Date(values[1]);\n amount = Double.parseDouble(values[2]);\n }\n\n public String who() {\n return who;\n }\n\n public Date when() {\n return when;\n }\n\n public double amount() {\n return amount;\n }\n\n public String toString() {\n return who() + \" spent \" + amount + \" on \" + when();\n }\n\n public static void main(String[] args) {\n Date date = new Date(8, 5, 2016);\n\n Exercise19_2_Parsing transaction = new Exercise19_2_Parsing(\"Turing\", date, 22.10);\n StdOut.println(transaction);\n StdOut.println(\"Expected: Turing spent 22.1 on 8/5/2016\");\n }\n}\n", "support_files": [], "metadata": {"number": "1.2.19", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.2, "section_title": "Data Abstraction", "type": "Creative Problem", "code_execution": false}} {"question": "Add a method isFull() to FixedCapacityStackOfStrings.", "answer": "package chapter1.section3;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento\n */\npublic class Exercise1 { //FixedCapacityStackOfStrings\n\n private String[] a;\n private int n;\n\n public Exercise1(int cap) {\n a = new String[cap];\n }\n\n public boolean isEmpty() {\n return n == 0;\n }\n\n public int size() {\n return n;\n }\n\n public void push(String item) {\n a[n++] = item;\n }\n\n public String pop() {\n return a[--n];\n }\n\n public boolean isFull() {\n return n == a.length;\n }\n\n public static void main(String... args) {\n Exercise1 fixedCapacityStackOfStrings = new Exercise1(2);\n StdOut.println(\"Is Full 1: \" + fixedCapacityStackOfStrings.isFull() + \" Expected: false\");\n\n fixedCapacityStackOfStrings.push(\"a\");\n fixedCapacityStackOfStrings.push(\"b\");\n StdOut.println(\"Is Full 2: \" + fixedCapacityStackOfStrings.isFull() + \" Expected: true\");\n }\n}\n", "support_files": [], "metadata": {"number": "1.3.1", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Exercise", "code_execution": false}} {"question": "Give the output printed by java Stack for the input\nit was - the best - of times - - - it was - the - -", "answer": "1.3.2 it was - the best - of times - - - it was - the - -\nThe output printed is:\n\nwas best times of the was the it \n(1 left on stack)\n", "support_files": [], "metadata": {"number": "1.3.2", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Exercise", "code_execution": false}} {"question": "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 [(]).", "answer": "package chapter1.section3;\n\nimport edu.princeton.cs.algs4.Stack;\nimport edu.princeton.cs.algs4.StdIn;\nimport edu.princeton.cs.algs4.StdOut;\n\npublic class Parentheses {\n public static void main(String[] args) {\n String input = StdIn.readAll().trim();\n StdOut.println(isBalanced(input));\n }\n\n private static boolean isBalanced(String input) {\n Stack stack = new Stack<>();\n for (char c : input.toCharArray()) {\n if (c == '(' || c == '[' || c == '{') {\n stack.push(c);\n } else if (c == ')' || c == ']' || c == '}') {\n if (stack.isEmpty()) return false;\n char open = stack.pop();\n if ((c == ')' && open != '(') || (c == ']' && open != '[') || (c == '}' && open != '{')) {\n return false;\n }\n }\n }\n return stack.isEmpty();\n }\n}\n", "support_files": [], "metadata": {"number": "1.3.4", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Exercise", "code_execution": false}} {"question": "What does the following code fragment do to the queue q?\nStack stack = new Stack(); \nwhile (!q.isEmpty())\n stack.push(q.dequeue()); \nwhile (!stack.isEmpty())\n q.enqueue(stack.pop());", "answer": "1.3.6\nIt inverts the order of the queue values\n", "support_files": [], "metadata": {"number": "1.3.6", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Exercise", "code_execution": false}} {"question": "Add a method peek() to Stack that returns the most recently inserted item on the stack (without popping it).", "answer": "package chapter1.section3;\n\nimport java.util.NoSuchElementException;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento\n */\npublic class Exercise7 {\n\n private Node first;\n private int n;\n\n private class Node {\n Item item;\n Node next;\n }\n\n public boolean isEmpty() {\n return first == null;\n }\n\n public int size() {\n return n;\n }\n\n public void push(Item item) {\n Node oldFirst = first;\n\n first = new Node();\n first.item = item;\n first.next = oldFirst;\n n++;\n }\n\n public Item pop() {\n if (isEmpty()) {\n throw new NoSuchElementException(\"Stack underflow\");\n }\n Item item = first.item;\n first = first.next;\n n--;\n\n return item;\n }\n\n public Item peek() {\n if (isEmpty()) {\n throw new NoSuchElementException(\"Stack underflow\");\n }\n return first.item;\n }\n\n public static void main(String[] args) {\n Exercise7 stack = new Exercise7<>();\n\n stack.push(\"String 1\");\n stack.push(\"String 2\");\n stack.push(\"String 4\");\n stack.push(\"String 8\");\n\n StdOut.println(\"Peek: \" + stack.peek());\n StdOut.println(\"Expected: String 8\\n\");\n\n StdOut.println(\"Pop: \" + stack.pop());\n StdOut.println(\"Expected: String 8\\n\");\n StdOut.println(\"Pop: \" + stack.pop());\n StdOut.println(\"Expected: String 4\");\n }\n}\n", "support_files": [], "metadata": {"number": "1.3.7", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Exercise", "code_execution": false}} {"question": "Give the contents and size of the array for DoublingStackOfStrings with the input\nit was - the best - of times - - - it was - the - -", "answer": "Contents: `it`. The backing array size is 2, because the final pop leaves one item after the array was last doubled to length 2.", "support_files": [], "metadata": {"number": "1.3.8", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Exercise", "code_execution": false}} {"question": "Write a filter InfixToPostfix that converts an arithmetic expression from infix to postfix.", "answer": "A standard shunting-yard filter converts infix tokens to postfix while preserving precedence.\n\n```java\nimport edu.princeton.cs.algs4.Stack;\nimport edu.princeton.cs.algs4.StdIn;\nimport edu.princeton.cs.algs4.StdOut;\n\npublic class InfixToPostfix {\n private static int precedence(String op) {\n if (op.equals(\"+\") || op.equals(\"-\")) return 1;\n if (op.equals(\"*\") || op.equals(\"/\")) return 2;\n return 0;\n }\n\n private static boolean isOperator(String token) {\n return token.equals(\"+\") || token.equals(\"-\") || token.equals(\"*\") || token.equals(\"/\");\n }\n\n public static void main(String[] args) {\n Stack ops = new Stack<>();\n while (!StdIn.isEmpty()) {\n String token = StdIn.readString();\n if (token.equals(\"(\")) {\n ops.push(token);\n } else if (token.equals(\")\")) {\n while (!ops.peek().equals(\"(\")) StdOut.print(ops.pop() + \" \");\n ops.pop();\n } else if (isOperator(token)) {\n while (!ops.isEmpty() && !ops.peek().equals(\"(\")\n && precedence(ops.peek()) >= precedence(token)) {\n StdOut.print(ops.pop() + \" \");\n }\n ops.push(token);\n } else {\n StdOut.print(token + \" \");\n }\n }\n while (!ops.isEmpty()) StdOut.print(ops.pop() + \" \");\n StdOut.println();\n }\n}\n```", "support_files": [], "metadata": {"number": "1.3.10", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Exercise", "code_execution": false}} {"question": "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.", "answer": "package chapter1.section3;\n\nimport edu.princeton.cs.algs4.Stack;\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento\n */\npublic class Exercise12 {\n\n private static Stack copy(Stack stack) {\n Stack temp = new Stack<>();\n Stack copy = new Stack<>();\n\n //Copy from stack to temp\n for (String s : stack) {\n temp.push(s);\n }\n\n //Copy from temp to copy to keep the original order\n for (String s : temp) {\n copy.push(s);\n }\n return copy;\n }\n\n public static void main(String[] args) {\n Stack stack = new Stack<>();\n stack.push(\"First Item\");\n stack.push(\"Second Item\");\n stack.push(\"Third Item\");\n\n Stack copy = copy(stack);\n stack.pop();\n stack.pop();\n\n for (String s : copy) {\n StdOut.println(s);\n }\n\n StdOut.println(\"\\nExpected: \" +\n \"\\nThird Item\\n\" +\n \"Second Item\\n\" +\n \"First Item\");\n }\n}\n", "support_files": [], "metadata": {"number": "1.3.12", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Exercise", "code_execution": false}} {"question": "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.", "answer": "public static Date[] readDates() {\n Queue queue = new Queue<>();\n while (!StdIn.isEmpty()) {\n queue.enqueue(new Date(StdIn.readString()));\n }\n\n Date[] dates = new Date[queue.size()];\n for (int i = 0; i < dates.length; i++) {\n dates[i] = queue.dequeue();\n }\n return dates;\n}\n", "support_files": [], "metadata": {"number": "1.3.16", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Exercise", "code_execution": false}} {"question": "Do Exercise 1.3.16 for Transaction.", "answer": "public static Transaction[] readTransactions() {\n Queue queue = new Queue<>();\n while (!StdIn.isEmpty()) {\n queue.enqueue(new Transaction(StdIn.readLine()));\n }\n\n Transaction[] transactions = new Transaction[queue.size()];\n for (int i = 0; i < transactions.length; i++) {\n transactions[i] = queue.dequeue();\n }\n return transactions;\n}\n", "support_files": [], "metadata": {"number": "1.3.17", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Exercise", "code_execution": false}} {"question": "Suppose x is a linked-list node and not the last node on the list. What is the effect of the following code fragment?\nx.next = x.next.next;", "answer": "1.3.18\nDeletes from the list the node the comes after x.\n", "support_files": [], "metadata": {"number": "1.3.18", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Exercise", "code_execution": false}} {"question": "Give a code fragment that removes the last node in a linked list whose first node is first.", "answer": "package chapter1.section3;\n\nimport java.util.Iterator;\nimport java.util.StringJoiner;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento\n */\npublic class Exercise19 implements Iterable {\n\n private class Node {\n Item item;\n Node next;\n }\n\n private int size;\n private Node first;\n\n public boolean isEmpty() {\n return size == 0;\n }\n\n public int size() {\n return size;\n }\n\n public void add(Item item) {\n if (isEmpty()) {\n first = new Node();\n first.item = item;\n } else {\n Node current;\n for (current = first; current.next != null; current = current.next) ;\n\n Node newNode = new Node();\n newNode.item = item;\n current.next = newNode;\n }\n size++;\n }\n\n public void deleteLastNode() {\n if (!isEmpty()) {\n if (size == 1) {\n first = null;\n } else {\n Node current = first;\n for (int i = 0; i < size - 2; i++) {\n current = current.next;\n }\n current.next = null;\n }\n\n size--;\n }\n }\n\n @Override\n public Iterator iterator() {\n return new ListIterator();\n }\n\n private class ListIterator implements Iterator {\n Node current = first;\n\n @Override\n public boolean hasNext() {\n return current != null;\n }\n\n @Override\n public Item next() {\n Item item = current.item;\n current = current.next;\n\n return item;\n }\n }\n\n public static void main(String[] args) {\n Exercise19 linkedList = new Exercise19<>();\n linkedList.add(0);\n linkedList.add(1);\n linkedList.add(2);\n linkedList.add(3);\n\n StdOut.println(\"Before removing last node\");\n\n StringJoiner listBeforeRemove = new StringJoiner(\" \");\n for (int number : linkedList) {\n listBeforeRemove.add(String.valueOf(number));\n }\n\n StdOut.println(listBeforeRemove.toString());\n StdOut.println(\"Expected: 0 1 2 3\");\n\n linkedList.deleteLastNode();\n\n StdOut.println(\"\\nAfter removing last node\");\n\n StringJoiner listAfterRemove = new StringJoiner(\" \");\n for (int number : linkedList) {\n listAfterRemove.add(String.valueOf(number));\n }\n\n StdOut.println(listAfterRemove.toString());\n StdOut.println(\"Expected: 0 1 2\");\n }\n}\n", "support_files": [], "metadata": {"number": "1.3.19", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Exercise", "code_execution": false}} {"question": "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).", "answer": "public static void insertAfter(Node first, Node second) {\n if (first == null || second == null) {\n return;\n }\n second.next = first.next;\n first.next = second;\n}\n\nThe method uses the node references directly, so it works even when the list contains duplicate item values.\n", "support_files": [], "metadata": {"number": "1.3.25", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Exercise", "code_execution": false}} {"question": "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.", "answer": "public static int max(Node first) {\n int max = 0;\n for (Node x = first; x != null; x = x.next) {\n if (x.item > max) {\n max = x.item;\n }\n }\n return max;\n}\n\nThis returns 0 for an empty list and otherwise scans the list once.\n", "support_files": [], "metadata": {"number": "1.3.27", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Exercise", "code_execution": false}} {"question": "Random bag. A random bag stores a collection of items and supports the following API:\npublic class RandomBag implements Iterable \nRandomBag() // create an empty random bag\nboolean isEmpty() // is the bag empty?\nint size() // number of items in the bag\nvoid add(Item item) // add an item\nWrite 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.", "answer": "package chapter1.section3;\n\nimport edu.princeton.cs.algs4.StdOut;\nimport edu.princeton.cs.algs4.StdRandom;\n\nimport java.util.Iterator;\nimport java.util.StringJoiner;\n\n/**\n * Created by Rene Argento on 8/16/16.\n */\npublic class Exercise34_RandomBag implements Iterable {\n\n private Item[] array;\n private int size;\n\n @SuppressWarnings(\"unchecked\")\n public Exercise34_RandomBag() {\n array = (Item[]) new Object[1];\n size = 0;\n }\n\n public boolean isEmpty() {\n return size == 0;\n }\n\n public int size() {\n return size;\n }\n\n public void add(Item item) {\n if (size() == array.length) {\n resize(array.length * 2);\n }\n\n array[size] = item;\n size++;\n }\n\n @SuppressWarnings(\"unchecked\")\n private void resize(int capacity) {\n Item[] temp = (Item[]) new Object[capacity];\n\n for (int i = 0; i < size(); i++) {\n temp[i] = array[i];\n }\n\n array = temp;\n }\n\n @Override\n public Iterator iterator() {\n return new RandomBagIterator();\n }\n\n @SuppressWarnings(\"unchecked\")\n private class RandomBagIterator implements Iterator {\n int index;\n Item[] arrayCopy;\n\n public RandomBagIterator() {\n index = 0;\n arrayCopy = (Item[]) new Object[size];\n\n for (int i = 0; i < size; i++) {\n arrayCopy[i] = array[i];\n }\n\n sortArrayCopy();\n }\n\n @Override\n public boolean hasNext() {\n return index < size();\n }\n\n @Override\n public Item next() {\n Item item = arrayCopy[index];\n index++;\n return item;\n }\n\n private void sortArrayCopy() {\n for (int i = 0; i < size; i++) {\n int randomIndex = StdRandom.uniform(i, size);\n\n // Swap\n Item temp = arrayCopy[i];\n arrayCopy[i] = arrayCopy[randomIndex];\n arrayCopy[randomIndex] = temp;\n }\n }\n }\n\n public static void main(String[] args) {\n Exercise34_RandomBag randomBag = new Exercise34_RandomBag<>();\n randomBag.add(1);\n randomBag.add(2);\n randomBag.add(3);\n randomBag.add(4);\n randomBag.add(5);\n randomBag.add(6);\n randomBag.add(7);\n randomBag.add(8);\n\n StdOut.print(\"Random bag items: \");\n\n StringJoiner randomBagItems = new StringJoiner(\" \");\n for (int item : randomBag) {\n randomBagItems.add(String.valueOf(item));\n }\n StdOut.println(randomBagItems.toString());\n }\n}\n", "support_files": [], "metadata": {"number": "1.3.34", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Creative Problem", "code_execution": false}} {"question": "Random queue. A random queue stores a collection of items and supports the following API:\npublic class RandomQueue\nRandomQueue() // create an empty random queue\nboolean isEmpty() // is the queue empty?\nvoid enqueue(Item item) // add an item\nItem dequeue() // remove and return a random item (sample without replacement)\nItem sample() // return a random item, but do not remove (sample with replacement)\nWrite 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.", "answer": "package chapter1.section3;\n\nimport edu.princeton.cs.algs4.StdOut;\nimport edu.princeton.cs.algs4.StdRandom;\n\n/**\n * Created by Rene Argento on 8/16/16.\n */\n@SuppressWarnings(\"unchecked\")\npublic class Exercise35_RandomQueue {\n\n public class RandomQueue {\n private Item[] items;\n private int size;\n\n public RandomQueue() {\n items = (Item[]) new Object[1];\n size = 0;\n }\n\n public boolean isEmpty() {\n return size == 0;\n }\n\n public void enqueue(Item item) {\n if (size == items.length) {\n resize(items.length * 2);\n }\n\n items[size] = item;\n size++;\n }\n\n public Item dequeue() {\n if (isEmpty()) {\n throw new RuntimeException(\"Queue underflow\");\n }\n\n int randomIndex = StdRandom.uniform(0, size);\n\n Item randomItem = items[randomIndex];\n\n items[randomIndex] = items[size - 1];\n items[size - 1] = null;\n size--;\n\n if (size > 0 && size == items.length / 4) {\n resize(items.length / 2);\n }\n\n return randomItem;\n }\n\n public Item sample() {\n if (isEmpty()) {\n throw new RuntimeException(\"Queue underflow\");\n }\n\n int randomIndex = StdRandom.uniform(0, size);\n\n return items[randomIndex];\n }\n\n private void resize(int capacity) {\n Item[] temp = (Item[]) new Object[capacity];\n\n for (int i = 0; i < size; i++) {\n temp[i] = items[i];\n }\n\n items = temp;\n }\n }\n\n public static void main(String[] args) {\n Exercise35_RandomQueue exercise35_randomQueue = new Exercise35_RandomQueue();\n RandomQueue randomQueue = exercise35_randomQueue.new RandomQueue<>();\n\n fillQueueWithBridgeHandsCards(randomQueue);\n\n for (int i = 0; i < 4; i++) {\n int count = 0;\n StdOut.println(\"Hand \" + (i + 1));\n\n while (count < 13) {\n StdOut.println(randomQueue.dequeue());\n count++;\n }\n StdOut.println();\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n private static void fillQueueWithBridgeHandsCards(RandomQueue randomQueue) {\n String[] suits = {\"Spades\", \"Hearts\", \"Diamonds\", \"Clubs\"};\n\n for (int i = 0; i < suits.length; i++) {\n randomQueue.enqueue(new Card(\"A\", suits[i]));\n randomQueue.enqueue(new Card(\"2\", suits[i]));\n randomQueue.enqueue(new Card(\"3\", suits[i]));\n randomQueue.enqueue(new Card(\"4\", suits[i]));\n randomQueue.enqueue(new Card(\"5\", suits[i]));\n randomQueue.enqueue(new Card(\"6\", suits[i]));\n randomQueue.enqueue(new Card(\"7\", suits[i]));\n randomQueue.enqueue(new Card(\"8\", suits[i]));\n randomQueue.enqueue(new Card(\"9\", suits[i]));\n randomQueue.enqueue(new Card(\"10\", suits[i]));\n randomQueue.enqueue(new Card(\"J\", suits[i]));\n randomQueue.enqueue(new Card(\"Q\", suits[i]));\n randomQueue.enqueue(new Card(\"K\", suits[i]));\n }\n }\n\n private static class Card {\n String value;\n String suit;\n\n public Card(String value, String suit) {\n this.value = value;\n this.suit = suit;\n }\n\n @Override\n public String toString() {\n return value + \"-\" + suit;\n }\n }\n}\n", "support_files": [], "metadata": {"number": "1.3.35", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Creative Problem", "code_execution": false}} {"question": "Delete kth element. Implement a class that supports the following API:\npublic class GeneralizedQueue\nGeneralizedQueue() // create an empty queue\nboolean isEmpty() // is the queue empty?\nvoid insert(Item x) // add an item\nItem delete(int k) // delete and return the kth least recently inserted item\nFirst, 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.", "answer": "// Exercise38_1_DeleteKthElement.java\npackage chapter1.section3;\n\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.Iterator;\nimport java.util.StringJoiner;\n\n/**\n * Created by Rene Argento on 8/21/16.\n */\n@SuppressWarnings(\"unchecked\")\npublic class Exercise38_1_DeleteKthElement implements Iterable{\n\n private Item[] queue;\n private int size;\n\n public Exercise38_1_DeleteKthElement() {\n queue = (Item[]) new Object[1];\n size = 0;\n }\n\n public boolean isEmpty() {\n return size == 0;\n }\n\n public void insert(Item item) {\n\n if (size == queue.length) {\n resize(queue.length * 2);\n }\n\n queue[size] = item;\n size++;\n }\n\n public Item delete(int k) {\n\n if (isEmpty()) {\n throw new RuntimeException(\"Queue underflow\");\n }\n if (k <= 0 || size < k) {\n throw new RuntimeException(\"Invalid index\");\n }\n\n Item item = queue[k - 1];\n moveItemsLeft(k);\n\n size--;\n\n if (size > 0 && size == queue.length / 4) {\n resize(Math.max(1, queue.length / 2));\n }\n\n return item;\n }\n\n private void moveItemsLeft(int firstIndex) {\n for (int i = firstIndex; i < size; i++) {\n queue[i - 1] = queue[i];\n }\n queue[size - 1] = null; //to avoid loitering\n }\n\n private void resize(int capacity) {\n Item[] temp = (Item[]) new Object[capacity];\n\n for (int i = 0; i < size; i++) {\n temp[i] = queue[i];\n }\n\n queue = temp;\n }\n\n @Override\n public Iterator iterator() {\n return new GeneralizedQueueIterator();\n }\n\n private class GeneralizedQueueIterator implements Iterator {\n\n private int index = 0;\n\n @Override\n public boolean hasNext() {\n return index < size;\n }\n\n @Override\n public Item next() {\n Item item = queue[index];\n index++;\n return item;\n }\n }\n\n public static void main(String[] args) {\n Exercise38_1_DeleteKthElement generalizedQueue = new Exercise38_1_DeleteKthElement<>();\n generalizedQueue.insert(0);\n generalizedQueue.insert(1);\n generalizedQueue.insert(2);\n generalizedQueue.insert(3);\n generalizedQueue.insert(4);\n\n generalizedQueue.delete(1);\n generalizedQueue.delete(3);\n\n StringJoiner generalizedQueueItems = new StringJoiner(\" \");\n for (int item : generalizedQueue) {\n generalizedQueueItems.add(String.valueOf(item));\n }\n\n StdOut.println(\"Generalized queue items: \" + generalizedQueueItems.toString());\n StdOut.println(\"Expected: 1 2 4\");\n }\n}\n\n// Exercise38_2_DeleteKthElement.java\npackage chapter1.section3;\n\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.Iterator;\nimport java.util.StringJoiner;\n\n/**\n * Created by Rene Argento on 8/21/16.\n */\npublic class Exercise38_2_DeleteKthElement implements Iterable{\n\n private class Node {\n Item item;\n Node next;\n Node previous;\n }\n\n private Node first;\n private Node last;\n private int size;\n\n public Exercise38_2_DeleteKthElement() {\n first = null;\n last = null;\n size = 0;\n }\n\n public boolean isEmpty() {\n return size == 0;\n }\n\n public void insert(Item item) {\n Node oldLast = last;\n last = new Node();\n last.item = item;\n last.previous = oldLast;\n\n if (last.previous != null) {\n last.previous.next = last;\n } else {\n first = last;\n }\n\n size++;\n }\n\n public Item delete(int k) {\n if (isEmpty()) {\n throw new RuntimeException(\"Queue underflow\");\n }\n if (k <= 0 || k > size) {\n throw new RuntimeException(\"Invalid index\");\n }\n\n int count;\n boolean startFromBeginning = k <= size / 2;\n\n Node current;\n\n if (startFromBeginning) {\n count = 1;\n for (current = first; count < k; current = current.next) {\n count++;\n }\n } else {\n count = size;\n for (current = last; count > k; current = current.previous) {\n count--;\n }\n }\n\n Item item = current.item;\n if (current.previous != null) {\n current.previous.next = current.next;\n } else {\n first = current.next;\n }\n\n if (current.next != null) {\n current.next.previous = current.previous;\n } else {\n last = current.previous;\n }\n\n size--;\n\n return item;\n }\n\n @Override\n public Iterator iterator() {\n return new GeneralizedQueueIterator();\n }\n\n private class GeneralizedQueueIterator implements Iterator {\n\n Node current = first;\n\n @Override\n public boolean hasNext() {\n return current != null;\n }\n\n @Override\n public Item next() {\n Item item = current.item;\n current = current.next;\n return item;\n }\n }\n\n public static void main(String[] args) {\n Exercise38_2_DeleteKthElement generalizedQueue = new Exercise38_2_DeleteKthElement<>();\n generalizedQueue.insert(0);\n generalizedQueue.insert(1);\n generalizedQueue.insert(2);\n generalizedQueue.insert(3);\n generalizedQueue.insert(4);\n\n generalizedQueue.delete(1);\n generalizedQueue.delete(4);\n generalizedQueue.insert(99);\n\n StringJoiner generalizedQueueItems = new StringJoiner(\" \");\n for (int item : generalizedQueue) {\n generalizedQueueItems.add(String.valueOf(item));\n }\n\n StdOut.println(\"Generalized queue items: \" + generalizedQueueItems.toString());\n StdOut.println(\"Expected: 1 2 3 99\");\n }\n}\n", "support_files": [], "metadata": {"number": "1.3.38", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Creative Problem", "code_execution": false}} {"question": "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).", "answer": "1.3.46 - Forbidden triple for stack generability\nSuppose 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\".\nThus, when \"c\" is pushed, both \"a\" and \"b\" are on the stack. Therefore, \"a\" cannot be popped before \"b\".\n\nWhen 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.\nIf a < b, \"a\" cannot be above \"b\" on the stack. Therefore, a permutation would not exist when a forbidden triple exists.\n\nConversely, suppose a permutation is not stack-generable. Let c be the first item that must be popped while some smaller item a that was pushed earlier is still below a larger item b on the stack. Since a < b < c and c appears before a and b in the output while a appears before b, the permutation contains the forbidden triple (a, b, c). Therefore avoiding forbidden triples is both necessary and sufficient.\n", "support_files": [], "metadata": {"number": "1.3.46", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.3, "section_title": "Bags, Queues, and Stacks", "type": "Creative Problem", "code_execution": false}} {"question": "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.", "answer": "1.4.1\n\nCounting argument:\nWhen choosing the first element there are N possibilities. \nWhen choosing the second element there are N - 1 possibilities.\nWhen choosing the third element there are N - 2 possibilities.\n\nThis is a total of N(N - 1)(N - 2). If the order of items mattered, this would be the result.\nHowever, the order of items does not matter. For 3 items there is a total of 3! possible orderings.\n3! = 6\n\nSo, the number of triples that can be chosen from N items is equal to:\nN(N - 1)(N - 2) / 6\n\nBy induction:\nLet's define the number of different triples that can be chosen from N elements as P(N).\nLet's assume that P(N) = N(N - 1)(N - 2) / 6 and consider the base cases.\n\nN = 1 P(N) = 1(1 - 1)(1 - 2) / 6 = 0\nN = 2 P(N) = 2(2 - 1)(2 - 2) / 6 = 0\nN = 3 P(N) = 3(3 - 1)(3 - 2) / 6 = 1\n\nAnd we can see that P(N) holds for those.\n\nNow if we assume that:\n\nP(N) = N(N - 1)(N - 2) / 6\n\nand we prove that:\n\nP(N + 1) = (N + 1)N(N - 1) / 6 [*]\n\nthen P(N) holds for any arbitrary N.\n\nP(N + 1) = P(N) + (number of new triples that contain the newly inserted N + 1)\n\nThere are exactly \"N choose K\" new triples that contain N + 1, so:\n\nP(N + 1) = P(N) + N! / 2!(N - 2)!\n = P(N) + N(N - 1) / 2\n = N(N - 1)(N - 2) / 6 + N(N - 1) / 2\n = N(N - 1)(N - 2) / 6 + 3N(N - 1) / 6\n = N(N - 1)(N - 2 + 3) / 6\n = N(N - 1)(N + 1) / 6\n \nAnd [*] is proven.\n", "support_files": [], "metadata": {"number": "1.4.1", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Exercise", "code_execution": false}} {"question": "Modify ThreeSum to work properly even when the int values are so large that adding two of them might cause overflow.", "answer": "package chapter1.section4;\n\nimport edu.princeton.cs.algs4.In;\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.math.BigInteger;\n\n/**\n * Created by Rene Argento on 9/27/16.\n */\npublic class Exercise2 {\n\n public static int count(int[] array) {\n //Count triples that sum to 0.\n int length = array.length;\n int count = 0;\n\n BigInteger bigInteger;\n\n for (int i = 0; i < length; i++) {\n for (int j = i + 1; j < length; j++) {\n for (int k = j + 1; k < length; k++) {\n bigInteger = BigInteger.valueOf(array[i]);\n bigInteger = bigInteger.add(BigInteger.valueOf(array[j]));\n bigInteger = bigInteger.add(BigInteger.valueOf(array[k]));\n\n if (bigInteger.equals(BigInteger.ZERO)) {\n count++;\n }\n }\n }\n }\n return count;\n }\n\n public static void main(String[] args) {\n In in = new In(args[0]);\n int[] array = in.readAllInts();\n StdOut.println(count(array));\n }\n}\n", "support_files": [], "metadata": {"number": "1.4.2", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Exercise", "code_execution": false}} {"question": "Develop a table like the one on page 181 for TwoSum.", "answer": "1.4.4\n\nStatement in Block Time in seconds Frequency Total time\n D t0 x(depends on input) t0x\n C t1 N^2/2 - N/2 t1(N^2/2 - N/2)\n B t2 N t2N\n A t3 1 t3\nGrand total: (t1/2) N^2\n + (-t1/2 + t2) N\n + t3 + t0x\nTilde approximation: ~(t1/2) N^2 (assuming x is small)\nOrder of growth: N^2\n", "support_files": [], "metadata": {"number": "1.4.4", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Exercise", "code_execution": false}} {"question": "Give the order of growth (as a function of N) of the running times of each of the following code fragments:\na. int sum = 0;\n for (int n = N; n > 0; n /= 2)\n for(int i = 0; i < n; i++)\n sum++;\nb. int sum = 0;\n for (int i = 1; i < N; i *= 2)\n for (int j = 0; j < i; j++)\n sum++;\nc. int sum = 0;\n for (int i = 1; i < N; i *= 2)\n for (int j = 0; j < N; j++)\n sum++;", "answer": "1.4.6\n\na. O(N)\nb. O(N)\nc. O(N log(N))\n\nThanks to Vivek Bhojawala (https://github.com/VBhojawala) for mentioning the correct answer to the question in letter a.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/9\n", "support_files": [], "metadata": {"number": "1.4.6", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Exercise", "code_execution": false}} {"question": "Analyze ThreeSum under a cost model that counts arithmetic operations (and comparisons) involving the input numbers.", "answer": "1.4.7\n\nWith a cost model that counts arithmetic operations (and comparisons) involving input numbers, the main \"if\" from\nThreeSum involves 4 operations instead of 1.\n\nif (a[i] + a[j] + a[k] == 0)\n\nOne operation for the if check; one operation to sum a[i] and a[j]; one operation to sum the result with a[k]\nand one operation to compare the result with 0.\n\nTherefore the main \"if\" has a frequency of 4 (N^3/6 - N^2/2 + N/3) instead of (N^3/6 - N^2/2 + N/3)\n\nAnd the grand total becomes:\nt1(4N^3/6 - 4N^2/2 + 4N/3) + t2(N^2/2 - N/2) + t3N + t4\n\nTilde approximation: ~(4t1/6)N^3\nOrder of growth: N^3\n", "support_files": [], "metadata": {"number": "1.4.7", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Exercise", "code_execution": false}} {"question": "Write a program to determine the number pairs of values in an input file that are equal. If your first try is quadratic, think again and use Arrays.sort() to develop a linearithmic solution.", "answer": "package chapter1.section4;\n\nimport edu.princeton.cs.algs4.In;\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * Created by Rene Argento on 9/28/16.\n */\n// Thanks to Vivek Bhojawala (https://github.com/VBhojawala) for mentioning that the solution should use\n// Arrays.sort(), as requested in the exercise. https://github.com/reneargento/algorithms-sedgewick-wayne/issues/6\n\n//Quantity of numbers : Quantity of equal pairs\n// 2 1\n// 3 3\n// 4 6\n// 5 10\n// The quantity of equal pairs is equal to:\n// (n - 1) * n / 2\npublic class Exercise8 {\n\n public static void main(String[] args) {\n In in = new In(args[0]);\n int[] values = in.readAllInts();\n StdOut.println(countNumberOfPairs(values));\n\n // Tests\n int[] values1 = {1, 2, 4, 1, 2, 1, 2, 4, 5, 1, 2, 4, 5, 1, 2 ,5, 6, 7, 7, 8, 2, 1, 2, 4, 5};\n StdOut.println(\"Equal pairs 1: \" + countNumberOfPairs(values1) + \" Expected: 49\");\n\n int[] values2 = {1, 1, 1};\n StdOut.println(\"Equal pairs 2: \" + countNumberOfPairs(values2) + \" Expected: 3\");\n }\n\n // O(n lg n) solution\n private static int countNumberOfPairs(int[] values) {\n Arrays.sort(values);\n\n int count = 0;\n int currentFrequency = 1;\n\n for (int i = 1; i < values.length; i++) {\n if (values[i] == values[i - 1]) {\n currentFrequency++;\n } else {\n if (currentFrequency > 1) {\n count += (currentFrequency - 1) * currentFrequency / 2;\n currentFrequency = 1;\n }\n }\n }\n\n if (currentFrequency > 1) {\n count += (currentFrequency - 1) * currentFrequency / 2;\n }\n return count;\n }\n\n // O(n) solution\n private static int countNumberOfPairs2(int[] values) {\n Map valuesMap = new HashMap<>();\n int equalNumbersCount = 0;\n\n for (int i = 0; i < values.length; i++) {\n int count = 0;\n if (valuesMap.containsKey(values[i])) {\n count = valuesMap.get(values[i]);\n }\n count++;\n valuesMap.put(values[i], count);\n }\n\n for (int numberKey : valuesMap.keySet()) {\n if (valuesMap.get(numberKey) > 1) {\n int n = valuesMap.get(numberKey);\n equalNumbersCount += (n - 1) * n / 2;\n }\n }\n return equalNumbersCount;\n }\n}\n", "support_files": [], "metadata": {"number": "1.4.8", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Exercise", "code_execution": false}} {"question": "Modify binary search so that it always returns the element with the smallest index that matches the search element (and still guarantees logarithmic running time).", "answer": "package chapter1.section4;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 9/28/16.\n */\n// Thanks to Vivek Bhojawala (https://github.com/VBhojawala) for fixing a bug and suggesting improvements\n// in the binarySearch() method at https://github.com/reneargento/algorithms-sedgewick-wayne/issues/6\n// Thanks to ajfg93 (https://github.com/ajfg93) for suggesting an iterative solution for the problem at\n// https://github.com/reneargento/algorithms-sedgewick-wayne/issues/27\n// Thanks to emergencyd (https://github.com/emergencyd) for suggesting an improvement on the iterative solution.\n// https://github.com/reneargento/algorithms-sedgewick-wayne/issues/124\n// For another (similar) iterative solution to this problem, check\n// https://github.com/reneargento/algorithms-sedgewick-wayne/issues/196 - Thanks to nedas-dev (https://github.com/nedas-dev)\npublic class Exercise10 {\n\n public static void main(String[] args) {\n int[] testArray1 = {3, 4, 4, 5, 6, 10, 15, 20, 20, 20, 20, 21};\n int elementToSearch1 = 4;\n int elementToSearch2 = 20;\n int elementToSearch3 = -5;\n\n StdOut.println(\"Binary search: \" + binarySearch(testArray1, elementToSearch1, 0, testArray1.length - 1) +\n \" Expected: 1\");\n StdOut.println(\"Binary search: \" + binarySearch(testArray1, elementToSearch2, 0, testArray1.length - 1) +\n \" Expected: 7\");\n StdOut.println(\"Binary search: \" + binarySearch(testArray1, elementToSearch3, 0, testArray1.length - 1) +\n \" Expected: -1\");\n\n int[] testArray2 = {4, 4, 4, 4, 4, 4, 15, 20, 20, 20, 20, 21};\n int elementToSearch4 = 4;\n\n StdOut.println(\"Binary search: \" + binarySearch(testArray2, elementToSearch4, 0, testArray2.length - 1) +\n \" Expected: 0\");\n }\n\n private static int binarySearch(int[] array, int element, int low, int high) {\n if (low > high) {\n return -1;\n }\n\n int middle = low + (high - low) / 2;\n\n if (array[middle] < element) {\n return binarySearch(array, element, middle + 1, high);\n } else if (array[middle] > element) {\n return binarySearch(array, element, low, middle - 1);\n } else {\n int possibleSmallestIndex = binarySearch(array, element, low, middle - 1);\n\n if (possibleSmallestIndex == -1) {\n return middle;\n } else {\n return possibleSmallestIndex;\n }\n }\n }\n\n private static int binarySearchIterative(int[] array, int element, int low, int high) {\n while (low <= high) {\n int middle = low + (high - low) / 2;\n\n if (array[middle] < element) {\n low = middle + 1;\n } else if (array[middle] > element\n || (middle > 0 && array[middle - 1] == element)) {\n high = middle - 1;\n } else {\n return middle;\n }\n }\n return -1;\n }\n}\n", "support_files": [], "metadata": {"number": "1.4.10", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Exercise", "code_execution": false}} {"question": "Write a program that, given two sorted arrays of N int values, prints all elements that appear in both arrays, in sorted order. The running time of your program should be proportional to N in the worst case.", "answer": "package chapter1.section4;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 9/29/16.\n */\n// Thanks to ektasingh151 (https://github.com/ektasingh151) for suggesting a simpler solution:\n// https://github.com/reneargento/algorithms-sedgewick-wayne/pull/149\npublic class Exercise12 {\n\n public static void main(String[] args) {\n int[] array1 = { 0, 1, 2, 2, 5, 6, 6, 8, 25, 25 };\n int[] array2 = { -2, 0, 1, 2, 2, 2, 3, 4, 5, 10, 20, 25, 25 };\n\n StdOut.print(\"Elements: \");\n printElementsThatAppearInBothArrays(array1, array2);\n StdOut.println(\"\\nExpected: 0 1 2 5 25\");\n }\n\n private static void printElementsThatAppearInBothArrays(int[] array1, int[] array2) {\n int array1Index = 0;\n int array2Index = 0;\n Integer recentMatchedValue = null;\n\n while (array1Index < array1.length && array2Index < array2.length) {\n if (array1[array1Index] < array2[array2Index]) {\n array1Index++;\n } else if (array2[array2Index] < array1[array1Index]) {\n array2Index++;\n } else {\n if (recentMatchedValue == null || recentMatchedValue != array1[array1Index]) {\n StdOut.print(array1[array1Index] + \" \");\n recentMatchedValue = array1[array1Index];\n }\n array1Index++;\n array2Index++;\n }\n }\n }\n}\n", "support_files": [], "metadata": {"number": "1.4.12", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Exercise", "code_execution": false}} {"question": "Closest pair (in one dimension). Write a program that, given an array a[] of N double values, finds a closest pair: two values whose difference is no greater than the difference of any other pair (in absolute value). The running time of your program should be linearithmic in the worst case.", "answer": "package chapter1.section4;\n\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.Arrays;\n\n/**\n * Created by Rene Argento on 9/30/16.\n */\npublic class Exercise16_ClosestPair {\n\n public static void main(String[] args) {\n double[] array1 = {-5.2, 9.4, 20, -10, 21.1, 40, 50, -20};\n double[] array2 = {-4, -3, 0, 10, 20};\n double[] array3 = {-10, -3, 0, 2, 4, 20};\n\n double[] closestPair1 = closestPair(array1);\n double[] closestPair2 = closestPair(array2);\n double[] closestPair3 = closestPair(array3);\n\n StdOut.println(\"Closest pair: \" + closestPair1[0] + \" \" + closestPair1[1] + \" Expected: 20.0 21.1\");\n StdOut.println(\"Closest pair: \" + closestPair2[0] + \" \" + closestPair2[1] + \" Expected: -4.0 -3.0\");\n StdOut.println(\"Closest pair: \" + closestPair3[0] + \" \" + closestPair3[1] + \" Expected: 0.0 2.0\");\n }\n\n private static double[] closestPair(double[] array) {\n double[] closestPair = new double[2];\n\n double currentMinimumDifference = Double.MAX_VALUE;\n\n Arrays.sort(array);\n\n for (int i = 0; i < array.length - 1; i++) {\n if (Math.abs(array[i] - array[i + 1]) < currentMinimumDifference) {\n currentMinimumDifference = Math.abs(array[i] - array[i + 1]);\n\n closestPair[0] = array[i];\n closestPair[1] = array[i + 1];\n }\n }\n return closestPair;\n }\n}\n", "support_files": [], "metadata": {"number": "1.4.16", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Creative Problem", "code_execution": false}} {"question": "Farthest pair (in one dimension). Write a program that, given an array a[] of N double values, finds a farthest pair: two values whose difference is no smaller than the difference of any other pair (in absolute value). The running time of your program should be linear in the worst case.", "answer": "package chapter1.section4;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 9/30/16.\n */\npublic class Exercise17_FarthestPair {\n\n public static void main(String[] args) {\n double[] array1 = {-5.2, 9.4, 20, -10, 21.1, 40, 50, -20};\n double[] array2 = {-4, -3, 0, 10, 20};\n double[] array3 = {-10, -3, 0, 2, 4, 20};\n\n double[] farthestPair1 = farthestPair(array1);\n double[] farthestPair2 = farthestPair(array2);\n double[] farthestPair3 = farthestPair(array3);\n\n StdOut.println(\"Farthest pair: \" + farthestPair1[0] + \" \" + farthestPair1[1] + \" Expected: -20.0 50.0\");\n StdOut.println(\"Farthest pair: \" + farthestPair2[0] + \" \" + farthestPair2[1] + \" Expected: -4.0 20.0\");\n StdOut.println(\"Farthest pair: \" + farthestPair3[0] + \" \" + farthestPair3[1] + \" Expected: -10.0 20.0\");\n }\n\n private static double[] farthestPair(double[] array) {\n double[] farthestPair = new double[2];\n\n if (array.length == 0) {\n throw new RuntimeException(\"Array cannot be null\");\n }\n\n double currentMin = array[0];\n double currentMax = array[0];\n\n farthestPair[0] = array[0];\n farthestPair[1] = array[0];\n\n for (int i = 1; i < array.length; i++) {\n if (array[i] < currentMin) {\n currentMin = array[i];\n farthestPair[0] = array[i];\n }\n\n if (array[i] > currentMax) {\n currentMax = array[i];\n farthestPair[1] = array[i];\n }\n }\n\n return farthestPair;\n }\n}\n", "support_files": [], "metadata": {"number": "1.4.17", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Creative Problem", "code_execution": false}} {"question": "Local minimum of an array. Write a program that, given an array a[] of N distinct integers, finds a local minimum: an index i such that a[i] is smaller than its neighbors (a[i-1] > a[i] < a[i+1]). Your program should use ~2lg N compares in the worst case.", "answer": "public static int localMinimumIndex(int[] a) {\n if (a == null || a.length == 0) return -1;\n if (a.length == 1 || a[0] < a[1]) return 0;\n int n = a.length;\n if (a[n - 1] < a[n - 2]) return n - 1;\n\n int lo = 1;\n int hi = n - 2;\n while (lo <= hi) {\n int mid = lo + (hi - lo) / 2;\n if (a[mid] < a[mid - 1] && a[mid] < a[mid + 1]) {\n return mid;\n }\n if (a[mid - 1] < a[mid]) {\n hi = mid - 1;\n } else {\n lo = mid + 1;\n }\n }\n return -1;\n}\n\nAt each step the search moves toward a smaller neighbor, so a local minimum must exist in the chosen half. The worst-case number of compares is proportional to lg N.\n", "support_files": [], "metadata": {"number": "1.4.18", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Creative Problem", "code_execution": false}} {"question": "Local minimum of a matrix. Given an N-by-N array a[] of N^2 distinct integers, design an algorithm that runs in time proportional to N to find a local minimum: a pair of indices i and j such that a[i][j] < a[i+1][j], a[i][j] < a[i][j+1], a[i][j] < a[i-1][j], and a[i][j] < a[i][j-1]. The running time of your program should be proportional to N in the worst case.", "answer": "Use the standard divide-and-conquer algorithm: inspect the middle row and middle column, find the minimum item on that cross, and either return it if it is smaller than its four neighbors or recurse into the quadrant containing a smaller neighbor.\n\n```java\npublic static int[] localMinimum(int[][] a) {\n return localMinimum(a, 0, a.length - 1, 0, a.length - 1);\n}\n\nprivate static int[] localMinimum(int[][] a, int rowLo, int rowHi, int colLo, int colHi) {\n int rowMid = rowLo + (rowHi - rowLo) / 2;\n int colMid = colLo + (colHi - colLo) / 2;\n int bestRow = rowMid;\n int bestCol = colMid;\n\n for (int c = colLo; c <= colHi; c++) {\n if (a[rowMid][c] < a[bestRow][bestCol]) {\n bestRow = rowMid;\n bestCol = c;\n }\n }\n for (int r = rowLo; r <= rowHi; r++) {\n if (a[r][colMid] < a[bestRow][bestCol]) {\n bestRow = r;\n bestCol = colMid;\n }\n }\n\n int[][] neighbors = {{bestRow - 1, bestCol}, {bestRow + 1, bestCol}, {bestRow, bestCol - 1}, {bestRow, bestCol + 1}};\n for (int[] nb : neighbors) {\n int r = nb[0], c = nb[1];\n if (r >= rowLo && r <= rowHi && c >= colLo && c <= colHi && a[r][c] < a[bestRow][bestCol]) {\n if (r < rowMid && c < colMid) return localMinimum(a, rowLo, rowMid - 1, colLo, colMid - 1);\n if (r < rowMid) return localMinimum(a, rowLo, rowMid - 1, colMid + 1, colHi);\n if (c < colMid) return localMinimum(a, rowMid + 1, rowHi, colLo, colMid - 1);\n return localMinimum(a, rowMid + 1, rowHi, colMid + 1, colHi);\n }\n }\n return new int[] {bestRow, bestCol};\n}\n```\n\nThe work per level is proportional to the current side length, giving N + N/2 + N/4 + ... = O(N).\n", "support_files": [], "metadata": {"number": "1.4.19", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Creative Problem", "code_execution": false}} {"question": "Throwing two eggs from a building. Consider the previous question, but now suppose you only have two eggs, and your cost model is the number of throws. Devise a strategy to determine F such that the number of throws is at most 2√N, then find a way to reduce the cost to ~c√F. This is analogous to a situation where search hits (egg intact) are much cheaper than misses (egg broken).", "answer": "package chapter1.section4;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 23/10/16.\n */\npublic class Exercise25_Throwing2Eggs {\n\n public static void main(String[] args) {\n int[] array = {0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1};\n\n int[] array2 = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1};\n\n int[] array3 = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 1};\n\n Exercise25_Throwing2Eggs exercise25_throwing2Eggs = new Exercise25_Throwing2Eggs();\n\n // findFloorIn2SqrtN\n\n int floor = exercise25_throwing2Eggs.findFloorIn2SqrtN(array);\n StdOut.println(\"Floor: \" + floor + \" Expected: 7\");\n\n int floor2 = exercise25_throwing2Eggs.findFloorIn2SqrtN(array2);\n StdOut.println(\"Floor: \" + floor2 + \" Expected: 0\");\n\n int floor3 = exercise25_throwing2Eggs.findFloorIn2SqrtN(array3);\n StdOut.println(\"Floor: \" + floor3 + \" Expected: 40\");\n\n // findFloorInCSqrtF\n\n int floor4 = exercise25_throwing2Eggs.findFloorInCSqrtF(array);\n StdOut.println(\"Floor: \" + floor4 + \" Expected: 7\");\n\n int floor5 = exercise25_throwing2Eggs.findFloorInCSqrtF(array2);\n StdOut.println(\"Floor: \" + floor5 + \" Expected: 0\");\n\n int floor6 = exercise25_throwing2Eggs.findFloorInCSqrtF(array3);\n StdOut.println(\"Floor: \" + floor6 + \" Expected: 40\");\n }\n\n private int findFloorIn2SqrtN(int[] array) {\n int low = 0;\n int high = array.length - 1;\n\n return findFloorIn2SqrtN(array, low, high, 0);\n }\n\n /*\n Solution to Part 1: To achieve 2 * sqrt(N), drop eggs at floors\n sqrt(N), 2 * sqrt(N), 3 * sqrt(N), ..., sqrt(N) * sqrt(N).\n (For simplicity, we assume here that sqrt(N) is an integer.)\n Let assume that the egg broke at level k * sqrt(N).\n With the second egg you should then perform a linear search\n in the interval (k-1) * sqrt(N) to k * sqrt(N).\n In total you will be able to find the floor F in at most 2 * sqrt(N) trials.\n */\n private int findFloorIn2SqrtN(int[] array, int low, int high, int searchLevel) {\n int key = 1;\n\n if (low <= high) {\n int sqrt = (int) Math.sqrt(array.length - 1);\n\n int separator = sqrt * searchLevel;\n\n if (separator >= array.length) {\n separator = array.length - 1;\n }\n\n StdOut.println(\"Debug - current index: \" + separator);\n\n if (key > array[separator]) {\n return findFloorIn2SqrtN(array, separator + 1, high, ++searchLevel);\n } else {\n // We broke 1 out of 2 eggs, now we do a linear search starting from a floor in which we know that the egg\n // does not break\n\n if (searchLevel != 0) {\n searchLevel = searchLevel - 1;\n }\n\n int lastFloorThatDidNotBreak = sqrt * searchLevel;\n\n for (int i = lastFloorThatDidNotBreak; i <= separator; i++) {\n StdOut.println(\"Debug - current index: \" + i);\n\n if (array[i] == 1) {\n // 2 out of 2 eggs broken, but we now have the floor number\n return i;\n }\n }\n }\n }\n\n return -1;\n }\n\n private int findFloorInCSqrtF(int[] array) {\n int low = 0;\n int high = array.length - 1;\n\n return findFloorInCSqrtF(array, low, high, 0, 0);\n }\n\n // Hint from website: 1 + 2 + 3 + ... k ~ 1/2 k^2.\n private int findFloorInCSqrtF(int[] array, int low, int high, int searchElement, int increment) {\n int key = 1;\n\n if (low <= high) {\n\n searchElement = searchElement + increment;\n\n if (searchElement >= array.length) {\n searchElement = array.length - 1;\n }\n\n StdOut.println(\"Debug - current index: \" + searchElement);\n\n if (key > array[searchElement]) {\n return findFloorInCSqrtF(array, searchElement + 1, high, searchElement, ++increment);\n } else {\n // We broke 1 out of 2 eggs, now we do a linear search starting from a floor in which we know that the egg\n // does not break\n\n searchElement = searchElement - increment;\n int lastFloorThatDidNotBreak = searchElement;\n\n for (int i = lastFloorThatDidNotBreak; i <= searchElement + increment; i++) {\n StdOut.println(\"Debug - current index: \" + i);\n\n if (array[i] == 1) {\n // 2 out of 2 eggs broken, but we now have the floor number\n return i;\n }\n }\n }\n }\n return -1;\n }\n}\n", "support_files": [], "metadata": {"number": "1.4.25", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Creative Problem", "code_execution": false}} {"question": "Queue with two stacks. Implement a queue with two stacks so that each queue operation takes a constant amortized number of stack operations. Hint: If you push elements onto a stack and then pop them all, they appear in reverse order. If you repeat this process, they’re now back in order.", "answer": "package chapter1.section4;\n\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.Stack;\n\n/**\n * Created by Rene Argento on 20/11/16.\n */\npublic class Exercise27_QueueWith2Stacks {\n private Stack tailStack;\n private Stack headStack;\n\n public Exercise27_QueueWith2Stacks() {\n tailStack = new Stack<>();\n headStack = new Stack<>();\n }\n\n // O(1)\n public int size() {\n return headStack.size() + tailStack.size();\n }\n\n // O(1)\n public boolean isEmpty() {\n return headStack.isEmpty() && tailStack.isEmpty();\n }\n\n // O(1)\n public void enqueue(Item item) {\n tailStack.push(item);\n }\n\n // Amortized O(1)\n public Item dequeue() {\n if (headStack.isEmpty()) {\n moveAllItemsFromTailToHead();\n }\n return headStack.pop();\n }\n\n private void moveAllItemsFromTailToHead() {\n while (!tailStack.isEmpty()) {\n headStack.push(tailStack.pop());\n }\n }\n\n public static void main(String[] args) {\n Exercise27_QueueWith2Stacks exercise27_queueWith2Stacks = new Exercise27_QueueWith2Stacks<>();\n\n StdOut.println(\"IsEmpty: \" + exercise27_queueWith2Stacks.isEmpty() + \" Expected: true\");\n StdOut.println(\"Size: \" + exercise27_queueWith2Stacks.size() + \" Expected: 0\");\n\n exercise27_queueWith2Stacks.enqueue(\"A\");\n exercise27_queueWith2Stacks.enqueue(\"B\");\n StdOut.println(exercise27_queueWith2Stacks.dequeue());\n StdOut.println(exercise27_queueWith2Stacks.dequeue());\n\n exercise27_queueWith2Stacks.enqueue(\"C\");\n exercise27_queueWith2Stacks.enqueue(\"D\");\n exercise27_queueWith2Stacks.enqueue(\"E\");\n exercise27_queueWith2Stacks.enqueue(\"F\");\n\n StdOut.println(\"Size: \" + exercise27_queueWith2Stacks.size() + \" Expected: 4\");\n\n StdOut.println(exercise27_queueWith2Stacks.dequeue());\n StdOut.println(exercise27_queueWith2Stacks.dequeue());\n\n StdOut.println(\"Expected output from dequeue(): A B C D\");\n\n StdOut.println(\"IsEmpty: \" + exercise27_queueWith2Stacks.isEmpty() + \" Expected: false\");\n StdOut.println(\"Size: \" + exercise27_queueWith2Stacks.size() + \" Expected: 2\");\n }\n}\n", "support_files": [], "metadata": {"number": "1.4.27", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Creative Problem", "code_execution": false}} {"question": "Hot or cold. Your goal is to guess a secret integer between 1 and N. You repeatedly guess integers between 1 and N. After each guess you learn if your guess equals the secret integer (and the game stops). Otherwise, you learn if the guess is hotter (closer to) or colder (farther from) the secret number than your previous guess. Design an algorithm that finds the secret number in at most ~2 lg N guesses. Then design an algorithm that finds the secret number in at most ~ 1 lg N guesses.", "answer": "// Exercise34_HotOrCold1LgN.java\npackage chapter1.section4;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 23/11/16.\n */\n//IOI 2010 task\n//Based on http://stackoverflow.com/questions/25558951/hot-and-cold-binary-search-game\n // Worst case is O(lg n) + 6 when we start in an \"end quarter\"\n // or O(lg n) + 4 when we start in a \"middle quarter\"\npublic class Exercise34_HotOrCold1LgN {\n\n private int hotOrCold(int n, int target) {\n return firstGuesses(n, target, 1, n);\n }\n\n private int firstGuesses(int number, int target, int low, int high) {\n\n //Check if it is in the first half\n int firstGuessIndex = number / 2;\n\n if (firstGuessIndex == target) {\n StdOut.println(\"Found it!\");\n return firstGuessIndex;\n }\n\n //Check if it is in the second half\n int secondGuessIndex = (number / 2) + 1;\n if (secondGuessIndex == target) {\n StdOut.println(\"Found it!\");\n return secondGuessIndex;\n } else {\n boolean isItHotter = isItHotter(firstGuessIndex, secondGuessIndex, target);\n\n if (isItHotter) {\n //Secret is in the second half, so the next guess will be \"high\"\n return initialSearch(target, secondGuessIndex, false, secondGuessIndex, high);\n } else {\n //Secret is in the first half, so the next guess will be \"low\"\n return initialSearch(target, secondGuessIndex, true, low, firstGuessIndex);\n }\n }\n }\n\n //This is just in case we fall into one of the 2 \"end quarters\" and need to go to one of the 2 \"middle quarters\"\n private int initialSearch(int target, int lastGuess, boolean isNextGuessInLeftEnd, int low, int high) {\n\n if (low > high) {\n return -1;\n }\n\n int nextGuess;\n //Check new guess\n if (isNextGuessInLeftEnd) {\n nextGuess = low;\n } else {\n nextGuess = high;\n }\n boolean isItHotter = isItHotter(lastGuess, nextGuess, target);\n\n int middle = low + (high - low) / 2;\n\n if (nextGuess == target) {\n return nextGuess;\n } else if (isItHotter) {\n //We are in one of the 2 end quarters\n\n int middleOfMiddle;\n\n if (isNextGuessInLeftEnd) {\n middleOfMiddle = low + (middle - low) / 2;\n } else {\n middleOfMiddle = middle + (high - middle) / 2;\n }\n\n //Guess middleOfMiddle\n isItHotter(nextGuess, middleOfMiddle, target);\n if (middleOfMiddle == target) {\n return middleOfMiddle;\n }\n\n //Guess middleOfMiddle + 1\n isItHotter = isItHotter(middleOfMiddle, middleOfMiddle + 1, target);\n if (middleOfMiddle + 1 == target) {\n return middleOfMiddle + 1;\n }\n\n if (isItHotter) {\n //Secret is in the second half\n return search(target, middleOfMiddle + 1, middleOfMiddle + 1, high);\n } else {\n //Secret is in the first half\n return search(target, middleOfMiddle + 1, low, middleOfMiddle);\n }\n } else {\n //We are in one of the 2 middle quarters\n if (isNextGuessInLeftEnd) {\n return search(target, nextGuess, middle + 1, high);\n } else {\n return search(target, nextGuess, low, middle);\n }\n }\n }\n\n //We are in a \"middle quarter\"\n //Considering [a, b] as the interval we know the secret integer exists within,\n // take c to be the last number we guessed.\n // We want to determine the position of the secret with respect\n // to the mid point (a + b) / 2, so we have a new number d to guess at to know the\n // secret relative position to (a + b) / 2.\n // How do we know such number d?\n // By solving the equation (c + d) / 2 = (a + b) / 2, which yields d = a + b - c.\n // Guessing at that d, we shrink the range [a, b] appropriately based on\n // the answer(colder or hotter) and then we repeat the process.\n private int search(int target, int lastGuess, int low, int high) {\n\n if (low == high) {\n if (low == target) {\n //Found it!\n return low;\n } else {\n return -1;\n }\n }\n\n if (low > high) {\n return -1;\n }\n\n // a = low\n // b = high\n // c = lastGuess\n // d = nextGuess\n\n int nextGuess = low + high - lastGuess;\n\n boolean isItHotter = isItHotter(lastGuess, nextGuess, target);\n\n int middle = low + (high - low) / 2;\n\n if (nextGuess == target) {\n return nextGuess;\n } else if (isItHotter) {\n if (nextGuess >= high) {\n return search(target, nextGuess, middle + 1, high);\n } else {\n return search(target, nextGuess, low, middle);\n }\n } else {\n if (nextGuess >= high) {\n return search(target, nextGuess, low, middle);\n } else {\n return search(target, nextGuess, middle + 1, high);\n }\n }\n }\n\n private boolean isItHotter(int lastGuess, int currentGuess, int secret) {\n\n if (currentGuess == secret) {\n StdOut.println(\"Found it!\");\n return true;\n }\n\n if (Math.abs(secret - currentGuess) < Math.abs(secret - lastGuess)) {\n StdOut.println(\"Hotter - Last guess: \" + lastGuess + \" Current guess: \" + currentGuess);\n return true;\n } else {\n StdOut.println(\"Colder - Last guess: \" + lastGuess + \" Current guess: \" + currentGuess);\n return false;\n }\n }\n\n public static void main(String[] args) {\n Exercise34_HotOrCold1LgN hotOrCold = new Exercise34_HotOrCold1LgN();\n StdOut.println(\"Hot or Cold: \" + hotOrCold.hotOrCold(10, 3) + \" Expected: 3\");\n StdOut.println(\"Hot or Cold: \" + hotOrCold.hotOrCold(20, 12) + \" Expected: 12\");\n StdOut.println(\"Hot or Cold: \" + hotOrCold.hotOrCold(10, 11) + \" Expected: -1\");\n }\n\n}\n\n// Exercise34_HotOrCold2LgN.java\npackage chapter1.section4;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 23/11/16.\n */\npublic class Exercise34_HotOrCold2LgN {\n\n private int hotOrCold(int number, int target) {\n //Check if it is in the first half\n int firstGuessIndex = number / 2;\n\n if (firstGuessIndex == target) {\n StdOut.println(\"Found it!\");\n return firstGuessIndex;\n }\n\n //Check if it is in the second half\n int secondGuessIndex = firstGuessIndex + 1;\n if (secondGuessIndex == target) {\n StdOut.println(\"Found it!\");\n return secondGuessIndex;\n } else {\n boolean isItHotter = isItHotter(firstGuessIndex, secondGuessIndex, target);\n\n if (isItHotter) {\n return binarySearch(target, secondGuessIndex, secondGuessIndex, number);\n } else {\n return binarySearch(target, secondGuessIndex, 1, firstGuessIndex);\n }\n }\n }\n\n //2 * O(lg n)\n private int binarySearch(int target, int lastGuess, int low, int high) {\n if (low == high) {\n if (low == target) {\n //Found it!\n return low;\n } else {\n return -1;\n }\n }\n\n if (low > high) {\n return -1;\n }\n\n int middle = low + (high - low) / 2;\n\n // Guess middle\n boolean isItHotterFirstHalf = isItHotter(lastGuess, middle, target);\n if (isItHotterFirstHalf && middle == target) {\n return middle;\n }\n\n // Guess middle + 1\n boolean isItHotterSecondHalf = isItHotter(middle, middle + 1, target);\n\n if (middle + 1 == target) {\n return middle + 1;\n } else if (isItHotterSecondHalf) {\n return binarySearch(target, middle + 1, middle + 2, high);\n } else {\n return binarySearch(target, middle + 1, low, middle);\n }\n }\n\n private boolean isItHotter(int lastGuess, int currentGuess, int secret) {\n\n if (currentGuess == secret) {\n StdOut.println(\"Found it!\");\n return true;\n }\n\n if (Math.abs(secret - currentGuess) < Math.abs(secret - lastGuess)) {\n StdOut.println(\"Hotter - Last guess: \" + lastGuess + \" Current guess: \" + currentGuess);\n return true;\n } else {\n StdOut.println(\"Colder - Last guess: \" + lastGuess + \" Current guess: \" + currentGuess);\n return false;\n }\n }\n\n public static void main(String[] args) {\n Exercise34_HotOrCold2LgN hotOrCold = new Exercise34_HotOrCold2LgN();\n StdOut.println(\"Hot or Cold: \" + hotOrCold.hotOrCold(10, 3) + \" Expected: 3\");\n StdOut.println(\"Hot or Cold: \" + hotOrCold.hotOrCold(20, 12) + \" Expected: 12\");\n StdOut.println(\"Hot or Cold: \" + hotOrCold.hotOrCold(10, 11) + \" Expected: -1\");\n }\n\n}\n", "support_files": [], "metadata": {"number": "1.4.34", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Creative Problem", "code_execution": false}} {"question": "Time costs for pushdown stacks. Justify the entries in the table below, which shows typical time costs for various pushdown stack implementations, using a cost model that counts both data references (references to data pushed onto the stack, either an array reference or a reference to an object’s instance variable) and objects created.\n| data structure | item type | cost to push N int values | |\n|------------------|-----------|---------------------------|----------------|\n| | | data references | objects created |\n| linked list | int | 2N | N |\n| | Integer | 3N | 2N |\n| resizing array | int | ~5N | lg N |\n| | Integer | ~5N | ~N |", "answer": "1.4.35 - Time costs for pushdown stacks\n\n** Linked list\n * int\n 2N data references - N references of the nodes for the enclosing class and N references for the next Node (including a reference to the first node in the stack)\n N objects created - the N nodes created\n * Integer\n 3N data references - N references of the nodes for the enclosing class, N references for the next Node (including a reference to the first node in the stack) and N references for the Integer object\n 2N objects created - N nodes created, each containing an Integer\n\n** Resizing array\n * int\n ~5N data references - each of the array entries has a reference to an int value. Due to resizing, the array can be 25% to 100% full, meaning the total number of references can go up to ~4N. Also, the stack has a reference to the array.\n lgN objects created - every time the array is resized, a new array object is created. When the array is resized (due to pushes), it doubles its size. Therefore, at capacity 1, 2, 4, 8, 16, etc, a new object will be created. Hence, lgN objects.\n * Integer\n ~5N data references - each of the array entries has a reference to an int value. Due to resizing, the array can be 25% to 100% full, meaning the total number of references can go up to ~4N. Also, the stack has a reference to the array.\n ~N objects created - the N Integer objects created plus lg N objects created due to the resize operations. Therefore, ~N.\n", "support_files": [], "metadata": {"number": "1.4.35", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Creative Problem", "code_execution": false}} {"question": "Naive 3-sum implementation. Run experiments to evaluate the following implementation of the inner loop of ThreeSum:\nfor (int i = 0; i < N; i++)\n for (int j = 0; j < N; j++)\n for (int k = 0; k < N; k++)\n if (i < j && j < k)\n if (a[i] + a[j] + a[k] == 0)\n cnt++;\nDo so by developing a version of DoublingTest that computes the ratio of the running times of this program and ThreeSum.", "answer": "// Exercise38_Naive3Sum.java\npackage chapter1.section4;\n\nimport edu.princeton.cs.algs4.StdOut;\nimport edu.princeton.cs.algs4.StdRandom;\nimport edu.princeton.cs.algs4.Stopwatch;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * Created by Rene Argento on 26/11/16.\n */\npublic class Exercise38_Naive3Sum {\n\n private static double timeTrial(int n, boolean useEvenNaiverImplementation) {\n //Time ThreeSum.count() for n random 6-digit ints.\n int max = 1000000;\n int[] values = new int[n];\n\n for (int i = 0; i < n; i++) {\n values[i] = StdRandom.uniform(-max, max);\n }\n\n Stopwatch timer = new Stopwatch();\n\n if (useEvenNaiverImplementation) {\n evenNaiverThreeSumCount(values);\n } else {\n threeSumCount(values);\n }\n\n return timer.elapsedTime();\n }\n\n private static int threeSumCount(int[] values) {\n // Count triples that sum to 0\n int n = values.length;\n int count = 0;\n\n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n for (int k = j + 1; k < n; k++) {\n if (values[i] + values[j] + values[k] == 0) {\n count++;\n }\n }\n }\n }\n return count;\n }\n\n private static int evenNaiverThreeSumCount(int[] values) {\n //Count triples that sum to 0\n int n = values.length;\n int count = 0;\n\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n for (int k = 0; k < n; k++) {\n if (i < j && j < k) {\n if (values[i] + values[j] + values[k] == 0) {\n count++;\n }\n }\n }\n }\n }\n return count;\n }\n\n public static void main(String[] args) {\n Map timesOfNaiveThreeSum = new HashMap<>();\n Map timesOfEvenNaiverThreeSum = new HashMap<>();\n\n int maxTrials = 4000;\n\n StdOut.println(\"Number of items and ratio\");\n\n // Compute running times of naive 3-Sum\n for (int n = 250; n <= maxTrials; n += n) {\n double time = timeTrial(n, false);\n timesOfNaiveThreeSum.put(n, time);\n }\n\n // Compute running times of even naiver 3-Sum\n for (int n = 250; n <= maxTrials; n += n) {\n double time = timeTrial(n, true);\n timesOfEvenNaiverThreeSum.put(n, time);\n }\n\n for (int n = 250; n <= maxTrials; n += n) {\n double timeOfNaiveThreeSum = timesOfNaiveThreeSum.get(n);\n double timeOfEvenNaiverThreeSum = timesOfEvenNaiverThreeSum.get(n);\n\n double ratio = timeOfEvenNaiverThreeSum / timeOfNaiveThreeSum;\n\n StdOut.printf(\"%7d %5.1f\\n\", n, ratio);\n }\n }\n}\n\nAdditional notes/results:\n1.4.38 - Naive 3-sum implementation\n\nNumber of items and ratio (naiver implementation / naive implementation)\n 250 3.6\n 500 5.8\n 1000 31.3\n 2000 30.6\n 4000 31.3\n\nThe naive implementation takes about 30 times less time than the naiver implementation.", "support_files": [], "metadata": {"number": "1.4.38", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Experiment", "code_execution": false}} {"question": "Show the contents of the id[] array and the number of times the array is accessed for each input pair when you use quick-find for the sequence 9-0 3-4 5-8 7-2 2-1 5-7 0-3 4-2.", "answer": "1.5.1\n 0 1 2 3 4 5 6 7 8 9\narray = 0 1 2 3 4 5 6 7 8 9\n\n9-0\n 0 1 2 3 4 5 6 7 8 9\narray = 0 1 2 3 4 5 6 7 8 0\nArray accesses: 13 (2 in 2x find() + 10 for checking parents + 1 for updating parents)\n\n3-4\n 0 1 2 3 4 5 6 7 8 9\narray = 0 1 2 4 4 5 6 7 8 0\nArray accesses: 13 (2 in 2x find() + 10 for checking parents + 1 for updating parents)\n\n5-8\n 0 1 2 3 4 5 6 7 8 9\narray = 0 1 2 4 4 8 6 7 8 0\nArray accesses: 13 (2 in 2x find() + 10 for checking parents + 1 for updating parents)\n\n7-2\n 0 1 2 3 4 5 6 7 8 9\narray = 0 1 2 4 4 8 6 2 8 0\nArray accesses: 13 (2 in 2x find() + 10 for checking parents + 1 for updating parents)\n\n2-1\n 0 1 2 3 4 5 6 7 8 9\narray = 0 1 1 4 4 8 6 1 8 0\nArray accesses: 14 (2 in 2x find() + 10 for checking parents + 2 for updating parents)\n\n5-7\n 0 1 2 3 4 5 6 7 8 9\narray = 0 1 1 4 4 1 6 1 1 0\nArray accesses: 14 (2 in 2x find() + 10 for checking parents + 2 for updating parents)\n\n0-3\n 0 1 2 3 4 5 6 7 8 9\narray = 4 1 1 4 4 1 6 1 1 4\nArray accesses: 14 (2 in 2x find() + 10 for checking parents + 2 for updating parents)\n\n4-2\n 0 1 2 3 4 5 6 7 8 9\narray = 1 1 1 1 1 1 6 1 1 1\nArray accesses: 16 (2 in 2x find() + 10 for checking parents + 4 for updating parents)\n", "support_files": [], "metadata": {"number": "1.5.1", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.5, "section_title": "Case Study: Union-Find", "type": "Exercise", "code_execution": false}} {"question": "Do Exercise 1.5.1, but use quick-union (page 224). In addition, draw the forest of trees represented by the id[] array after each input pair is processed.", "answer": "1.5.2\n 0 1 2 3 4 5 6 7 8 9\narray = 0 1 2 3 4 5 6 7 8 9\n\n9-0\n 0 1 2 3 4 5 6 7 8 9\narray = 0 1 2 3 4 5 6 7 8 0\nArray accesses: 3 (1 for find(9), 1 for find(0) and 1 for updating parent)\n\nForest:\n0 1 2 3 4 5 6 7 8 \n9\n\n3-4\n 0 1 2 3 4 5 6 7 8 9\narray = 0 1 2 4 4 5 6 7 8 0\nArray accesses: 3 (1 for find(3), 1 for find(4) and 1 for updating parent)\n\nForest:\n0 1 2 4 5 6 7 8 \n9 3\n\n5-8\n 0 1 2 3 4 5 6 7 8 9\narray = 0 1 2 4 4 8 6 7 8 0\nArray accesses: 3 (1 for find(5), 1 for find(8) and 1 for updating parent)\n\nForest:\n0 1 2 4 6 7 8 \n9 3 5\n\n7-2\n 0 1 2 3 4 5 6 7 8 9\narray = 0 1 2 4 4 8 6 2 8 0\nArray accesses: 3 (1 for find(7), 1 for find(2) and 1 for updating parent)\n\nForest:\n0 1 2 4 6 8 \n9 7 3 5\n\n2-1\n 0 1 2 3 4 5 6 7 8 9\narray = 0 1 1 4 4 8 6 2 8 0\nArray accesses: 3 (1 for find(2), 1 for find(1) and 1 for updating parent)\n\nForest:\n0 1 4 6 8 \n9 2 3 5\n 7\n\n5-7\n 0 1 2 3 4 5 6 7 8 9\narray = 0 1 1 4 4 8 6 2 1 0\nArray accesses: 9 (3 for find(5), 5 for find(7) and 1 for updating parent)\n\nForest:\n0 1 4 6\n9 2 8 3\n 7 5\n\n0-3\n 0 1 2 3 4 5 6 7 8 9\narray = 4 1 1 4 4 8 6 2 1 0\nArray accesses: 5 (1 for find(0), 3 for find(3) and 1 for updating parent)\n\nForest:\n 1 4 6\n2 8 3 0\n7 5 9\n\n4-2\n 0 1 2 3 4 5 6 7 8 9\narray = 4 1 1 4 1 8 6 2 1 0\nArray accesses: 5 (1 for find(4), 3 for find(2) and 1 for updating parent)\n\nForest:\n 1 6\n2 8 4\n7 5 3 0\n 9\n\nThanks to kaustubhb (https://github.com/kaustubhb) for fixing a bug in the array values.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/4\nThanks to emergencyd (https://github.com/emergencyd) for fixing some of the array access counts.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/135\n", "support_files": [], "metadata": {"number": "1.5.2", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.5, "section_title": "Case Study: Union-Find", "type": "Exercise", "code_execution": false}} {"question": "Show the contents of the sz[] and id[] arrays and the number of array accesses for each input pair corresponding to the weighted quick-union examples in the text (both the reference input and the worst-case input).", "answer": "1.5.4\n\nReference input\n\nBeginning\n\nid[]\n0 1 2 3 4 5 6 7 8 9\n0 1 2 3 4 5 6 7 8 9\n\nsz[]\n0 1 2 3 4 5 6 7 8 9\n1 1 1 1 1 1 1 1 1 1\n\n4-3\n\nid[]\n0 1 2 3 4 5 6 7 8 9\n0 1 2 4 4 5 6 7 8 9\n\nsz[]\n0 1 2 3 4 5 6 7 8 9\n1 1 1 1 2 1 1 1 1 1\n\nArray accesses: 3 (1 for find(4), 1 for find(3) and 1 for updating parent)\n\n3-8\n\nid[]\n0 1 2 3 4 5 6 7 8 9\n0 1 2 4 4 5 6 7 4 9\n\nsz[]\n0 1 2 3 4 5 6 7 8 9\n1 1 1 1 3 1 1 1 1 1\n\nArray accesses: 5 (3 for find(3), 1 for find(8) and 1 for updating parent)\n\n6-5\n\nid[]\n0 1 2 3 4 5 6 7 8 9\n0 1 2 4 4 6 6 7 4 9\n\nsz[]\n0 1 2 3 4 5 6 7 8 9\n1 1 1 1 3 1 2 1 1 1\n\nArray accesses: 3 (1 for find(6), 1 for find(5) and 1 for updating parent)\n\n9-4\n\nid[]\n0 1 2 3 4 5 6 7 8 9\n0 1 2 4 4 6 6 7 4 4\n\nsz[]\n0 1 2 3 4 5 6 7 8 9\n1 1 1 1 4 1 2 1 1 1\n\nArray accesses: 3 (1 for find(9), 1 for find(4) and 1 for updating parent)\n\n2-1\n\nid[]\n0 1 2 3 4 5 6 7 8 9\n0 2 2 4 4 6 6 7 4 4\n\nsz[]\n0 1 2 3 4 5 6 7 8 9\n1 1 2 1 4 1 2 1 1 1\n\nArray accesses: 3 (1 for find(2), 1 for find(1) and 1 for updating parent)\n\n8-9\n\nid[]\n0 1 2 3 4 5 6 7 8 9\n0 2 2 4 4 6 6 7 4 4\n\nsz[]\n0 1 2 3 4 5 6 7 8 9\n1 1 2 1 4 1 2 1 1 1\n\nArray accesses: 6 (3 for find(8) and 3 for find(9))\n\n5-0\n\nid[]\n0 1 2 3 4 5 6 7 8 9\n6 2 2 4 4 6 6 7 4 4\n\nsz[]\n0 1 2 3 4 5 6 7 8 9\n1 1 2 1 4 1 3 1 1 1\n\nArray accesses: 5 (3 for find(5), 1 for find(0) and 1 for updating parent)\n\n7-2\n\nid[]\n0 1 2 3 4 5 6 7 8 9\n6 2 2 4 4 6 6 2 4 4\n\nsz[]\n0 1 2 3 4 5 6 7 8 9\n1 1 3 1 4 1 3 1 1 1\n\nArray accesses: 3 (1 for find(7), 1 for find(2) and 1 for updating parent)\n\n6-1\n\nid[]\n0 1 2 3 4 5 6 7 8 9\n6 2 6 4 4 6 6 2 4 4\n\nsz[]\n0 1 2 3 4 5 6 7 8 9\n1 1 3 1 4 1 6 1 1 1\n\nArray accesses: 5 (1 for find(6), 3 for find(1) and 1 for updating parent)\n\n1-0\n\nid[]\n0 1 2 3 4 5 6 7 8 9\n6 2 6 4 4 6 6 2 4 4\n\nsz[]\n0 1 2 3 4 5 6 7 8 9\n1 1 3 1 4 1 6 1 1 1\n\nArray accesses: 8 (5 for find(1) and 3 for find(0))\n\n6-7\n\nid[]\n0 1 2 3 4 5 6 7 8 9\n6 2 6 4 4 6 6 2 4 4\n\nsz[]\n0 1 2 3 4 5 6 7 8 9\n1 1 3 1 4 1 6 1 1 1\n\nArray accesses: 6 (1 for find(6) and 5 for find(7))\n\nWorst-case input\n\nBeginning\n\nid[]\n0 1 2 3 4 5 6 7\n0 1 2 3 4 5 6 7\n\nsz[]\n0 1 2 3 4 5 6 7\n1 1 1 1 1 1 1 1\n\n0-1\n\nid[]\n0 1 2 3 4 5 6 7\n0 0 2 3 4 5 6 7\n\nsz[]\n0 1 2 3 4 5 6 7\n2 1 1 1 1 1 1 1\n\nArray accesses: 3 (1 for find(0), 1 for find(1) and 1 for updating parent)\n\n2-3\n\nid[]\n0 1 2 3 4 5 6 7\n0 0 2 2 4 5 6 7\n\nsz[]\n0 1 2 3 4 5 6 7\n2 1 2 1 1 1 1 1\n\nArray accesses: 3 (1 for find(2), 1 for find(3) and 1 for updating parent)\n\n4-5\n\nid[]\n0 1 2 3 4 5 6 7\n0 0 2 2 4 4 6 7\n\nsz[]\n0 1 2 3 4 5 6 7\n2 1 2 1 2 1 1 1\n\nArray accesses: 3 (1 for find(4), 1 for find(5) and 1 for updating parent)\n\n6-7\n\nid[]\n0 1 2 3 4 5 6 7\n0 0 2 2 4 4 6 6\n\nsz[]\n0 1 2 3 4 5 6 7\n2 1 2 1 2 1 2 1\n\nArray accesses: 3 (1 for find(6), 1 for find(7) and 1 for updating parent)\n\n0-2\n\nid[]\n0 1 2 3 4 5 6 7\n0 0 0 2 4 4 6 6\n\nsz[]\n0 1 2 3 4 5 6 7\n4 1 2 1 2 1 2 1\n\nArray accesses: 3 (1 for find(0), 1 for find(2) and 1 for updating parent)\n\n4-6\n\nid[]\n0 1 2 3 4 5 6 7\n0 0 0 2 4 4 4 6\n\nsz[]\n0 1 2 3 4 5 6 7\n4 1 2 1 4 1 2 1\n\nArray accesses: 3 (1 for find(4), 1 for find(6) and 1 for updating parent)\n\n0-4\n\nid[]\n0 1 2 3 4 5 6 7\n0 0 0 2 0 4 4 6\n\nsz[]\n0 1 2 3 4 5 6 7\n8 1 2 1 4 1 2 1\n\nArray accesses: 3 (1 for find(0), 1 for find(4) and 1 for updating parent)\n\nThanks to sergiovasquez122 (https://github.com/sergiovasquez122) for noticing that there were extra array fields in the worst case:\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/168\nThanks to xzy2022 (https://github.com/xzy2022) for reporting an issue with the array access count in the find() method:\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/307\n", "support_files": [], "metadata": {"number": "1.5.4", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.5, "section_title": "Case Study: Union-Find", "type": "Exercise", "code_execution": false}} {"question": "Repeat Exercise 1.5.5 for weighted quick-union.", "answer": "1.5.6\n\n10^9 sites\n10^6 input pairs\nComputer can execute 10^9 instructions per second\nEach iteration of the inner for loop requires 10 instructions\n\nThe object initialization makes ~10^10 instructions (1 for initializing the count variable, 1 for creating the sites array, 10^10 due to the for loop iterations over the sites, 10^9 for initializing each site, 1 for creating the size array, 10^9 for initializing each size)\nEach find operation makes on the worst case lg(10^9) instructions * 10 due to the loop iterations over the sites ~ 300 instructions\nEach union operation makes on the worst case ~650 instructions (300 for each find(), 1 for comparing sites of the components being united, 1 for comparing sizes, 1 for updating one of the sizes, 1 for increasing one of the sizes and 1 for reducing the count of components)\n\nFor 10^6 input pairs, the total number of instructions required (I) is:\nI = M x IU\n\nWhere M is the number of input pairs and IU is the number of instructions in the union operation.\n\nI = 10^6 x 650\nI = 650,000,000\n\nSeconds needed = 65 x 10^7 / 10^9\nSeconds needed = 65 x 10^-2\nSeconds needed = 0.65\n\n0.65 seconds = 0.01 minutes = 0.0001 hours = 0.0000041 days\n\nThanks to QiotoF (https://github.com/QiotoF) for noting that the for loop instructions were not being considered.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/65\n", "support_files": [], "metadata": {"number": "1.5.6", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.5, "section_title": "Case Study: Union-Find", "type": "Exercise", "code_execution": false}} {"question": "Develop classes QuickUnionUF and QuickFindUF that implement quick-union and quick-find, respectively.", "answer": "```java\npublic class QuickUnionUF {\n private final int[] parent;\n private int count;\n\n public QuickUnionUF(int n) {\n count = n;\n parent = new int[n];\n for (int i = 0; i < n; i++) parent[i] = i;\n }\n\n public int count() { return count; }\n\n public int find(int p) {\n while (p != parent[p]) p = parent[p];\n return p;\n }\n\n public boolean connected(int p, int q) { return find(p) == find(q); }\n\n public void union(int p, int q) {\n int pRoot = find(p);\n int qRoot = find(q);\n if (pRoot == qRoot) return;\n parent[pRoot] = qRoot;\n count--;\n }\n}\n\npublic class QuickFindUF {\n private final int[] id;\n private int count;\n\n public QuickFindUF(int n) {\n count = n;\n id = new int[n];\n for (int i = 0; i < n; i++) id[i] = i;\n }\n\n public int count() { return count; }\n public int find(int p) { return id[p]; }\n public boolean connected(int p, int q) { return id[p] == id[q]; }\n\n public void union(int p, int q) {\n int pID = id[p];\n int qID = id[q];\n if (pID == qID) return;\n for (int i = 0; i < id.length; i++) {\n if (id[i] == pID) id[i] = qID;\n }\n count--;\n }\n}\n```", "support_files": [], "metadata": {"number": "1.5.7", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.5, "section_title": "Case Study: Union-Find", "type": "Exercise", "code_execution": false}} {"question": "Give a counterexample that shows why this intuitive implementation of union() for quick-find is not correct:\npublic void union(int p, int q) \n{ \n if (connected(p, q)) return;\n // Rename p’s component to q’s name.\n for (int i = 0; i < id.length; i++)\n if (id[i] == id[p]) id[i] = id[q];\n count--; \n}", "answer": "1.5.8\n\nIn the loop, id[p] will eventually be set to id[q], losing the reference to the original parent.\nThis will make the next elements with id[i] == id[p] to not have their values updated.\n\nCounterexample:\n\nid[p] = 2\nid[q] = 4\n\nArray\n0 1 2 2 4 2 6\n\n0 != 2, is not updated\n1 != 2, is not updated\n2 == 2, is updated to 4 (after this, all comparisons are incorrectly made with 4 instead of 2)\n2 != 4 is not updated (and should have been updated)\n4 == 4 is updated to 4 (again)\n2 != 4 is not updated (and should have been updated)\n6 != 4 is not updated\n", "support_files": [], "metadata": {"number": "1.5.8", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.5, "section_title": "Case Study: Union-Find", "type": "Exercise", "code_execution": false}} {"question": "In the weighted quick-union algorithm, suppose that we set id[find(p)] to q instead of to id[find(q)]. Would the resulting algorithm be correct?", "answer": "1.5.10\n\nYes, but that would increase the maximum possible height of the trees to N, which would decrease find()'s\nworst case performance from lg (N) to N and, consequently, decrease union()'s worst case performance to N.\n", "support_files": [], "metadata": {"number": "1.5.10", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.5, "section_title": "Case Study: Union-Find", "type": "Exercise", "code_execution": false}} {"question": "Quick-union with path compression. Modify quick-union (page 224) to include path compression, by adding a loop to union() that links every site on the paths from p and q to the roots of their trees to the root of the new tree. Give a sequence of input pairs that causes this method to produce a path of length 4. Note: The amortized cost per operation for this algorithm is known to be logarithmic.", "answer": "public void union(int p, int q) {\n int pRoot = root(p);\n int qRoot = root(q);\n if (pRoot == qRoot) {\n return;\n }\n\n id[pRoot] = qRoot;\n\n while (p != qRoot) {\n int next = id[p];\n id[p] = qRoot;\n p = next;\n }\n while (q != qRoot) {\n int next = id[q];\n id[q] = qRoot;\n q = next;\n }\n count--;\n}\n\nprivate int root(int p) {\n while (p != id[p]) {\n p = id[p];\n }\n return p;\n}\n\nOne sequence that can still create a path of length 4 before compression on that path is: 0-1, 2-3, 4-5, 6-7, 6-4, 4-2, 4-0.\n", "support_files": [], "metadata": {"number": "1.5.12", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.5, "section_title": "Case Study: Union-Find", "type": "Creative Problem", "code_execution": false}} {"question": "Amortized costs plots. Instrument your implementations from Exercise 1.5.7 to make amortized costs plots like those in the text.", "answer": "// Exercise16_AmortizedCostsPlotsQF.java\npackage chapter1.section5;\n\nimport util.GraphPanel;\nimport edu.princeton.cs.algs4.StdOut;\nimport edu.princeton.cs.algs4.StdRandom;\n\nimport javax.swing.*;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Created by Rene Argento on 08/12/16.\n */\npublic class Exercise16_AmortizedCostsPlotsQF {\n\n private class QuickFind {\n\n int[] id;\n int count;\n\n // Used for plotting amortized costs\n int operation;\n int currentCost;\n int totalCost;\n List total;\n\n public QuickFind(int size) {\n id = new int[size];\n count = size;\n\n operation = 1;\n currentCost = 0;\n totalCost = 0;\n total = new ArrayList<>();\n\n for (int i = 0; i < id.length; i++) {\n id[i] = i;\n }\n }\n\n public int count() {\n return count;\n }\n\n // O(1)\n public int find(int site) {\n currentCost++;\n return id[site];\n }\n\n // O(1)\n public boolean connected(int site1, int site2) {\n boolean isConnected = find(site1) == find(site2);\n\n if (isConnected) {\n updateCostAnalysis();\n }\n return isConnected;\n }\n\n // O(n)\n public void union(int site1, int site2) {\n int leaderId1 = find(site1);\n int leaderId2 = find(site2);\n\n if (leaderId1 == leaderId2) {\n return;\n }\n\n for (int i = 0; i < id.length; i++) {\n currentCost++; // 1 access for every site\n\n if (id[i] == leaderId1) {\n id[i] = leaderId2;\n\n currentCost++; // 1 access for every component merged\n }\n }\n\n count--;\n updateCostAnalysis();\n }\n\n private void updateCostAnalysis() {\n totalCost += currentCost;\n\n total.add(totalCost / operation);\n\n currentCost = 0;\n operation++;\n }\n }\n\n public static void main(String[] args) {\n int numberOfSites = 100;\n\n Exercise16_AmortizedCostsPlotsQF amortizedCostsPlots = new Exercise16_AmortizedCostsPlotsQF();\n QuickFind quickFind = amortizedCostsPlots.new QuickFind(numberOfSites);\n\n for (int i = 0; i < 150; i++) {\n int randomSite1 = StdRandom.uniform(numberOfSites);\n int randomSite2 = StdRandom.uniform(numberOfSites);\n\n if (quickFind.connected(randomSite1, randomSite2)) {\n continue;\n }\n\n quickFind.union(randomSite1, randomSite2);\n }\n\n StdOut.println(\"Components: \" + quickFind.count);\n\n amortizedCostsPlots.draw(quickFind);\n }\n\n private void draw(QuickFind quickFind) {\n SwingUtilities.invokeLater(new Runnable() {\n public void run() {\n GraphPanel graphPanel = new GraphPanel(\"QuickFind\", \"Amortized Cost Plot\",\n \"Number of Connections\", \"Number of Array Accesses\", quickFind.total);\n graphPanel.createAndShowGui();\n }\n });\n }\n}\n\n// Exercise16_AmortizedCostsPlotsQU.java\npackage chapter1.section5;\n\nimport util.GraphPanel;\nimport edu.princeton.cs.algs4.StdOut;\nimport edu.princeton.cs.algs4.StdRandom;\n\nimport javax.swing.*;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Created by Rene Argento on 08/12/16.\n */\npublic class Exercise16_AmortizedCostsPlotsQU {\n\n private class QuickUnion {\n int[] id;\n int count;\n\n // Used for plotting amortized costs\n int operation;\n int currentCost;\n int totalCost;\n List total;\n\n public QuickUnion(int size) {\n id = new int[size];\n count = size;\n\n operation = 1;\n currentCost = 0;\n totalCost = 0;\n total = new ArrayList<>();\n\n for (int i = 0; i < id.length; i++) {\n id[i] = i;\n }\n }\n\n public int count() {\n return count;\n }\n\n // O(1)\n public int find(int site) {\n currentCost++;\n\n while (site != id[site]) {\n currentCost++;\n\n site = id[site];\n }\n\n return site;\n }\n\n // O(1)\n public boolean connected(int site1, int site2) {\n boolean isConnected = find(site1) == find(site2);\n\n if (isConnected) {\n updateCostAnalysis();\n }\n\n return isConnected;\n }\n\n // O(n)\n public void union(int site1, int site2) {\n int leaderId1 = find(site1);\n int leaderId2 = find(site2);\n\n if (leaderId1 == leaderId2) {\n return;\n }\n\n id[leaderId1] = leaderId2;\n\n count--;\n\n currentCost++;\n updateCostAnalysis();\n }\n\n private void updateCostAnalysis() {\n totalCost += currentCost;\n\n total.add(totalCost / operation);\n\n currentCost = 0;\n operation++;\n }\n }\n\n public static void main(String[] args) {\n int numberOfSites = 100;\n\n Exercise16_AmortizedCostsPlotsQU amortizedCostsPlots = new Exercise16_AmortizedCostsPlotsQU();\n QuickUnion quickUnion = amortizedCostsPlots.new QuickUnion(numberOfSites);\n\n for (int i = 0; i < 150; i++) {\n int randomSite1 = StdRandom.uniform(numberOfSites);\n int randomSite2 = StdRandom.uniform(numberOfSites);\n\n if (quickUnion.connected(randomSite1, randomSite2)) {\n continue;\n }\n\n quickUnion.union(randomSite1, randomSite2);\n }\n\n StdOut.println(\"Components: \" + quickUnion.count);\n\n amortizedCostsPlots.draw(quickUnion);\n }\n\n private void draw(QuickUnion quickUnion) {\n SwingUtilities.invokeLater(new Runnable() {\n public void run() {\n GraphPanel graphPanel = new GraphPanel(\"QuickUnion\", \"Amortized Cost Plot\",\n \"Number of Connections\", \"Number of Array Accesses\", quickUnion.total);\n graphPanel.createAndShowGui();\n }\n });\n }\n}\n", "support_files": [], "metadata": {"number": "1.5.16", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.5, "section_title": "Case Study: Union-Find", "type": "Creative Problem", "code_execution": false}} {"question": "Random connections. Develop a UF client ErdosRenyi that takes an integer value N from the command line, generates random pairs of integers between 0 and N-1, calling connected() to determine if they are connected and then union() if not (as in our development client), looping until all sites are connected, and printing the number of connections generated. Package your program as a static method count() that takes N as argument and returns the number of connections and a main() that takes N from the command line, calls count(), and prints the returned value.", "answer": "```java\nimport edu.princeton.cs.algs4.StdOut;\nimport edu.princeton.cs.algs4.StdRandom;\nimport edu.princeton.cs.algs4.WeightedQuickUnionUF;\n\npublic class ErdosRenyi {\n public static int count(int n) {\n WeightedQuickUnionUF uf = new WeightedQuickUnionUF(n);\n int connections = 0;\n while (uf.count() > 1) {\n int p = StdRandom.uniformInt(n);\n int q = StdRandom.uniformInt(n);\n connections++;\n if (!uf.connected(p, q)) uf.union(p, q);\n }\n return connections;\n }\n\n public static void main(String[] args) {\n int n = Integer.parseInt(args[0]);\n StdOut.println(count(n));\n }\n}\n```", "support_files": [], "metadata": {"number": "1.5.17", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.5, "section_title": "Case Study: Union-Find", "type": "Creative Problem", "code_execution": false}} {"question": "Random grid generator. Write a program RandomGrid that takes an int value N from the command line, generates all the connections in an N-by-N grid, puts them in random order, randomly orients them (so that p q and q p are equally likely to occur), and prints the result to standard output. To randomly order the connections, use a RandomBag (see Exercise 1.3.34 on page 167). To encapsulate p and q in a single object, use the Connection nested class shown below. Package your program as two static methods: generate(), which takes N as argument and returns an array of connections, and main(), which takes N from the command line, calls generate(), and iterates through the returned array to print the connections.\nprivate class Connection \n{\n int p;\n int q;\n public Connection(int p, int q)\n { this.p = p; this.q = q; } \n}", "answer": "package chapter1.section5;\n\nimport chapter1.section3.Exercise34_RandomBag;\nimport edu.princeton.cs.algs4.StdOut;\nimport edu.princeton.cs.algs4.StdRandom;\n\npublic class RandomGrid {\n public static class Connection {\n int p;\n int q;\n Connection(int p, int q) {\n this.p = p;\n this.q = q;\n }\n }\n\n public static Connection[] generate(int n) {\n Exercise34_RandomBag bag = new Exercise34_RandomBag<>();\n for (int row = 0; row < n; row++) {\n for (int col = 0; col < n; col++) {\n int site = row * n + col;\n if (col + 1 < n) addRandomOrientation(bag, site, site + 1);\n if (row + 1 < n) addRandomOrientation(bag, site, site + n);\n }\n }\n\n Connection[] result = new Connection[bag.size()];\n int i = 0;\n for (Connection c : bag) result[i++] = c;\n return result;\n }\n\n private static void addRandomOrientation(Exercise34_RandomBag bag, int p, int q) {\n if (StdRandom.bernoulli()) bag.add(new Connection(p, q));\n else bag.add(new Connection(q, p));\n }\n\n public static void main(String[] args) {\n int n = Integer.parseInt(args[0]);\n for (Connection c : generate(n)) {\n StdOut.println(c.p + \" \" + c.q);\n }\n }\n}\n", "support_files": [], "metadata": {"number": "1.5.18", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.5, "section_title": "Case Study: Union-Find", "type": "Creative Problem", "code_execution": false}} {"question": "Animation. Write a RandomGrid client (see Exercise 1.5.18) that uses UnionFind as in our development client to check connectivity and uses StdDraw to draw the connections as they are processed.", "answer": "Use `RandomGrid.generate(N)` to produce all grid connections in random order, draw each connection as it is processed, and stop when the union-find structure reports one component.\n\n```java\npublic static void main(String[] args) {\n int n = Integer.parseInt(args[0]);\n int sites = n * n;\n WeightedQuickUnionUF uf = new WeightedQuickUnionUF(sites);\n StdDraw.setXscale(-1, n);\n StdDraw.setYscale(-1, n);\n\n for (RandomGrid.Connection c : RandomGrid.generate(n)) {\n int p = c.p;\n int q = c.q;\n drawConnection(p, q, n);\n if (!uf.connected(p, q)) uf.union(p, q);\n if (uf.count() == 1) break;\n }\n}\n```\n\nThe key correction is that `N` comes from the command line and every randomized grid connection is considered, not just a hard-coded 4-by-4 prefix.", "support_files": [], "metadata": {"number": "1.5.19", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.5, "section_title": "Case Study: Union-Find", "type": "Creative Problem", "code_execution": false}} {"question": "Doubling test for random grids. Develop a performance-testing client that takes an int value T from the command line and performs T trials of the following experiment: Use your client from Exercise 1.5.18 to generate the connections in an N-by-N square grid, randomly oriented and in random order, then use UnionFind to determine connectivity as in our development client, looping until all sites are connected. For each N, print the value of N, the average number of connections processed, and the ratio of the running time to the previous. Use your program to validate the hypotheses in the text that the running times for quick-find and quick-union are quadratic and weighted quick-union is near-linear. Note: As N doubles, the number of sites in the grid increases by a factor of 4, so expect a doubling factor of 16 for quadratic and 4 for linear.", "answer": "For each grid size `N`, run exactly `T` independent trials, average the number of connections processed and the elapsed time, then double `N`.\n\n```java\nfor (int n = 8; true; n += n) {\n Stopwatch timer = new Stopwatch();\n long totalConnections = 0;\n for (int t = 0; t < T; t++) {\n WeightedQuickUnionUF uf = new WeightedQuickUnionUF(n * n);\n int processed = 0;\n for (RandomGrid.Connection c : RandomGrid.generate(n)) {\n processed++;\n if (!uf.connected(c.p, c.q)) uf.union(c.p, c.q);\n if (uf.count() == 1) break;\n }\n totalConnections += processed;\n }\n double time = timer.elapsedTime();\n StdOut.printf(\"%8d %12.2f %10.3f\\n\", n, (double) totalConnections / T, time);\n}\n```\n\n`T` is the number of trials for each `N`; it is not the number of different grid sizes to test.", "support_files": [], "metadata": {"number": "1.5.25", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.5, "section_title": "Case Study: Union-Find", "type": "Experiment", "code_execution": false}} {"question": "Show, in the style of the example trace with Algorithm 2.1, how selection sort sorts the array E A S Y Q U E S T I O N.", "answer": "2.1.1\n\t\ta[]\ni min 0 1 2 3 4 5 6 7 8 9 10 11 \n\tE A S Y Q U E S T I O N\n0 1 E A S Y Q U E S T I O N\n1 1 A E S Y Q U E S T I O N\n2 6 A E S Y Q U E S T I O N\n3 9 A E E Y Q U S S T I O N\n4 11 A E E I Q U S S T Y O N\n5 10 A E E I N U S S T Y O Q\n6 11 A E E I N O S S T Y U Q\n7 7 A E E I N O Q S T Y U S\n8 11 A E E I N O Q S T Y U S\n9 11 A E E I N O Q S S Y U T\n10 10 A E E I N O Q S S T U Y\n11 11 A E E I N O Q S S T U Y\n\tA E E I N O Q S S T U Y\n", "support_files": [], "metadata": {"number": "2.1.1", "chapter": 2, "chapter_title": "Sorting", "section": 2.1, "section_title": "Elementary Sorts", "type": "Exercise", "code_execution": false}} {"question": "What is the maximum number of exchanges involving any particular element during selection sort? What is the average number of exchanges involving an element?", "answer": "2.1.2\nThe maximum number of exchanges involving any particular item during selection sort is N - 1.\nThis happens when the first item has the highest value in the unsorted array and the other values are sorted.\nFor example, in the array 4 1 2 3, the element 4 will be swapped N - 1 times.\nThe average number of exchanges involving an item is exactly 2, because there are exactly N exchanges and N items (and each exchange involves two items).\n\nReference: https://algs4.cs.princeton.edu/21elementary/\n", "support_files": [], "metadata": {"number": "2.1.2", "chapter": 2, "chapter_title": "Sorting", "section": 2.1, "section_title": "Elementary Sorts", "type": "Exercise", "code_execution": false}} {"question": "Give an example of an array of N items that maximizes the number of times the test a[j] < a[min] succeeds (and, therefore, min gets updated) during the operation of selection sort (Algorithm 2.1).", "answer": "2.1.3\nArray: H G F E D C B A\n\nThanks to QiotoF (https://github.com/QiotoF) for mentioning a better array solution for this exercise\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/76\n", "support_files": [], "metadata": {"number": "2.1.3", "chapter": 2, "chapter_title": "Sorting", "section": 2.1, "section_title": "Elementary Sorts", "type": "Exercise", "code_execution": false}} {"question": "Show, in the style of the example trace with Algorithm 2.2, how insertion sort sorts the array E A S Y Q U E S T I O N.", "answer": "2.1.4\n\t\ta[]\ni j 0 1 2 3 4 5 6 7 8 9 10 11 \n\tE A S Y Q U E S T I O N\n0 0 E A S Y Q U E S T I O N\n1 0 A E S Y Q U E S T I O N\n2 2 A E S Y Q U E S T I O N\n3 3 A E S Y Q U E S T I O N\n4 2 A E Q S Y U E S T I O N\n5 4 A E Q S U Y E S T I O N\n6 2 A E E Q S U Y S T I O N\n7 5 A E E Q S S U Y T I O N\n8 6 A E E Q S S T U Y I O N\n9 3 A E E I Q S S T U Y O N\n10 4 A E E I O Q S S T U Y N\n11 4 A E E I N O Q S S T U Y\n\tA E E I N O Q S S T U Y\n", "support_files": [], "metadata": {"number": "2.1.4", "chapter": 2, "chapter_title": "Sorting", "section": 2.1, "section_title": "Elementary Sorts", "type": "Exercise", "code_execution": false}} {"question": "For each of the two conditions in the inner for loop in insertion sort (Algorithm 2.2), describe an array of N items where that condition is always false when the loop terminates.", "answer": "2.1.5\n\nCondition 1: j > 0 -> When the array is reverse ordered\nZ Q K D C B A\n\nCondition 2: less(a[j], a[j - 1]) -> When the array is ordered\nA B C D E F G\n", "support_files": [], "metadata": {"number": "2.1.5", "chapter": 2, "chapter_title": "Sorting", "section": 2.1, "section_title": "Elementary Sorts", "type": "Exercise", "code_execution": false}} {"question": "Which method runs faster for an array with all keys identical, selection sort or insertion sort?", "answer": "2.1.6\n\nInsertion sort because it will only make one comparison with the previous element (per element) and won't exchange any elements,\nrunning in linear time. Selection sort will exchange each element with itself and will run in quadratic time.\n\nThanks to glucu (https://github.com/glucu) for correcting the number of exchanges done in selection sort.\n", "support_files": [], "metadata": {"number": "2.1.6", "chapter": 2, "chapter_title": "Sorting", "section": 2.1, "section_title": "Elementary Sorts", "type": "Exercise", "code_execution": false}} {"question": "Which method runs faster for an array in reverse order, selection sort or insertion sort?", "answer": "2.1.7\n\nSelection sort because even though both selection sort and insertion sort will run in quadratic time, selection sort will\nonly make N exchanges, while insertion sort will make N * N / 2 exchanges.\n\nThanks to LudekCizinsky (https://github.com/LudekCizinsky), rg9a27 (https://github.com/rg9a27) and\nBOTbkcd (https://github.com/BOTbkcd) for correcting the number of exchanges in selection sort.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/194 and\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/211\n", "support_files": [], "metadata": {"number": "2.1.7", "chapter": 2, "chapter_title": "Sorting", "section": 2.1, "section_title": "Elementary Sorts", "type": "Exercise", "code_execution": false}} {"question": "Suppose that we use insertion sort on a randomly ordered array where elements have only one of three values. Is the running time linear, quadratic, or something in between?", "answer": "2.1.8\n\nQuadratic. Insertion sort's running time is linear when the array is already sorted or all elements are equal.\nWith three possible values the running time quadratic.\n", "support_files": [], "metadata": {"number": "2.1.8", "chapter": 2, "chapter_title": "Sorting", "section": 2.1, "section_title": "Elementary Sorts", "type": "Exercise", "code_execution": false}} {"question": "Show, in the style of the example trace with Algorithm 2.3, how shellsort sorts the array E A S Y S H E L L S O R T Q U E S T I O N.", "answer": "2.1.9\n\t\t\t\ta[]\n h i j 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20\n\t E A S Y S H E L L S O R T Q U E S T I O N\n13 13 13 E A S Y S H E L L S O R T Q U E S T I O N\n13 14 14 E A S Y S H E L L S O R T Q U E S T I O N\n13 15 2 E A E Y S H E L L S O R T Q U S S T I O N\n13 16 3 E A E S S H E L L S O R T Q U S Y T I O N\n13 17 17 E A E S S H E L L S O R T Q U S Y T I O N\n13 18 18 E A E S S H E L L S O R T Q U S Y T I O N\n13 19 19 E A E S S H E L L S O R T Q U S Y T I O N\n13 20 20 E A E S S H E L L S O R T Q U S Y T I O N\n\t E A E S S H E L L S O R T Q U S Y T I O N\n 4 4 4 E A E S S H E L L S O R T Q U S Y T I O N\n 4 5 5 E A E S S H E L L S O R T Q U S Y T I O N\n 4 6 6 E A E S S H E L L S O R T Q U S Y T I O N\n 4 7 3 E A E L S H E S L S O R T Q U S Y T I O N\n 4 8 4 E A E L L H E S S S O R T Q U S Y T I O N\n 4 9 9 E A E L L H E S S S O R T Q U S Y T I O N\n 4 10 10 E A E L L H E S S S O R T Q U S Y T I O N\n 4 11 7 E A E L L H E R S S O S T Q U S Y T I O N\n 4 12 12 E A E L L H E R S S O S T Q U S Y T I O N\n 4 13 9 E A E L L H E R S Q O S T S U S Y T I O N\n 4 14 14 E A E L L H E R S Q O S T S U S Y T I O N\n 4 15 15 E A E L L H E R S Q O S T S U S Y T I O N\n 4 16 16 E A E L L H E R S Q O S T S U S Y T I O N\n 4 17 17 E A E L L H E R S Q O S T S U S Y T I O N\n 4 18 10 E A E L L H E R S Q I S T S O S Y T U O N\n 4 19 7 E A E L L H E O S Q I R T S O S Y T U S N\n 4 20 8 E A E L L H E O N Q I R S S O S T T U S Y\n\t E A E L L H E O N Q I R S S O S T T U S Y\n 1 1 0 A E E L L H E O N Q I R S S O S T T U S Y\n 1 2 2 A E E L L H E O N Q I R S S O S T T U S Y\n 1 3 3 A E E L L H E O N Q I R S S O S T T U S Y\n 1 4 4 A E E L L H E O N Q I R S S O S T T U S Y\n 1 5 3 A E E H L L E O N Q I R S S O S T T U S Y\n 1 6 3 A E E E H L L O N Q I R S S O S T T U S Y\n 1 7 7 A E E E H L L O N Q I R S S O S T T U S Y\n 1 8 7 A E E E H L L N O Q I R S S O S T T U S Y\n 1 9 9 A E E E H L L N O Q I R S S O S T T U S Y\n 1 10 5 A E E E H I L L N O Q R S S O S T T U S Y\n 1 11 11 A E E E H I L L N O Q R S S O S T T U S Y\n 1 12 12 A E E E H I L L N O Q R S S O S T T U S Y\n 1 13 13 A E E E H I L L N O Q R S S O S T T U S Y\n 1 14 10 A E E E H I L L N O O Q R S S S T T U S Y\n 1 15 15 A E E E H I L L N O O Q R S S S T T U S Y\n 1 16 16 A E E E H I L L N O O Q R S S S T T U S Y\n 1 17 17 A E E E H I L L N O O Q R S S S T T U S Y\n 1 18 18 A E E E H I L L N O O Q R S S S T T U S Y\n 1 19 16 A E E E H I L L N O O Q R S S S S T T U Y\n 1 20 20 A E E E H I L L N O O Q R S S S S T T U Y\n\t A E E E H I L L N O O Q R S S S S T T U Y\n", "support_files": [], "metadata": {"number": "2.1.9", "chapter": 2, "chapter_title": "Sorting", "section": 2.1, "section_title": "Elementary Sorts", "type": "Exercise", "code_execution": false}} {"question": "Why not use selection sort for h-sorting in shellsort?", "answer": "2.1.10\nInsertion sort is faster than selection sort for h-sorting because as \"h\" decreases, the array becomes partially sorted.\nInsertion sort makes less comparisons in partially sorted arrays than selection sort.\nAlso, when h-sorting, eventually h will have an increment value of 1.\nUsing selection sort with an increment value of 1 would be the same as using the standard selection sort algorithm from the beginning.\nThis would make the steps with the previous increments to be unnecessary work.\n\nThanks to jaeheonshim (https://github.com/jaeheonshim) for adding an extra reason not to use selection sort.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/254\n", "support_files": [], "metadata": {"number": "2.1.10", "chapter": 2, "chapter_title": "Sorting", "section": 2.1, "section_title": "Elementary Sorts", "type": "Exercise", "code_execution": false}} {"question": "Deck sort. Explain how you would put a deck of cards in order by suit (in the order spades, hearts, clubs, diamonds) and by rank within each suit, with the restriction that the cards must be laid out face down in a row, and the only allowed operations are to check the values of two cards and to exchange two cards (keeping them face down).", "answer": "2.1.13 - Deck sort\nI would use selection sort, comparing the cards first by suit, and if they have the same suit, by rank.\nAs we are dealing with physical objects it makes sense to minimize the number of swaps.\nWith selection sort it may be needed to look at more cards than insertion sort (twice as many in the average case),\nbut swaps will be required at most 52 times versus at most 676 times.\n\nThanks to zefrawg (https://github.com/zefrawg) and nedas-dev (https://github.com/nedas-dev) for improving this exercise:\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/198\n", "support_files": [], "metadata": {"number": "2.1.13", "chapter": 2, "chapter_title": "Sorting", "section": 2.1, "section_title": "Elementary Sorts", "type": "Creative Problem", "code_execution": false}} {"question": "Dequeue sort. Explain how you would sort a deck of cards, with the restriction that the only allowed operations are to look at the values of the top two cards, to exchange the top two cards, and to move the top card to the bottom of the deck.", "answer": "2.1.14 - Dequeue sort\nI would use a variation of bubble sort.\n\n1- I would compare both top cards and, if the top card were bigger than the second card, I would swap them.\n2- I would mark the top card, so I could know it was the first card (in this iteration) sent to the bottom of the deck.\n3- I would send the top card to the bottom of the deck.\n4- I would repeat steps 1 and 3 until the marked card becomes the second card in the deck\n5- I would send the top card to the bottom of the deck (and the marked card is now at the top, signaling that a iteration is over)\n6- If there were no swaps in this iteration, the deck is sorted. Otherwise, repeat steps 1 to 6.\n\nNice explanation here: \nhttp://stackoverflow.com/questions/38061140/sort-a-deck-of-cards\n", "support_files": [], "metadata": {"number": "2.1.14", "chapter": 2, "chapter_title": "Sorting", "section": 2.1, "section_title": "Elementary Sorts", "type": "Creative Problem", "code_execution": false}} {"question": "Expensive exchange. A clerk at a shipping company is charged with the task of rearranging a number of large crates in order of the time they are to be shipped out. Thus, the cost of compares is very low (just look at the labels) relative to the cost of exchanges (move the crates). The warehouse is nearly full—there is extra space sufficient to hold any one of the crates, but not two. What sorting method should the clerk use?", "answer": "2.1.15 - Expensive exchange\n\nThe clerk should use selection sort. Since the cost of compares is low, the N^2 complexity won't be a problem.\nAnd it guarantees a cost of at most N exchanges.\n", "support_files": [], "metadata": {"number": "2.1.15", "chapter": 2, "chapter_title": "Sorting", "section": 2.1, "section_title": "Elementary Sorts", "type": "Creative Problem", "code_execution": false}} {"question": "Shellsort best case. What is the best case for shellsort? Justify your answer.", "answer": "2.1.20 - Shellsort best case\n\nJust like insertion sort, the best case for shellsort is when the array is already ordered. This causes every element to \nbe compared only once in each iteration. \nThe time complexity in this case is O(n log n).\n\nGood explanation: https://www.toptal.com/developers/sorting-algorithms/shell-sort\nhttp://www.codingeek.com/algorithms/shell-sort-algorithm-explanation-implementation-and-complexity/\n", "support_files": [], "metadata": {"number": "2.1.20", "chapter": 2, "chapter_title": "Sorting", "section": 2.1, "section_title": "Elementary Sorts", "type": "Creative Problem", "code_execution": false}} {"question": "Give a trace, in the style of the trace given at the beginning of this section, showing how the keys A E Q S U Y E I N O S T are merged with the abstract in-place merge() method.", "answer": "2.2.1\n a[] aux[]\n k 0 1 2 3 4 5 6 7 8 9 10 11 i j 0 1 2 3 4 5 6 7 8 9 10 11\ninput A E Q S U Y E I N O S T - - - - - - - - - - - -\ncopy A E Q S U Y E I N O S T A E Q S U Y E I N O S T\n 0 6\n 0 A 1 6 A E Q S U Y E I N O S T\n 1 A E 2 6 E Q S U Y E I N O S T \n 2 A E E 2 7 Q S U Y E I N O S T \n 3 A E E I 2 8 Q S U Y I N O S T \n 4 A E E I N 2 9 Q S U Y N O S T \n 5 A E E I N O 2 10 Q S U Y O S T \n 6 A E E I N O Q 3 10 Q S U Y S T \n 7 A E E I N O Q S 4 10 S U Y S T \n 8 A E E I N O Q S S 4 11 U Y S T \n 9 A E E I N O Q S S T 4 12 U Y T\n 10 A E E I N O Q S S T U 5 12 U Y \n 11 A E E I N O Q S S T U Y 6 12 Y \nmerged result \n A E E I N O Q S S T U Y\n", "support_files": [], "metadata": {"number": "2.2.1", "chapter": 2, "chapter_title": "Sorting", "section": 2.2, "section_title": "Mergesort", "type": "Exercise", "code_execution": false}} {"question": "Give traces, in the style of the trace given with Algorithm 2.4, showing how the keys E A S Y Q U E S T I O N are sorted with top-down mergesort.", "answer": "2.2.2\n a[]\n 0 1 2 3 4 5 6 7 8 9 10 11\n E A S Y Q U E S T I O N\n merge(a, 0, 0, 1) A E S Y Q U E S T I O N\n merge(a, 0, 1, 2) A E S Y Q U E S T I O N\n merge(a, 3, 3, 4) A E S Q Y U E S T I O N\n merge(a, 3, 4, 5) A E S Q U Y E S T I O N\n merge(a, 0, 2, 5) A E Q S U Y E S T I O N\n merge(a, 6, 6, 7) A E Q S U Y E S T I O N\n merge(a, 6, 7, 8) A E Q S U Y E S T I O N\n merge(a, 9, 9, 10) A E Q S U Y E S T I O N\n merge(a, 9, 10, 11) A E Q S U Y E S T I N O\n merge(a, 6, 8, 11) A E Q S U Y E I N O S T\n merge(a, 0, 5, 11) A E E I N O Q S S T U Y\n A E E I N O Q S S T U Y\n", "support_files": [], "metadata": {"number": "2.2.2", "chapter": 2, "chapter_title": "Sorting", "section": 2.2, "section_title": "Mergesort", "type": "Exercise", "code_execution": false}} {"question": "Answer Exercise 2.2.2 for bottom-up mergesort.", "answer": "2.2.3\n\n a[]\n 0 1 2 3 4 5 6 7 8 9 10 11\n sz = 1 E A S Y Q U E S T I O N\n merge(a, 0, 0, 1) A E S Y Q U E S T I O N\n merge(a, 2, 2, 3) A E S Y Q U E S T I O N\n merge(a, 4, 4, 5) A E S Y Q U E S T I O N\n merge(a, 6, 6, 7) A E S Y Q U E S T I O N\n merge(a, 8, 8, 9) A E S Y Q U E S I T O N\n merge(a, 10, 10, 11) A E S Y Q U E S I T N O\n sz = 2\n merge(a, 0, 1, 3) A E S Y Q U E S I T N O\n merge(a, 4, 5, 7) A E S Y E Q S U I T N O\n merge(a, 8, 9, 11) A E S Y E Q S U I N O T\n sz = 4\n merge(a, 0, 3, 7) A E E Q S S U Y I N O T\nsz = 8\nmerge(a, 0, 7, 11) A E E I N O Q S S T U Y\n A E E I N O Q S S T U Y\n", "support_files": [], "metadata": {"number": "2.2.3", "chapter": 2, "chapter_title": "Sorting", "section": 2.2, "section_title": "Mergesort", "type": "Exercise", "code_execution": false}} {"question": "Does the abstract in-place merge produce proper output if and only if the two input subarrays are in sorted order? Prove your answer, or provide a counterexample.", "answer": "2.2.4\n\nYes. The merge phase uses two pointers that move comparing both subarray values.\nOnce it finds that one value is smaller than the other, it selects this value for the output without checking the other elements.\nIf one or more of the input subarrays are not sorted then some values would be considered in the wrong position during this comparison, leading to an incorrect output.\n", "support_files": [], "metadata": {"number": "2.2.4", "chapter": 2, "chapter_title": "Sorting", "section": 2.2, "section_title": "Mergesort", "type": "Exercise", "code_execution": false}} {"question": "Give the sequence of subarray sizes in the merges performed by both the top-down and the bottom-up mergesort algorithms, for N = 39.", "answer": "2.2.5\n\nTop-down mergesort: \n2, 3, 2, 5, 2, 3, 2, 5, 10, 2, 3, 2, 5, 2, 3, 2, 5, 10, 20, 2, 3, 2, 5, 2, 3, 2, 5, 10, 2, 3, 2, 5, 2, 2, 4, 9, 19, 39.\n\nBottom-up mergesort: \n2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 8, 8, 8, 8, 7, 16, 16, 32, 39.\n", "support_files": [], "metadata": {"number": "2.2.5", "chapter": 2, "chapter_title": "Sorting", "section": 2.2, "section_title": "Mergesort", "type": "Exercise", "code_execution": false}} {"question": "Write a program to compute the exact value of the number of array accesses used by top-down mergesort and by bottom-up mergesort. Use your program to plot the values for N from 1 to 512, and to compare the exact values with the upper bound 6N lg N.", "answer": "// Exercise6.java\npackage chapter2.section2;\n\nimport edu.princeton.cs.algs4.StdOut;\nimport edu.princeton.cs.algs4.StdRandom;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * Created by Rene Argento on 11/02/17.\n */\n// Thanks to ajfg93 (https://github.com/ajfg93) for correcting the array access count.\n// https://github.com/reneargento/algorithms-sedgewick-wayne/issues/12\npublic class Exercise6 {\n\n private enum SortType {\n TOP_DOWN_MERGESORT, BOTTOM_UP_MERGESORT;\n }\n\n private static int numberOfArrayAccesses;\n\n public static void main(String[] args) {\n\n int initialArraySize = 1;\n int numberOfExperiments = 512;\n\n Map allInputArrays = generateAllArrays(initialArraySize, numberOfExperiments);\n\n StdOut.printf(\"%6s %15s %11s\\n\", \"N\", \"Array Accesses\", \"Upper Bound\");\n StdOut.println();\n\n StdOut.printf(\"Top-Down MergeSort\");\n StdOut.println();\n doExperiments(SortType.TOP_DOWN_MERGESORT, 1, 512, allInputArrays);\n\n StdOut.println();\n StdOut.printf(\"Bottom-Up MergeSort\");\n StdOut.println();\n doExperiments(SortType.BOTTOM_UP_MERGESORT, 1, 512, allInputArrays);\n }\n\n private static void doExperiments(SortType sortType, int arrayLength, int numberOfExperiments,\n Map allInputArrays) {\n\n for (int i = 0; i < numberOfExperiments; i++) {\n\n numberOfArrayAccesses = 0;\n\n Comparable[] originalArray = allInputArrays.get(i);\n Comparable[] array = new Comparable[originalArray.length];\n System.arraycopy(originalArray, 0, array, 0, originalArray.length);\n\n if (sortType == SortType.TOP_DOWN_MERGESORT) {\n topDownMergeSort(array);\n } else if (sortType == SortType.BOTTOM_UP_MERGESORT) {\n bottomUpMergeSort(array);\n }\n\n printExperiment(arrayLength);\n\n arrayLength++;\n }\n }\n\n private static Map generateAllArrays(int initialArraySize, int numberOfExperiments) {\n\n Map allArrays = new HashMap<>();\n\n int arraySize = initialArraySize;\n\n for (int i = 0; i < numberOfExperiments; i++) {\n Comparable[] array = generateRandomArray(arraySize);\n allArrays.put(i, array);\n\n arraySize++;\n }\n\n return allArrays;\n }\n\n private static Comparable[] generateRandomArray(int arrayLength) {\n Comparable[] array = new Comparable[arrayLength];\n\n for (int i = 0; i < arrayLength; i++) {\n array[i] = StdRandom.uniform();\n }\n\n return array;\n }\n\n private static void topDownMergeSort(Comparable[] array) {\n Comparable[] aux = new Comparable[array.length];\n\n topDownMergeSort(array, aux, 0, array.length - 1);\n }\n\n private static void topDownMergeSort(Comparable[] array, Comparable[] aux, int low, int high) {\n\n if (high <= low) {\n return;\n }\n\n int middle = low + (high - low) / 2;\n\n topDownMergeSort(array, aux, low, middle);\n topDownMergeSort(array, aux, middle + 1, high);\n\n merge(array, aux, low, middle, high);\n }\n\n private static void bottomUpMergeSort(Comparable[] array) {\n\n Comparable[] aux = new Comparable[array.length];\n\n for (int size = 1; size < array.length; size = size + size) {\n\n for (int low = 0; low + size < array.length; low += size + size) {\n int high = Math.min(low + size + size - 1, array.length - 1);\n\n merge(array, aux, low, low + size - 1, high);\n }\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n private static void merge(Comparable[] array, Comparable[] aux, int low, int middle, int high) {\n for (int i = low; i <= high; i++) {\n aux[i] = array[i];\n\n numberOfArrayAccesses += 2;\n }\n\n int indexLeft = low;\n int indexRight = middle + 1;\n int arrayIndex = low;\n\n while (indexLeft <= middle && indexRight <= high) {\n if (aux[indexLeft].compareTo(aux[indexRight]) <= 0) {\n array[arrayIndex] = aux[indexLeft];\n indexLeft++;\n } else {\n array[arrayIndex] = aux[indexRight];\n indexRight++;\n }\n\n arrayIndex++;\n numberOfArrayAccesses += 4;\n }\n\n while (indexLeft <= middle) {\n array[arrayIndex] = aux[indexLeft];\n\n indexLeft++;\n arrayIndex++;\n\n numberOfArrayAccesses += 2;\n }\n }\n\n private static void printExperiment(int arrayLength) {\n double upperBound = 6 * arrayLength * (Math.log10(arrayLength) / Math.log10(2));\n\n StdOut.printf(\"%6d %15d %11.0f\\n\", arrayLength, numberOfArrayAccesses, upperBound);\n }\n}\n\nAdditional notes/results:\n2.2.6\n\n N Array Accesses Upper Bound\n\nTop-Down MergeSort\n 1 0 0\n 2 8 12\n 3 22 29\n 4 38 48\n 5 56 70\n 6 80 93\n 7 100 118\n 8 116 144\n 9 138 171\n 10 174 199\n 11 192 228\n 12 230 258\n 13 248 289\n 14 270 320\n 15 304 352\n 16 336 384\n 17 372 417\n 18 380 450\n 19 430 484\n 20 452 519\n 21 484 553\n 22 532 589\n 23 560 624\n 24 594 660\n 25 622 697\n 26 650 733\n 27 694 770\n 28 720 808\n 29 746 845\n 30 796 883\n 31 814 921\n 32 852 960\n 33 888 999\n 34 946 1038\n 35 972 1077\n 36 1012 1117\n 37 1036 1156\n 38 1052 1197\n 39 1108 1237\n 40 1164 1277\n 41 1164 1318\n 42 1238 1359\n 43 1278 1400\n 44 1308 1441\n 45 1368 1483\n 46 1412 1525\n 47 1402 1566\n 48 1472 1608\n 49 1492 1651\n 50 1546 1693\n 51 1556 1736\n 52 1632 1779\n 53 1640 1821\n 54 1678 1865\n 55 1738 1908\n 56 1770 1951\n 57 1814 1995\n 58 1846 2039\n 59 1880 2082\n 60 1926 2126\n 61 1950 2171\n 62 1994 2215\n 63 2034 2259\n 64 2092 2304\n 65 2122 2349\n 66 2150 2394\n 67 2184 2439\n 68 2248 2484\n 69 2262 2529\n 70 2344 2574\n 71 2374 2620\n 72 2432 2665\n 73 2474 2711\n 74 2498 2757\n 75 2564 2803\n 76 2590 2849\n 77 2662 2895\n 78 2704 2942\n 79 2740 2988\n 80 2768 3035\n 81 2856 3081\n 82 2872 3128\n 83 2912 3175\n 84 2968 3222\n 85 2976 3269\n 86 3020 3316\n 87 3112 3363\n 88 3122 3411\n 89 3174 3458\n 90 3194 3506\n 91 3248 3553\n 92 3342 3601\n 93 3362 3649\n 94 3398 3697\n 95 3426 3745\n 96 3508 3793\n 97 3532 3841\n 98 3598 3889\n 99 3618 3938\n 100 3638 3986\n 101 3738 4035\n 102 3768 4084\n 103 3824 4132\n 104 3836 4181\n 105 3902 4230\n 106 3900 4279\n 107 3966 4328\n 108 4008 4377\n 109 4058 4426\n 110 4104 4476\n 111 4152 4525\n 112 4180 4575\n 113 4226 4624\n 114 4272 4674\n 115 4312 4723\n 116 4318 4773\n 117 4452 4823\n 118 4480 4873\n 119 4450 4923\n 120 4552 4973\n 121 4604 5023\n 122 4624 5073\n 123 4712 5124\n 124 4752 5174\n 125 4738 5224\n 126 4810 5275\n 127 4816 5325\n 128 4848 5376\n 129 4928 5427\n 130 4960 5477\n 131 5062 5528\n 132 5152 5579\n 133 5156 5630\n 134 5196 5681\n 135 5240 5732\n 136 5318 5783\n 137 5338 5835\n 138 5390 5886\n 139 5466 5937\n 140 5444 5989\n 141 5536 6040\n 142 5624 6092\n 143 5680 6143\n 144 5682 6195\n 145 5758 6247\n 146 5838 6298\n 147 5886 6350\n 148 5918 6402\n 149 5956 6454\n 150 6002 6506\n 151 6042 6558\n 152 6062 6610\n 153 6178 6662\n 154 6188 6715\n 155 6212 6767\n 156 6260 6819\n 157 6388 6872\n 158 6446 6924\n 159 6482 6976\n 160 6526 7029\n 161 6586 7082\n 162 6630 7134\n 163 6650 7187\n 164 6682 7240\n 165 6766 7293\n 166 6846 7346\n 167 6902 7398\n 168 6966 7451\n 169 6954 7504\n 170 7028 7558\n 171 7008 7611\n 172 7118 7664\n 173 7166 7717\n 174 7226 7770\n 175 7262 7824\n 176 7304 7877\n 177 7328 7931\n 178 7396 7984\n 179 7464 8038\n 180 7508 8091\n 181 7568 8145\n 182 7598 8199\n 183 7694 8252\n 184 7684 8306\n 185 7772 8360\n 186 7758 8414\n 187 7882 8468\n 188 7910 8522\n 189 7924 8576\n 190 8012 8630\n 191 8026 8684\n 192 8140 8738\n 193 8176 8792\n 194 8248 8846\n 195 8270 8901\n 196 8318 8955\n 197 8374 9009\n 198 8406 9064\n 199 8466 9118\n 200 8548 9173\n 201 8528 9227\n 202 8598 9282\n 203 8642 9336\n 204 8772 9391\n 205 8786 9446\n 206 8800 9501\n 207 8862 9555\n 208 8946 9610\n 209 8986 9665\n 210 8964 9720\n 211 9094 9775\n 212 9128 9830\n 213 9114 9885\n 214 9170 9940\n 215 9294 9995\n 216 9308 10050\n 217 9368 10106\n 218 9394 10161\n 219 9484 10216\n 220 9528 10271\n 221 9574 10327\n 222 9666 10382\n 223 9614 10438\n 224 9706 10493\n 225 9778 10549\n 226 9860 10604\n 227 9890 10660\n 228 9980 10715\n 229 10036 10771\n 230 9982 10827\n 231 10086 10883\n 232 10128 10938\n 233 10136 10994\n 234 10218 11050\n 235 10292 11106\n 236 10328 11162\n 237 10368 11218\n 238 10416 11274\n 239 10474 11330\n 240 10478 11386\n 241 10614 11442\n 242 10610 11498\n 243 10636 11554\n 244 10686 11611\n 245 10856 11667\n 246 10888 11723\n 247 10890 11779\n 248 10882 11836\n 249 10952 11892\n 250 11010 11949\n 251 11094 12005\n 252 11110 12062\n 253 11128 12118\n 254 11260 12175\n 255 11260 12231\n 256 11310 12288\n 257 11388 12345\n 258 11470 12401\n 259 11456 12458\n 260 11488 12515\n 261 11640 12572\n 262 11672 12629\n 263 11722 12685\n 264 11722 12742\n 265 11880 12799\n 266 11876 12856\n 267 11918 12913\n 268 12036 12970\n 269 12094 13027\n 270 12094 13084\n 271 12150 13142\n 272 12228 13199\n 273 12308 13256\n 274 12366 13313\n 275 12398 13370\n 276 12448 13428\n 277 12500 13485\n 278 12524 13542\n 279 12686 13600\n 280 12684 13657\n 281 12754 13715\n 282 12804 13772\n 283 12882 13830\n 284 12922 13887\n 285 13016 13945\n 286 13062 14002\n 287 13066 14060\n 288 13110 14118\n 289 13194 14175\n 290 13298 14233\n 291 13328 14291\n 292 13480 14349\n 293 13476 14406\n 294 13446 14464\n 295 13596 14522\n 296 13628 14580\n 297 13628 14638\n 298 13656 14696\n 299 13754 14754\n 300 13832 14812\n 301 13852 14870\n 302 13896 14928\n 303 14020 14986\n 304 14010 15044\n 305 14090 15102\n 306 14196 15161\n 307 14230 15219\n 308 14288 15277\n 309 14368 15335\n 310 14336 15394\n 311 14394 15452\n 312 14464 15510\n 313 14532 15569\n 314 14612 15627\n 315 14626 15686\n 316 14704 15744\n 317 14762 15802\n 318 14834 15861\n 319 14854 15920\n 320 14974 15978\n 321 15002 16037\n 322 14986 16095\n 323 15142 16154\n 324 15148 16213\n 325 15168 16271\n 326 15250 16330\n 327 15316 16389\n 328 15402 16448\n 329 15494 16506\n 330 15454 16565\n 331 15546 16624\n 332 15632 16683\n 333 15674 16742\n 334 15774 16801\n 335 15746 16860\n 336 15854 16919\n 337 15922 16978\n 338 16032 17037\n 339 16016 17096\n 340 16104 17155\n 341 16112 17214\n 342 16188 17273\n 343 16288 17333\n 344 16274 17392\n 345 16328 17451\n 346 16370 17510\n 347 16458 17570\n 348 16544 17629\n 349 16606 17688\n 350 16666 17748\n 351 16758 17807\n 352 16730 17866\n 353 16744 17926\n 354 16848 17985\n 355 16930 18045\n 356 16980 18104\n 357 16986 18164\n 358 17092 18223\n 359 17110 18283\n 360 17202 18342\n 361 17204 18402\n 362 17276 18462\n 363 17350 18521\n 364 17358 18581\n 365 17444 18641\n 366 17472 18700\n 367 17570 18760\n 368 17678 18820\n 369 17706 18880\n 370 17758 18940\n 371 17814 19000\n 372 17882 19059\n 373 17926 19119\n 374 17994 19179\n 375 18040 19239\n 376 18110 19299\n 377 18194 19359\n 378 18166 19419\n 379 18248 19479\n 380 18318 19539\n 381 18300 19599\n 382 18424 19659\n 383 18510 19720\n 384 18530 19780\n 385 18644 19840\n 386 18640 19900\n 387 18714 19960\n 388 18794 20021\n 389 18726 20081\n 390 18806 20141\n 391 18966 20201\n 392 18970 20262\n 393 19102 20322\n 394 19106 20383\n 395 19154 20443\n 396 19166 20503\n 397 19394 20564\n 398 19296 20624\n 399 19294 20685\n 400 19408 20745\n 401 19318 20806\n 402 19522 20866\n 403 19666 20927\n 404 19698 20988\n 405 19716 21048\n 406 19714 21109\n 407 19868 21169\n 408 19958 21230\n 409 19878 21291\n 410 20006 21352\n 411 20024 21412\n 412 20030 21473\n 413 20168 21534\n 414 20290 21595\n 415 20402 21655\n 416 20328 21716\n 417 20380 21777\n 418 20430 21838\n 419 20520 21899\n 420 20478 21960\n 421 20630 22021\n 422 20672 22082\n 423 20724 22143\n 424 20780 22204\n 425 20856 22265\n 426 20928 22326\n 427 20994 22387\n 428 21032 22448\n 429 21028 22509\n 430 21150 22570\n 431 21210 22631\n 432 21228 22693\n 433 21388 22754\n 434 21336 22815\n 435 21432 22876\n 436 21406 22938\n 437 21486 22999\n 438 21532 23060\n 439 21648 23121\n 440 21732 23183\n 441 21732 23244\n 442 21820 23306\n 443 21904 23367\n 444 21946 23428\n 445 22018 23490\n 446 22040 23551\n 447 22106 23613\n 448 22136 23674\n 449 22218 23736\n 450 22200 23797\n 451 22224 23859\n 452 22414 23920\n 453 22364 23982\n 454 22472 24044\n 455 22438 24105\n 456 22580 24167\n 457 22706 24228\n 458 22754 24290\n 459 22748 24352\n 460 22794 24414\n 461 22894 24475\n 462 22848 24537\n 463 22982 24599\n 464 22982 24661\n 465 23116 24722\n 466 23198 24784\n 467 23214 24846\n 468 23252 24908\n 469 23314 24970\n 470 23426 25032\n 471 23414 25094\n 472 23466 25156\n 473 23560 25218\n 474 23620 25280\n 475 23702 25342\n 476 23812 25404\n 477 23762 25466\n 478 23812 25528\n 479 23894 25590\n 480 23954 25652\n 481 23980 25714\n 482 23962 25776\n 483 24070 25838\n 484 24134 25900\n 485 24174 25963\n 486 24174 26025\n 487 24268 26087\n 488 24372 26149\n 489 24440 26211\n 490 24508 26274\n 491 24474 26336\n 492 24644 26398\n 493 24752 26461\n 494 24778 26523\n 495 24772 26585\n 496 24830 26648\n 497 24746 26710\n 498 24922 26772\n 499 24994 26835\n 500 25066 26897\n 501 25156 26960\n 502 25154 27022\n 503 25194 27085\n 504 25224 27147\n 505 25366 27210\n 506 25292 27272\n 507 25442 27335\n 508 25462 27398\n 509 25506 27460\n 510 25660 27523\n 511 25576 27585\n 512 25710 27648\n\nBottom-Up MergeSort\n 1 0 0\n 2 8 12\n 3 22 29\n 4 38 48\n 5 60 70\n 6 84 93\n 7 100 118\n 8 116 144\n 9 156 171\n 10 188 199\n 11 206 228\n 12 228 258\n 13 254 289\n 14 270 320\n 15 304 352\n 16 336 384\n 17 408 417\n 18 434 450\n 19 478 484\n 20 468 519\n 21 510 553\n 22 548 589\n 23 562 624\n 24 588 660\n 25 644 697\n 26 658 733\n 27 694 770\n 28 716 808\n 29 748 845\n 30 808 883\n 31 814 921\n 32 852 960\n 33 986 999\n 34 1034 1038\n 35 1082 1077\n 36 1100 1117\n 37 1108 1156\n 38 1168 1197\n 39 1176 1237\n 40 1198 1277\n 41 1252 1318\n 42 1242 1359\n 43 1314 1400\n 44 1330 1441\n 45 1378 1483\n 46 1398 1525\n 47 1420 1566\n 48 1478 1608\n 49 1574 1651\n 50 1588 1693\n 51 1586 1736\n 52 1634 1779\n 53 1660 1821\n 54 1702 1865\n 55 1752 1908\n 56 1780 1951\n 57 1792 1995\n 58 1856 2039\n 59 1898 2082\n 60 1914 2126\n 61 1946 2171\n 62 1988 2215\n 63 2034 2259\n 64 2092 2304\n 65 2390 2349\n 66 2430 2394\n 67 2464 2439\n 68 2530 2484\n 69 2510 2529\n 70 2566 2574\n 71 2608 2620\n 72 2624 2665\n 73 2632 2711\n 74 2704 2757\n 75 2728 2803\n 76 2744 2849\n 77 2750 2895\n 78 2774 2942\n 79 2828 2988\n 80 2874 3035\n 81 2982 3081\n 82 2990 3128\n 83 3036 3175\n 84 3060 3222\n 85 3082 3269\n 86 3076 3316\n 87 3162 3363\n 88 3168 3411\n 89 3258 3458\n 90 3250 3506\n 91 3304 3553\n 92 3350 3601\n 93 3354 3649\n 94 3422 3697\n 95 3406 3745\n 96 3492 3793\n 97 3636 3841\n 98 3700 3889\n 99 3754 3938\n 100 3738 3986\n 101 3810 4035\n 102 3842 4084\n 103 3850 4132\n 104 3878 4181\n 105 3934 4230\n 106 3968 4279\n 107 3968 4328\n 108 4054 4377\n 109 4106 4426\n 110 4090 4476\n 111 4142 4525\n 112 4184 4575\n 113 4288 4624\n 114 4306 4674\n 115 4366 4723\n 116 4348 4773\n 117 4450 4823\n 118 4456 4873\n 119 4478 4923\n 120 4526 4973\n 121 4562 5023\n 122 4638 5073\n 123 4704 5124\n 124 4744 5174\n 125 4748 5224\n 126 4820 5275\n 127 4816 5325\n 128 4848 5376\n 129 5544 5427\n 130 5606 5477\n 131 5620 5528\n 132 5668 5579\n 133 5762 5630\n 134 5728 5681\n 135 5756 5732\n 136 5776 5783\n 137 5810 5835\n 138 5852 5886\n 139 5910 5937\n 140 5940 5989\n 141 5990 6040\n 142 5980 6092\n 143 6032 6143\n 144 6050 6195\n 145 6176 6247\n 146 6234 6298\n 147 6210 6350\n 148 6212 6402\n 149 6300 6454\n 150 6300 6506\n 151 6318 6558\n 152 6364 6610\n 153 6478 6662\n 154 6488 6715\n 155 6564 6767\n 156 6552 6819\n 157 6620 6872\n 158 6614 6924\n 159 6698 6976\n 160 6708 7029\n 161 6844 7082\n 162 6902 7134\n 163 6936 7187\n 164 6930 7240\n 165 6970 7293\n 166 7050 7346\n 167 7038 7398\n 168 7062 7451\n 169 7190 7504\n 170 7208 7558\n 171 7176 7611\n 172 7248 7664\n 173 7280 7717\n 174 7290 7770\n 175 7368 7824\n 176 7402 7877\n 177 7500 7931\n 178 7526 7984\n 179 7516 8038\n 180 7568 8091\n 181 7582 8145\n 182 7652 8199\n 183 7736 8252\n 184 7712 8306\n 185 7752 8360\n 186 7806 8414\n 187 7926 8468\n 188 7972 8522\n 189 7982 8576\n 190 8054 8630\n 191 8068 8684\n 192 8122 8738\n 193 8468 8792\n 194 8410 8846\n 195 8546 8901\n 196 8580 8955\n 197 8580 9009\n 198 8648 9064\n 199 8668 9118\n 200 8732 9173\n 201 8766 9227\n 202 8766 9282\n 203 8796 9336\n 204 8868 9391\n 205 8880 9446\n 206 8968 9501\n 207 8996 9555\n 208 9056 9610\n 209 9104 9665\n 210 9118 9720\n 211 9170 9775\n 212 9258 9830\n 213 9256 9885\n 214 9248 9940\n 215 9366 9995\n 216 9396 10050\n 217 9438 10106\n 218 9520 10161\n 219 9532 10216\n 220 9556 10271\n 221 9572 10327\n 222 9664 10382\n 223 9616 10438\n 224 9702 10493\n 225 9890 10549\n 226 9966 10604\n 227 10028 10660\n 228 10030 10715\n 229 10046 10771\n 230 10116 10827\n 231 10112 10883\n 232 10208 10938\n 233 10140 10994\n 234 10272 11050\n 235 10310 11106\n 236 10380 11162\n 237 10400 11218\n 238 10462 11274\n 239 10508 11330\n 240 10488 11386\n 241 10668 11442\n 242 10658 11498\n 243 10702 11554\n 244 10728 11611\n 245 10866 11667\n 246 10866 11723\n 247 10884 11779\n 248 10864 11836\n 249 10954 11892\n 250 11038 11949\n 251 11102 12005\n 252 11176 12062\n 253 11132 12118\n 254 11260 12175\n 255 11260 12231\n 256 11310 12288\n 257 12560 12345\n 258 12814 12401\n 259 12686 12458\n 260 12640 12515\n 261 12968 12572\n 262 12986 12629\n 263 12954 12685\n 264 13046 12742\n 265 13002 12799\n 266 13080 12856\n 267 13058 12913\n 268 13194 12970\n 269 13124 13027\n 270 13160 13084\n 271 13100 13142\n 272 13254 13199\n 273 13362 13256\n 274 13428 13313\n 275 13428 13370\n 276 13422 13428\n 277 13428 13485\n 278 13496 13542\n 279 13628 13600\n 280 13510 13657\n 281 13658 13715\n 282 13688 13772\n 283 13582 13830\n 284 13746 13887\n 285 13802 13945\n 286 13808 14002\n 287 13834 14060\n 288 13886 14118\n 289 13990 14175\n 290 14116 14233\n 291 14136 14291\n 292 14210 14349\n 293 14274 14406\n 294 14194 14464\n 295 14224 14522\n 296 14336 14580\n 297 14356 14638\n 298 14348 14696\n 299 14374 14754\n 300 14438 14812\n 301 14434 14870\n 302 14526 14928\n 303 14592 14986\n 304 14630 15044\n 305 14722 15102\n 306 14786 15161\n 307 14772 15219\n 308 14794 15277\n 309 14860 15335\n 310 14832 15394\n 311 14870 15452\n 312 14878 15510\n 313 14938 15569\n 314 15098 15627\n 315 15060 15686\n 316 15112 15744\n 317 15168 15802\n 318 15238 15861\n 319 15184 15920\n 320 15280 15978\n 321 15594 16037\n 322 15678 16095\n 323 15678 16154\n 324 15752 16213\n 325 15782 16271\n 326 15774 16330\n 327 15800 16389\n 328 15900 16448\n 329 15996 16506\n 330 15978 16565\n 331 16034 16624\n 332 16088 16683\n 333 16132 16742\n 334 16156 16801\n 335 16152 16860\n 336 16188 16919\n 337 16346 16978\n 338 16348 17037\n 339 16374 17096\n 340 16318 17155\n 341 16396 17214\n 342 16486 17273\n 343 16488 17333\n 344 16544 17392\n 345 16678 17451\n 346 16680 17510\n 347 16758 17570\n 348 16704 17629\n 349 16760 17688\n 350 16836 17748\n 351 16834 17807\n 352 16864 17866\n 353 17076 17926\n 354 17102 17985\n 355 17122 18045\n 356 17174 18104\n 357 17178 18164\n 358 17296 18223\n 359 17296 18283\n 360 17362 18342\n 361 17446 18402\n 362 17380 18462\n 363 17422 18521\n 364 17558 18581\n 365 17566 18641\n 366 17572 18700\n 367 17608 18760\n 368 17738 18820\n 369 17840 18880\n 370 17888 18940\n 371 17880 19000\n 372 17992 19059\n 373 18010 19119\n 374 18006 19179\n 375 18052 19239\n 376 18128 19299\n 377 18244 19359\n 378 18140 19419\n 379 18232 19479\n 380 18306 19539\n 381 18334 19599\n 382 18476 19659\n 383 18460 19720\n 384 18588 19780\n 385 19288 19840\n 386 19052 19900\n 387 19288 19960\n 388 19360 20021\n 389 19268 20081\n 390 19348 20141\n 391 19368 20201\n 392 19510 20262\n 393 19578 20322\n 394 19600 20383\n 395 19544 20443\n 396 19614 20503\n 397 19732 20564\n 398 19734 20624\n 399 19758 20685\n 400 19686 20745\n 401 19834 20806\n 402 19830 20866\n 403 19970 20927\n 404 20016 20988\n 405 19976 21048\n 406 20000 21109\n 407 20088 21169\n 408 20126 21230\n 409 20086 21291\n 410 20198 21352\n 411 20326 21412\n 412 20298 21473\n 413 20398 21534\n 414 20390 21595\n 415 20510 21655\n 416 20486 21716\n 417 20692 21777\n 418 20684 21838\n 419 20724 21899\n 420 20872 21960\n 421 20844 22021\n 422 20938 22082\n 423 20874 22143\n 424 20938 22204\n 425 21080 22265\n 426 21086 22326\n 427 21152 22387\n 428 21190 22448\n 429 21164 22509\n 430 21272 22570\n 431 21258 22631\n 432 21276 22693\n 433 21484 22754\n 434 21476 22815\n 435 21592 22876\n 436 21568 22938\n 437 21596 22999\n 438 21534 23060\n 439 21692 23121\n 440 21732 23183\n 441 21766 23244\n 442 21854 23306\n 443 21864 23367\n 444 21900 23428\n 445 22006 23490\n 446 22014 23551\n 447 22042 23613\n 448 22134 23674\n 449 22474 23736\n 450 22382 23797\n 451 22458 23859\n 452 22610 23920\n 453 22578 23982\n 454 22666 24044\n 455 22542 24105\n 456 22690 24167\n 457 22838 24228\n 458 22876 24290\n 459 22898 24352\n 460 22942 24414\n 461 22950 24475\n 462 22958 24537\n 463 23034 24599\n 464 22986 24661\n 465 23264 24722\n 466 23278 24784\n 467 23328 24846\n 468 23338 24908\n 469 23316 24970\n 470 23486 25032\n 471 23500 25094\n 472 23496 25156\n 473 23570 25218\n 474 23682 25280\n 475 23672 25342\n 476 23688 25404\n 477 23876 25466\n 478 23826 25528\n 479 23852 25590\n 480 24000 25652\n 481 24198 25714\n 482 24114 25776\n 483 24144 25838\n 484 24198 25900\n 485 24202 25963\n 486 24248 26025\n 487 24312 26087\n 488 24420 26149\n 489 24522 26211\n 490 24564 26274\n 491 24554 26336\n 492 24614 26398\n 493 24652 26461\n 494 24764 26523\n 495 24814 26585\n 496 24744 26648\n 497 24810 26710\n 498 25000 26772\n 499 25044 26835\n 500 25024 26897\n 501 25152 26960\n 502 25178 27022\n 503 25240 27085\n 504 25226 27147\n 505 25282 27210\n 506 25350 27272\n 507 25442 27335\n 508 25536 27398\n 509 25526 27460\n 510 25672 27523\n 511 25576 27585\n 512 25710 27648\n", "support_files": [], "metadata": {"number": "2.2.6", "chapter": 2, "chapter_title": "Sorting", "section": 2.2, "section_title": "Mergesort", "type": "Exercise", "code_execution": false}} {"question": "Show that the number of compares used by mergesort is monotonically increasing (C(N+1) > C(N) for all N > 0).", "answer": "For top-down mergesort in the worst case, the number of compares C(N) satisfies\n\nC(1) = 0\nC(N) = C(floor(N/2)) + C(ceil(N/2)) + N - 1\n\nThe merge of two sorted subarrays whose total length is N uses at most N - 1 compares. To prove C(N + 1) > C(N), compare the recurrences. Increasing the input size by one increases one of the two recursive subproblem sizes by one and increases the final merge term from N - 1 to N. By induction, the recursive part cannot decrease, and the merge term increases by exactly one. Therefore C(N + 1) > C(N) for all N > 0.\n\nThis statement is about the worst-case compare count. A randomized experiment on particular inputs can show non-monotone realized compare counts because a merge may finish early when one side is exhausted.\n", "support_files": [], "metadata": {"number": "2.2.7", "chapter": 2, "chapter_title": "Sorting", "section": 2.2, "section_title": "Mergesort", "type": "Exercise", "code_execution": false}} {"question": "Suppose that Algorithm 2.4 is modified to skip the call on merge() whenever a[mid] <= a[mid+1]. Prove that the number of compares used to mergesort a sorted array is linear.", "answer": "2.2.8\n\nSince the array is already sorted, merge() will always be skipped. So there won't be any values copied from the aux array to the original array (only values copied from the original array to the aux array).\nTherefore, there will be only 1 compare for every subarray, which is a linear operation.\n\nWhen N is a power of 2, the number of compares will satisfy the recurrence\nT(N) = 2 T(N/2) + 1, with T(1) = 0\n", "support_files": [], "metadata": {"number": "2.2.8", "chapter": 2, "chapter_title": "Sorting", "section": 2.2, "section_title": "Mergesort", "type": "Exercise", "code_execution": false}} {"question": "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 that does not use a static array. Do not make aux[] local to merge() (see the Q&A for this section). Hint: Pass the auxiliary array as an argument to the recursive sort().", "answer": "package chapter2.section2;\n\nimport edu.princeton.cs.algs4.StdRandom;\n\n/**\n * Created by Rene Argento on 11/02/17.\n */\npublic class Exercise9 {\n\n public static void main(String[] args) {\n\n Comparable[] array = generateRandomArray(1000);\n topDownMergeSort(array);\n }\n\n private static Comparable[] generateRandomArray(int arrayLength) {\n Comparable[] array = new Comparable[arrayLength];\n\n for (int i = 0; i < arrayLength; i++) {\n array[i] = StdRandom.uniform();\n }\n\n return array;\n }\n\n private static void topDownMergeSort(Comparable[] array) {\n Comparable[] aux = new Comparable[array.length];\n\n topDownMergeSort(array, aux, 0, array.length - 1);\n }\n\n private static void topDownMergeSort(Comparable[] array, Comparable[] aux, int low, int high) {\n\n if (high <= low) {\n return;\n }\n\n int middle = low + (high - low) / 2;\n\n topDownMergeSort(array, aux, low, middle);\n topDownMergeSort(array, aux, middle + 1, high);\n\n merge(array, aux, low, middle, high);\n }\n\n @SuppressWarnings(\"unchecked\")\n private static void merge(Comparable[] array, Comparable[] aux, int low, int middle, int high) {\n for (int i = low; i <= high; i++) {\n aux[i] = array[i];\n }\n\n int indexLeft = low;\n int indexRight = middle + 1;\n int arrayIndex = low;\n\n while (indexLeft <= middle && indexRight <= high) {\n if (aux[indexLeft].compareTo(aux[indexRight]) <= 0) {\n array[arrayIndex] = aux[indexLeft];\n indexLeft++;\n } else {\n array[arrayIndex] = aux[indexRight];\n indexRight++;\n }\n\n arrayIndex++;\n }\n\n while (indexLeft <= middle) {\n array[arrayIndex] = aux[indexLeft];\n\n indexLeft++;\n arrayIndex++;\n }\n }\n}\n", "support_files": [], "metadata": {"number": "2.2.9", "chapter": 2, "chapter_title": "Sorting", "section": 2.2, "section_title": "Mergesort", "type": "Exercise", "code_execution": false}} {"question": "Faster merge. Implement a version of merge() that copies the second half of a[] to aux[] in decreasing order and then does the merge back to a[]. This change allows you to remove the code to test that each of the halves has been exhausted from the inner loop. Note: The resulting sort is not stable (see page 341).", "answer": "package chapter2.section2;\n\nimport util.ArrayGenerator;\n\n/**\n * Created by Rene Argento on 12/02/17.\n */\n@SuppressWarnings(\"rawtypes\")\npublic class Exercise10_FasterMerge {\n\n public static void main(String[] args) {\n Comparable[] array = ArrayGenerator.generateRandomArray(1000);\n topDownMergeSort(array);\n }\n\n public static void topDownMergeSort(Comparable[] array) {\n Comparable[] aux = new Comparable[array.length];\n topDownMergeSort(array, aux, 0, array.length - 1);\n }\n\n private static void topDownMergeSort(Comparable[] array, Comparable[] aux, int low, int high) {\n if (high <= low) {\n return;\n }\n int middle = low + (high - low) / 2;\n\n topDownMergeSort(array, aux, low, middle);\n topDownMergeSort(array, aux, middle + 1, high);\n merge(array, aux, low, middle, high);\n }\n\n @SuppressWarnings(\"unchecked\")\n private static void merge(Comparable[] array, Comparable[] aux, int low, int middle, int high) {\n int auxIndex = low;\n\n for (int i = low; i <= middle; i++) {\n aux[auxIndex] = array[i];\n auxIndex++;\n }\n\n for (int i = high; i >= middle + 1; i--) {\n aux[auxIndex] = array[i];\n auxIndex++;\n }\n\n int indexLeft = low;\n int indexRight = high;\n int arrayIndex = low;\n\n while (indexLeft <= middle) {\n if (aux[indexLeft].compareTo(aux[indexRight]) <= 0) {\n array[arrayIndex] = aux[indexLeft];\n indexLeft++;\n } else {\n array[arrayIndex] = aux[indexRight];\n indexRight--;\n }\n arrayIndex++;\n }\n }\n}\n", "support_files": [], "metadata": {"number": "2.2.10", "chapter": 2, "chapter_title": "Sorting", "section": 2.2, "section_title": "Mergesort", "type": "Creative Problem", "code_execution": false}} {"question": "Lower bound for average case. Prove that the expected number of compares used by any compare-based sorting algorithm must be at least ~N lg N (assuming that all possible orderings of the input are equally likely). Hint: The expected number of compares is at least the external path length of the compare tree (the sum of the lengths of the paths from the root to all leaves), which is minimized when it is balanced.", "answer": "2.2.13 - Lower bound for average case\n\nBased on: https://www.cs.cmu.edu/~avrim/451f11/lectures/lect0913.pdf\n\nTheorem: For any deterministic comparison-based sorting algorithm A, the average-case number of comparisons (the number of comparisons on average on a randomly chosen permutation of n distinct elements) is at least log2(n!) rounded up.\n\nBased on the Stirlings approximation, log2(n!) -> ~ N log2(N)\n\nProof: Let S be the set of all n! possible orderings of n distinct elements. \nThese each require a different permutation to be produced as output. \nLet's now build out the entire decision tree for algorithm A on S: the tree we get by looking at all the different question/answer paths we get by running algorithm A on the inputs in S.\nThis tree has n! leaves, where the depth of a leaf is the number of comparisons performed by the sorting algorithm on that input. \nOur goal is to show that the average depth of the leaves must be at least log2(n!) rounded up (for the worst-case, we only care about the maximum depth).\n\nIf the tree is completely balanced, then each leaf is at depth log2(n!) (rounded up or rounded down) and we are done. \nTo prove the theorem, we just need to show that out of all binary trees on a given number of leaves, the one that minimizes their average depth is a completely balanced tree. \nThis is not too hard to see: given some unbalanced tree, we take two sibling leaves at largest depth and move them to be children of the leaf of smallest depth. \nSince the difference between the largest depth and the smallest depth is at least 2 (otherwise the tree would be balanced), this operation reduces the average depth of the leaves. \nSpecifically, if the smaller depth is \"d\" and the larger depth is \"D\", we have removed two leaves of depth \"D\" and one of depth \"d\", and we have added two leaves of depth \"d + 1\" and one of depth \"D - 1\".\nSince any unbalanced tree can be modified to have a smaller average depth, such a tree cannot be one that minimizes average depth, and therefore the tree of smallest average depth must in fact be balanced.\n", "support_files": [], "metadata": {"number": "2.2.13", "chapter": 2, "chapter_title": "Sorting", "section": 2.2, "section_title": "Mergesort", "type": "Creative Problem", "code_execution": false}} {"question": "Merging sorted queues. Develop a static method that takes two queues of sorted items as arguments and returns a queue that results from merging the queues into sorted order.", "answer": "package chapter2.section2;\n\nimport edu.princeton.cs.algs4.Queue;\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 13/02/17.\n */\n// Thanks to dragon-dreamer (https://github.com/dragon-dreamer) for suggesting a simpler method to merge the queues:\n// https://github.com/reneargento/algorithms-sedgewick-wayne/issues/107\n@SuppressWarnings(\"unchecked\")\npublic class Exercise14_MergingSortedQueues {\n\n public static void main(String[] args) {\n\n Queue queue1 = new Queue<>();\n queue1.enqueue(1);\n queue1.enqueue(3);\n queue1.enqueue(5);\n queue1.enqueue(7);\n queue1.enqueue(9);\n\n Queue queue2 = new Queue<>();\n queue2.enqueue(2);\n queue2.enqueue(4);\n queue2.enqueue(6);\n queue2.enqueue(8);\n\n Queue mergedQueue = mergeQueues(queue1, queue2);\n\n StdOut.print(\"Merged queues: \");\n for (Comparable item : mergedQueue) {\n StdOut.print(item + \" \");\n }\n StdOut.println(\"\\nExpected: 1 2 3 4 5 6 7 8 9\");\n }\n\n public static Queue mergeQueues(Queue queue1, Queue queue2) {\n Queue mergedQueue = new Queue<>();\n\n while (!queue1.isEmpty() && !queue2.isEmpty()) {\n if (queue1.peek().compareTo(queue2.peek()) <= 0) {\n mergedQueue.enqueue(queue1.dequeue());\n } else {\n mergedQueue.enqueue(queue2.dequeue());\n }\n }\n\n while (!queue1.isEmpty()) {\n mergedQueue.enqueue(queue1.dequeue());\n }\n while (!queue2.isEmpty()) {\n mergedQueue.enqueue(queue2.dequeue());\n }\n return mergedQueue;\n }\n}\n", "support_files": [], "metadata": {"number": "2.2.14", "chapter": 2, "chapter_title": "Sorting", "section": 2.2, "section_title": "Mergesort", "type": "Creative Problem", "code_execution": false}} {"question": "Bottom-up queue mergesort. Develop a bottom-up mergesort implementation based on the following approach: Given N items, create N queues, each containing one of the items. Create a queue of the N queues. Then repeatedly apply the merging operation of Exercise 2.2.14 to the first two queues and reinsert the merged queue at the end. Repeat until the queue of queues contains only one queue.", "answer": "package chapter2.section2;\n\nimport edu.princeton.cs.algs4.Queue;\nimport edu.princeton.cs.algs4.StdOut;\nimport edu.princeton.cs.algs4.StdRandom;\n\n/**\n * Created by Rene Argento on 13/02/17.\n */\npublic class Exercise15_BottomUpQueueMergesort {\n\n public static void main(String[] args) {\n\n Comparable[] array = generateRandomArray(10);\n\n Queue> mergedQueue = bottomUpQueueMergesort(array);\n\n StdOut.println(\"Merged queues:\");\n for (Comparable item : mergedQueue.peek()) {\n StdOut.print(item + \" \");\n }\n }\n\n private static Comparable[] generateRandomArray(int arrayLength) {\n Comparable[] array = new Comparable[arrayLength];\n\n for (int i = 0; i < arrayLength; i++) {\n array[i] = StdRandom.uniform();\n }\n\n return array;\n }\n\n private static Queue> bottomUpQueueMergesort(Comparable[] array) {\n Queue> sortedQueues = new Queue<>();\n\n for (Comparable value : array) {\n Queue queue = new Queue<>();\n queue.enqueue(value);\n\n sortedQueues.enqueue(queue);\n }\n\n while (sortedQueues.size() > 1) {\n Queue queue1 = sortedQueues.dequeue();\n Queue queue2 = sortedQueues.dequeue();\n\n Queue mergedQueue = Exercise14_MergingSortedQueues.mergeQueues(queue1, queue2);\n sortedQueues.enqueue(mergedQueue);\n }\n return sortedQueues;\n }\n}\n", "support_files": [], "metadata": {"number": "2.2.15", "chapter": 2, "chapter_title": "Sorting", "section": 2.2, "section_title": "Mergesort", "type": "Creative Problem", "code_execution": false}} {"question": "Indirect sort. Develop and implement a version of mergesort that does not rearrange the array, but returns an int[] array perm such that perm[i] is the index of the ith smallest entry in the array.", "answer": "package chapter2.section2;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 18/02/17.\n */\n//Based on http://algs4.cs.princeton.edu/22mergesort/Merge.java.html\npublic class Exercise20_IndexSort {\n\n public static void main(String[] args) {\n\n Comparable[] array1 = generateArray1();\n int[] indexSortedArray1 = indexSort(array1);\n\n int[] expectedIndexSortedArray1 = {5, 4, 6, 3, 7, 2, 8, 1, 9, 0};\n if (validate(expectedIndexSortedArray1, indexSortedArray1)) {\n StdOut.println(\"Index sorted OK\");\n } else {\n StdOut.println(\"Index sorted NOT OK\");\n }\n StdOut.println(\"Expected: Index sorted OK\\n\");\n\n Comparable[] array2 = generateArray2();\n int[] indexSortedArray2 = indexSort(array2);\n\n int[] expectedIndexSortedArray2 = {3, 2, 1, 0};\n if (validate(expectedIndexSortedArray2, indexSortedArray2)) {\n StdOut.println(\"Index sorted OK\");\n } else {\n StdOut.println(\"Index sorted NOT OK\");\n }\n StdOut.println(\"Expected: Index sorted OK\");\n }\n\n private static Comparable[] generateArray1() {\n Comparable[] array = new Comparable[10];\n\n array[0] = 10; //Correct index: 9\n array[1] = 9; //Correct index: 7\n array[2] = 8; //Correct index: 5\n array[3] = 7; //Correct index: 3\n array[4] = 6; //Correct index: 1\n array[5] = 5; //Correct index: 0\n array[6] = 6; //Correct index: 2\n array[7] = 7; //Correct index: 4\n array[8] = 8; //Correct index: 6\n array[9] = 9; //Correct index: 8\n\n //Expected: [5, 4, 6, 3, 7, 2, 8, 1, 9, 0]\n\n return array;\n }\n\n private static Comparable[] generateArray2() {\n\n Comparable[] array = new Comparable[4];\n\n array[0] = 4; //Correct index: 3\n array[1] = 3; //Correct index: 2\n array[2] = 2; //Correct index: 1\n array[3] = 1; //Correct index: 0\n\n //Expected: [3, 2, 1, 0]\n\n return array;\n }\n\n private static int[] indexSort(Comparable[] array) {\n int[] aux = new int[array.length];\n int[] indexSort = new int[array.length];\n\n for (int i = 0; i < array.length; i++) {\n indexSort[i] = i;\n }\n\n indexSort(array, aux, indexSort, 0, array.length - 1);\n return indexSort;\n }\n\n private static void indexSort(Comparable[] array, int[] aux, int[] indexSort, int low, int high) {\n if (low >= high) {\n return;\n }\n\n int middle = low + (high - low) / 2;\n\n indexSort(array, aux, indexSort, low, middle);\n indexSort(array, aux, indexSort, middle + 1, high);\n\n merge(array, aux, indexSort, low, middle, high);\n }\n\n @SuppressWarnings(\"unchecked\")\n private static void merge(Comparable[] array, int[] aux, int[] indexSort, int low, int middle, int high) {\n for (int i = low; i <= high; i++) {\n aux[i] = indexSort[i];\n }\n\n int leftIndex = low;\n int rightIndex = middle + 1;\n int arrayIndex = low;\n\n while (leftIndex <= middle && rightIndex <= high) {\n if (array[aux[leftIndex]].compareTo(array[aux[rightIndex]]) <= 0) {\n indexSort[arrayIndex] = aux[leftIndex];\n\n leftIndex++;\n } else {\n indexSort[arrayIndex] = aux[rightIndex];\n rightIndex++;\n }\n\n arrayIndex++;\n }\n\n while (leftIndex <= middle) {\n indexSort[arrayIndex] = aux[leftIndex];\n leftIndex++;\n arrayIndex++;\n }\n }\n\n private static boolean validate(int[] expectedIndexSortedArray, int[] indexSortedArray) {\n if (expectedIndexSortedArray.length != indexSortedArray.length) {\n return false;\n }\n\n for (int i = 0; i < expectedIndexSortedArray.length; i++) {\n if (expectedIndexSortedArray[i] != indexSortedArray[i]) {\n return false;\n }\n }\n return true;\n }\n}\n", "support_files": [], "metadata": {"number": "2.2.20", "chapter": 2, "chapter_title": "Sorting", "section": 2.2, "section_title": "Mergesort", "type": "Creative Problem", "code_execution": false}} {"question": "Show, in the style of the trace given with partition(), how that method partitions the array E A S Y Q U E S T I O N.", "answer": "2.3.1\n a[]\n i j 0 1 2 3 4 5 6 7 8 9 10 11\ninitial values 0 12 E A S Y Q U E S T I O N\nscan left, scan right 2 6 E A S Y Q U E S T I O N\nexchange 2 6 E A E Y Q U S S T I O N\nscan left, scan right 3 2 E A E Y Q U S S T I O N\nfinal exchange 2 E A E Y Q U S S T I O N\nresult 2 E A E Y Q U S S T I O N\n\nThanks to Forest-Lee (https://github.com/Forest-Lee) for mentioning that we should have the last line with the result.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/292\n", "support_files": [], "metadata": {"number": "2.3.1", "chapter": 2, "chapter_title": "Sorting", "section": 2.3, "section_title": "Quicksort", "type": "Exercise", "code_execution": false}} {"question": "Show, in the style of the quicksort trace given in this section, how quicksort sorts the array E A S Y Q U E S T I O N (for the purposes of this exercise, ignore the initial shuffle).", "answer": "2.3.2\n a[] \nlo j hi 0 1 2 3 4 5 6 7 8 9 10 11\n E A S Y Q U E S T I O N\n 0 2 11 E A E Y Q U S S T I O N\n 0 1 1 A E E Y Q U S S T I O N\n 0 0 A E E Y Q U S S T I O N\n 3 11 11 A E E N Q U S S T I O Y\n 3 4 10 A E E I N U S S T Q O Y\n 3 3 A E E I N U S S T Q O Y\n 5 10 10 A E E I N O S S T Q U Y\n 5 5 9 A E E I N O S S T Q U Y\n 6 7 9 A E E I N O Q S T S U Y\n 6 6 A E E I N O Q S T S U Y\n 8 9 9 A E E I N O Q S S T U Y\n A E E I N O Q S S T U Y\n\nThanks to Shahin Ansari for finding that one extra line in the trace could be removed.\n", "support_files": [], "metadata": {"number": "2.3.2", "chapter": 2, "chapter_title": "Sorting", "section": 2.3, "section_title": "Quicksort", "type": "Exercise", "code_execution": false}} {"question": "What is the maximum number of times during the execution of Quick.sort() that the largest item can be exchanged, for an array of length N?", "answer": "2.3.3\n\nThe maximum number of times during the execution of Quick.sort() that the largest item can be exchanged, for an\narray of length N is floor(N / 2).\nNote that this answer is specific to this version of quicksort in which the first element is always selected as the pivot.\n\nReference: https://stackoverflow.com/questions/43263249/number-of-largest-element-exchanges-for-quicksort\n\nThanks to ajfg93 (https://github.com/ajfg93) for correcting this exercise.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/30\n", "support_files": [], "metadata": {"number": "2.3.3", "chapter": 2, "chapter_title": "Sorting", "section": 2.3, "section_title": "Quicksort", "type": "Exercise", "code_execution": false}} {"question": "Suppose that the initial random shuffle is omitted. Give six arrays of ten elements for which Quick.sort() uses the worst-case number of compares.", "answer": "2.3.4\n\n[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n[2, 3, 4, 5, 6, 7, 8, 9, 10, 11]\n[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]\n[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]\n[11, 10, 9, 8, 7, 6, 5, 4, 3, 2]\n[12, 11, 10, 9, 8, 7, 6, 5, 4, 3]\n", "support_files": [], "metadata": {"number": "2.3.4", "chapter": 2, "chapter_title": "Sorting", "section": 2.3, "section_title": "Quicksort", "type": "Exercise", "code_execution": false}} {"question": "Give a code fragment that sorts an array that is known to consist of items having just two distinct keys.", "answer": "package chapter2.section3;\n\nimport edu.princeton.cs.algs4.StdOut;\nimport util.ArrayGenerator;\n\nimport java.util.StringJoiner;\n\n/**\n * Created by Rene Argento on 04/03/17.\n */\npublic class Exercise5 {\n\n public static void main(String[] args) {\n int arrayLength = Integer.parseInt(args[0]);\n Comparable array[] = ArrayGenerator.generateRandomArrayWith2Values(arrayLength);\n\n StringJoiner originalArray = new StringJoiner(\" \");\n for (Comparable element : array) {\n originalArray.add(String.valueOf(element));\n }\n StdOut.println(\"Original array: \" + originalArray);\n\n sort3WayPartitioning(array);\n\n StringJoiner sortedArray = new StringJoiner(\" \");\n for (Comparable element : array) {\n sortedArray.add(String.valueOf(element));\n }\n StdOut.println(\"Sorted array: \" + sortedArray);\n }\n\n @SuppressWarnings(\"unchecked\")\n private static void sort3WayPartitioning(Comparable[] array) {\n\n int lt = 0;\n int gt = array.length - 1;\n int i = lt + 1;\n\n Comparable pivot = array[0];\n\n while (i <= gt) {\n int comparison = array[i].compareTo(pivot);\n\n if (comparison < 0) {\n exchange(array, lt, i);\n lt++;\n i++;\n } else if (comparison > 0) {\n exchange(array, i, gt);\n gt--;\n } else {\n i++;\n }\n }\n }\n\n private static void exchange(Comparable[] array, int position1, int position2) {\n Comparable temp = array[position1];\n array[position1] = array[position2];\n array[position2] = temp;\n }\n}\n", "support_files": [], "metadata": {"number": "2.3.5", "chapter": 2, "chapter_title": "Sorting", "section": 2.3, "section_title": "Quicksort", "type": "Exercise", "code_execution": false}} {"question": "Write a program to compute the exact value of CN, and compare the exact value with the approximation 2N ln N, for N = 100, 1,000, and 10,000.", "answer": "For standard quicksort with random distinct keys,\n\n`C_0 = C_1 = 0`\n\nand, for `N >= 2`,\n\n`C_N = N + 1 + (2 / N) * (C_0 + C_1 + ... + C_{N-1})`.\n\nEquivalently, `C_N = 2(N + 1)H_N - 4N`.\n\n| N | exact C_N | 2N ln N |\n|---:|---:|---:|\n| 100 | 648 | 921 |\n| 1,000 | 10,986 | 13,816 |\n| 10,000 | 155,772 | 184,207 |\n\nThe previous answer used empirical-looking counts. The exact values above are the expected number of compares from the recurrence.", "support_files": [], "metadata": {"number": "2.3.6", "chapter": 2, "chapter_title": "Sorting", "section": 2.3, "section_title": "Quicksort", "type": "Exercise", "code_execution": false}} {"question": "Find the expected number of subarrays of size 0, 1, and 2 when quicksort is used to sort an array of N items with distinct keys. If you are mathematically inclined, do the math; if not, run some experiments to develop hypotheses.", "answer": "2.3.7\n\nArray Size | SubArrays Size 0 | SubArrays Size 1 | SubArrays Size 2\n 1000 325 338 174\n 2000 657 672 333\n 4000 1383 1309 681\n 8000 2639 2681 1329\n 16000 5327 5337 2662\n\nHypothesis: \nThe expected number of subarrays of size 0, 1 and 2 when quicksort is used to sort an array of N items with distinct keys is:\nSubarray size 0: 1/3 N\nSubarray size 1: 1/3 N\nSubarray size 2: 1/6 N\n", "support_files": [], "metadata": {"number": "2.3.7", "chapter": 2, "chapter_title": "Sorting", "section": 2.3, "section_title": "Quicksort", "type": "Exercise", "code_execution": false}} {"question": "About how many compares will Quick.sort() make when sorting an array of N items that are all equal?", "answer": "2.3.8\n\nWhen sorting an array of N items that are all equal, Quick.sort() will make approximately N lg N compares.\nEach partition will divide the array in half, plus or minus one.\n", "support_files": [], "metadata": {"number": "2.3.8", "chapter": 2, "chapter_title": "Sorting", "section": 2.3, "section_title": "Quicksort", "type": "Exercise", "code_execution": false}} {"question": "Explain what happens when Quick.sort() is run on an array having items with just two distinct keys, and then explain what happens when it is run on an array having just three distinct keys.", "answer": "2.3.9\n\nOn both cases (when Quick.sort() is run on arrays having items with just two or three distinct keys) there is a high occurrence of subarrays consisting solely of items with equal keys. To improve performance when sorting such arrays (from linearithmic to linear) quicksort with 3-way partitioning should be used.\n", "support_files": [], "metadata": {"number": "2.3.9", "chapter": 2, "chapter_title": "Sorting", "section": 2.3, "section_title": "Quicksort", "type": "Exercise", "code_execution": false}} {"question": "Chebyshev’s inequality says that the probability that a random variable is more than k standard deviations away from the mean is less than 1/k^2. For N = 1 million, use Chebyshev’s inequality to bound the probability that the number of compares used by quicksort is more than 100 billion (.1 N^2).", "answer": "2.3.10\n\nThere are 1 million elements, so N = 1,000,000.\nAs mentioned on the book, quicksort uses ~2N ln N compares on the average case to sort N keys.\nTherefore, on average there will be 27,620,000 compares.\n\nAs also mentioned on the book, the standard deviation of the number of compares is about .65 N, which in this case is 650,000.\nWith this information, the probability can be computed as follows:\n\nDifference between target compares and average compares = 100,000,000,000 - 27,620,000 = 99,972,380,000\nk = number of standard deviations = 99,972,380,000 / 650,000 ~= 153,804\nProbability < 1 / k^2\nProbability < 1 / (153,804)^2\nProbability < 1 / 23,655,670,416\nProbability < 0.000000000042273 = 0.0000000042273%\n\nTherefore, the probability that the number of compares used by quicksort for N = 1,000,000 is more than 100 billion is less than 0.0000000042273%.\n", "support_files": [], "metadata": {"number": "2.3.10", "chapter": 2, "chapter_title": "Sorting", "section": 2.3, "section_title": "Quicksort", "type": "Exercise", "code_execution": false}} {"question": "What is the recursive depth of quicksort, in the best, worst, and average cases? This is the size of the stack that the system needs to keep track of the recursive calls. See Exercise 2.3.20 for a way to guarantee that the recursive depth is logarithmic in the worst case.", "answer": "2.3.13\n\nRecursive depth in the best case: logarithmic \nRecursive depth in the worst case: linear\nRecursive depth in the average case: logarithmic (if the pivot is chosen at random or if the array is shuffled before the sort begins).\n", "support_files": [], "metadata": {"number": "2.3.13", "chapter": 2, "chapter_title": "Sorting", "section": 2.3, "section_title": "Quicksort", "type": "Exercise", "code_execution": false}} {"question": "Prove that when running quicksort on an array with N distinct items, the probability of comparing the ith and jth largest items is 2/(j - i + 1). Then use this result to prove Proposition K.", "answer": "2.3.14\n\nThe ith and jth elements will be compared if either of them is selected as pivot. \nIn an array of size (j - i + 1), the probability of choosing either the ith or the jth element as the pivot is 2 / (j - i + 1).\n\nTherefore, when running quicksort on an array with N distinct items, the probability of comparing the ith and the jth smallest items is 2 / (j - i + 1).\n\nBased on: http://stackoverflow.com/questions/2750726/randomized-quicksort-probability-of-two-elements-comparison \n\nProposition K says that quicksort uses ~ 2N ln N compares (and one-sixth that many exchanges) on the average to sort an array of length N with distinct keys. \n\nConsider the pivot element as k.\n\n1- When k > both ith and jth elements: in this case A[i] and A[j] are not compared to each other in this recursive call, but both are passed on to the first recursive call (so they might be compared in the future).\n2- When k < both ith and jth elements: similarly, in this case A[i] and A[j] are not compared to each other but both are passed on to the second recursive call.\n\nAs we have seen, the probability Pr of comparing the ith and jth elements is: \nPr[Cij = 1] = 2 / (j - i + 1)\n\nCombining both 1 and 2 statements yields:\n\nC = 2 * SUM(from i=1 to N) * SUM(from j = i + 1 to N) * 1 / (j - i + 1)\n\nNote that for each fixed i, the inner sum is:\n\n1/2 + 1/3 + 1/4 + ... + 1 / (n - i + 1) <= SUM(from k = 2 to N) * 1/k\n\nWe can upper bound the right-hand side by the area under the curve f(x) = 1/x. In other words:\nSUM(from k = 2 to N) * 1/k <= LIM(from 1 to N) * dx / x = ln * x |(from 1 to N) = ln N\n\nPutting it all together, we have\n\nC = 2 * SUM(from i=1 to N) * SUM(from j = i + 1 to N) * 1 / (j - i + 1) <= 2N * SUM(from k = 2 to N) * 1/k <= 2N ln N,\n\nwhich completes the proof.\n", "support_files": [], "metadata": {"number": "2.3.14", "chapter": 2, "chapter_title": "Sorting", "section": 2.3, "section_title": "Quicksort", "type": "Exercise", "code_execution": false}} {"question": "Nuts and bolts. (G. J. E. Rawlins) You have a mixed pile of N nuts and N bolts and need to quickly find the corresponding pairs of nuts and bolts. Each nut matches exactly one bolt, and each bolt matches exactly one nut. By fitting a nut and bolt together, you can see which is bigger, but it is not possible to directly compare two nuts or two bolts. Give an efficient method for solving the problem.", "answer": "2.3.15 - Nuts and bolts\n\nSince each nut matches exactly one bolt, the array of nuts and the array of bolts have distinct elements.\nTo avoid a O(N^2) complexity, initially I would shuffle the nuts array.\n\nI would then use Quicksort's partition method:\n1- Select a nut as the pivot (since the array is shuffled it is safe to always select the first nut).\n2- Using that pivot, partition the bolts array. This would result in the bolts array with a bolt (matching the nut pivot) in the correct place, all bolts smaller than it on its left and all bolts bigger than it on its right.\n3- Use the bolt found on the previous step as a pivot and partition the nuts array.\n4- Split the bolt array into two sub-arrays: one array with bolts smaller than the bolt found on step 2, and another array with bolts bigger than it.\n5- Do the same split for the nuts array, based on the nut found on step 3.\n\nI would repeat these steps recursively on the corresponding nut and bolt sub-arrays.\nAt the end, I would iterate over the sorted arrays and connect all nuts and bolts based on their index.\n\nThis method would do 2 * N operations for finding the partitions (N operations for the nuts array and N operations for the bolts array), lg N times, and would yield a complexity of O(N lg N).\n\nBased on: https://www.geeksforgeeks.org/nuts-bolts-problem-lock-key-problem/\nThanks to dragon-dreamer (https://github.com/dragon-dreamer) for suggesting a simpler method for this exercise.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/109\n", "support_files": [], "metadata": {"number": "2.3.15", "chapter": 2, "chapter_title": "Sorting", "section": 2.3, "section_title": "Quicksort", "type": "Creative Problem", "code_execution": false}} {"question": "Nonrecursive quicksort. Implement a nonrecursive version of quicksort based on a main loop where a subarray is popped from a stack to be partitioned, and the resulting subarrays are pushed onto the stack. Note: Push the larger of the subarrays onto the stack first, which guarantees that the stack will have at most lg N entries.", "answer": "// Exercise20_NonrecursiveQuicksort.java\npackage chapter2.section3;\n\nimport edu.princeton.cs.algs4.Stack;\nimport edu.princeton.cs.algs4.StdOut;\nimport edu.princeton.cs.algs4.StdRandom;\nimport edu.princeton.cs.algs4.Stopwatch;\nimport util.ArrayUtil;\nimport util.ArrayGenerator;\n\nimport java.util.Map;\n\n/**\n * Created by Rene Argento on 07/03/17.\n */\n// Thanks to dragon-dreamer (https://github.com/dragon-dreamer) for noticing that some redundant checks could be removed.\n// https://github.com/reneargento/algorithms-sedgewick-wayne/issues/110\npublic class Exercise20_NonrecursiveQuicksort {\n\n private static class QuickSortRange {\n int low;\n int high;\n\n QuickSortRange(int low, int high) {\n this.low = low;\n this.high = high;\n }\n }\n\n // Parameters example: 8 131072\n public static void main(String[] args) {\n int numberOfExperiments = Integer.parseInt(args[0]);\n int initialArraySize = Integer.parseInt(args[1]);\n\n Map allInputArrays = ArrayGenerator.generateAllArrays(numberOfExperiments, initialArraySize, 2);\n\n doExperiment(numberOfExperiments, initialArraySize, allInputArrays);\n }\n\n private static void doExperiment(int numberOfExperiments, int initialArraySize, Map allInputArrays) {\n StdOut.printf(\"%13s %23s %22s\\n\", \"Array Size | \", \"QuickSort Running Time |\", \"Nonrecursive QuickSort\");\n\n int arraySize = initialArraySize;\n\n for (int i = 0; i < numberOfExperiments; i++) {\n\n Comparable[] originalArray = allInputArrays.get(i);\n Comparable[] arrayCopy1 = new Comparable[originalArray.length];\n System.arraycopy(originalArray, 0, arrayCopy1, 0, originalArray.length);\n\n // Default QuickSort\n Stopwatch defaultQuickSortTimer = new Stopwatch();\n\n QuickSort.quickSort(originalArray);\n\n double defaultQuickSortRunningTime = defaultQuickSortTimer.elapsedTime();\n\n // Nonrecursive QuickSort\n Stopwatch nonRecursiveQuickSortTimer = new Stopwatch();\n\n nonRecursiveQuickSort(arrayCopy1);\n\n double nonRecursiveQuickSortRunningTime = nonRecursiveQuickSortTimer.elapsedTime();\n\n printResults(arraySize, defaultQuickSortRunningTime, nonRecursiveQuickSortRunningTime);\n\n arraySize *= 2;\n }\n }\n\n private static void nonRecursiveQuickSort(Comparable[] array) {\n StdRandom.shuffle(array);\n quickSort(array, 0, array.length - 1);\n }\n\n private static void quickSort(Comparable[] array, int low, int high) {\n Stack stack = new Stack<>();\n\n QuickSortRange quickSortRange = new QuickSortRange(low, high);\n stack.push(quickSortRange);\n\n while (stack.size() > 0) {\n QuickSortRange currentQuickSortRange = stack.pop();\n\n int partition = partition(array, currentQuickSortRange.low, currentQuickSortRange.high);\n QuickSortRange leftQuickSortRange = new QuickSortRange(currentQuickSortRange.low, partition - 1);\n QuickSortRange rightQuickSortRange = new QuickSortRange(partition + 1, currentQuickSortRange.high);\n\n // Size = right - left + 1\n int leftSubArraySize = partition - currentQuickSortRange.low;\n int rightSubArraySize = currentQuickSortRange.high - partition;\n\n // Push the larger sub array first to guarantee that the stack will have at most lg N entries\n if (leftSubArraySize > rightSubArraySize) {\n if (leftSubArraySize > 1) {\n stack.push(leftQuickSortRange);\n }\n if (rightSubArraySize > 1) {\n stack.push(rightQuickSortRange);\n }\n } else {\n if (rightSubArraySize > 1) {\n stack.push(rightQuickSortRange);\n }\n if (leftSubArraySize > 1) {\n stack.push(leftQuickSortRange);\n }\n }\n }\n }\n\n private static int partition(Comparable[] array, int low, int high) {\n Comparable pivot = array[low];\n\n int i = low;\n int j = high + 1;\n\n while (true) {\n while (ArrayUtil.less(array[++i], pivot)) {\n if (i == high) {\n break;\n }\n }\n\n while (ArrayUtil.less(pivot, array[--j])) {\n if (j == low) {\n break;\n }\n }\n\n if (i >= j) {\n break;\n }\n\n ArrayUtil.exchange(array, i, j);\n }\n\n // Place pivot in the right place\n ArrayUtil.exchange(array, low, j);\n return j;\n }\n\n private static void printResults(int arraySize, double defaultQuickSortRunningTime, double nonRecursiveQuickSort) {\n StdOut.printf(\"%10d %25.1f %24.1f\\n\", arraySize, defaultQuickSortRunningTime, nonRecursiveQuickSort);\n }\n}\n\nAdditional notes/results:\n2.3.20 - Nonrecursive QuickSort\n\nThe recursive implementation has a better running time than the non recursive implementation.\n\nArray Size | QuickSort Running Time | Nonrecursive QuickSort\n 131072 0.1 0.1\n 262144 0.1 0.8\n 524288 0.2 0.2\n 1048576 0.4 0.4\n 2097152 0.9 1.7\n 4194304 2.3 3.0\n 8388608 5.5 6.1\n 16777216 11.6 12.3", "support_files": [], "metadata": {"number": "2.3.20", "chapter": 2, "chapter_title": "Sorting", "section": 2.3, "section_title": "Quicksort", "type": "Creative Problem", "code_execution": false}} {"question": "Java system sort. Add to your implementation from Exercise 2.3.22 code to use the Tukey ninther to compute the partitioning item—choose three sets of three items, take the median of each, then use the median of the three medians as the partitioning item. Also, add a cutoff to insertion sort for small subarrays.", "answer": "// Exercise23_TukeysNinther.java\npackage chapter2.section3;\n\nimport chapter2.section1.InsertionSort;\nimport edu.princeton.cs.algs4.StdOut;\nimport edu.princeton.cs.algs4.StdRandom;\nimport edu.princeton.cs.algs4.Stopwatch;\nimport util.ArrayUtil;\nimport util.ArrayGenerator;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * Created by Rene Argento on 10/03/17.\n */\npublic class Exercise23_TukeysNinther {\n\n private static final int SIZE_REQUIRED_FOR_TUKEY_NINTHER = 9;\n private static final int INSERTION_SORT_CUTOFF = 9;\n\n // Parameters example: 8 1048576\n public static void main(String[] args) {\n int numberOfExperiments = Integer.parseInt(args[0]);\n int initialArraySize = Integer.parseInt(args[1]);\n\n Map allInputArrays = new HashMap<>();\n\n int arraySize = initialArraySize;\n\n for (int i = 0; i < numberOfExperiments; i++) {\n Comparable[] array = ArrayGenerator.generateRandomArrayWith3Values(arraySize);\n allInputArrays.put(i, array);\n\n arraySize *= 2;\n }\n\n doExperiment(numberOfExperiments, initialArraySize, allInputArrays);\n }\n\n private static void doExperiment(int numberOfExperiments, int initialArraySize, Map allInputArrays) {\n StdOut.printf(\"%13s %16s %38s %52s\\n\", \"Array Size | \", \"QuickSort 3-Way |\", \"QuickSort with fast 3-way partitioning | \",\n \"QuickSort w/ fast 3-way partitioning + Tukey Ninther\");\n\n int arraySize = initialArraySize;\n\n for (int i = 0; i < numberOfExperiments; i++) {\n Comparable[] originalArray = allInputArrays.get(i);\n Comparable[] arrayCopy1 = new Comparable[originalArray.length];\n System.arraycopy(originalArray, 0, arrayCopy1, 0, originalArray.length);\n Comparable[] arrayCopy2 = new Comparable[originalArray.length];\n System.arraycopy(originalArray, 0, arrayCopy2, 0, originalArray.length);\n\n //QuickSort 3-Way\n Stopwatch quickSort3WaySortTimer = new Stopwatch();\n\n QuickSort3Way.quickSort3Way(originalArray);\n\n double quickSort3WayRunningTime = quickSort3WaySortTimer.elapsedTime();\n\n //QuickSort with fast 3-way partitioning (Bentley-McIlroy)\n Stopwatch quickSortWithFast3WayPartitioning = new Stopwatch();\n\n Exercise22_Fast3WayPartitioning.quickSortWithFast3WayPartitioning(arrayCopy1);\n\n double quickSortWithFast3WayPartitioningRunningTime = quickSortWithFast3WayPartitioning.elapsedTime();\n\n //QuickSort with fast 3-way partitioning (Bentley-McIlroy) + Tukey Ninther\n Stopwatch quickSortWithFast3WayPartitioningTukeyNinther = new Stopwatch();\n\n quickSortWithFast3WayPartitioningTukeyNinther(arrayCopy2);\n\n double quickSortWithFast3WayPartitioningTukeyNintherRunningTime = quickSortWithFast3WayPartitioningTukeyNinther.elapsedTime();\n\n printResults(arraySize, quickSort3WayRunningTime, quickSortWithFast3WayPartitioningRunningTime,\n quickSortWithFast3WayPartitioningTukeyNintherRunningTime);\n\n arraySize *= 2;\n }\n }\n\n private static void quickSortWithFast3WayPartitioningTukeyNinther(Comparable[] array) {\n StdRandom.shuffle(array);\n quickSort(array, 0, array.length - 1);\n }\n\n @SuppressWarnings(\"unchecked\")\n private static void quickSort(Comparable[] array, int low, int high) {\n\n if (low >= high) {\n return;\n }\n\n if (high - low + 1 < INSERTION_SORT_CUTOFF) {\n InsertionSort.insertionSort(array, low, high);\n return;\n }\n\n int i = low;\n int j = high + 1;\n\n int p = low;\n int q = high + 1;\n\n int pivotIndex = getPivotIndex(array, low, high);\n ArrayUtil.exchange(array, low, pivotIndex);\n Comparable pivot = array[low];\n\n while (true) {\n\n if (i > low && array[i].compareTo(pivot) == 0) {\n ArrayUtil.exchange(array, ++p, i);\n }\n if (j <= high && array[j].compareTo(pivot) == 0) {\n ArrayUtil.exchange(array, --q, j);\n }\n\n while (ArrayUtil.less(array[++i], pivot)) {\n if (i == high) {\n break;\n }\n }\n\n while (ArrayUtil.less(pivot, array[--j])) {\n if (j == low) {\n break;\n }\n }\n\n //pointers cross\n if (i == j && array[i].compareTo(pivot) == 0) {\n ArrayUtil.exchange(array, ++p, i);\n }\n if (i >= j) {\n break;\n }\n\n ArrayUtil.exchange(array, i, j);\n }\n\n //Currently:\n // array[low..p] == pivot\n // array[p..i] < pivot\n // array[j..q] > pivot\n // array[q..high] == pivot\n\n i = j + 1;\n\n for (int k = low; k <= p; k++) {\n ArrayUtil.exchange(array, k, j--);\n }\n for (int k = high; k >= q; k--) {\n ArrayUtil.exchange(array, k, i++);\n }\n\n //Now:\n // array[low..j] < pivot\n // array[j..i] == pivot\n // array[i..high] > pivot\n\n quickSort(array, low, j);\n quickSort(array, i, high);\n }\n\n //Tukey's ninther\n private static int getPivotIndex(Comparable[] array, int low, int high) {\n int numberOfValues = high - low + 1;\n\n int eps = numberOfValues / SIZE_REQUIRED_FOR_TUKEY_NINTHER;\n int middle = low + (high - low) / 2;\n\n int medianIndex1 = getMedianIndex(array, low, low + eps, low + eps + eps);\n int medianIndex2 = getMedianIndex(array, middle - eps, middle, middle + eps);\n int medianIndex3 = getMedianIndex(array, high - eps - eps, high - eps, high);\n\n return getMedianIndex(array, medianIndex1, medianIndex2, medianIndex3);\n }\n\n private static int getMedianIndex(Comparable[] array, int index1, int index2, int index3) {\n return ArrayUtil.less(array[index1], array[index2]) ?\n (ArrayUtil.less(array[index2], array[index3]) ? index2 : ArrayUtil.less(array[index1], array[index3])\n ? index3 : index1) :\n (ArrayUtil.less(array[index1], array[index3]) ? index1 : ArrayUtil.less(array[index2], array[index3]) ? index3 : index2);\n }\n\n private static void printResults(int arraySize, double quickSort3WayRunningTime, double quickSortWithFast3WayPartitioningRunningTime,\n double quickSortWithFast3WayPartitioningTukeyNintherRunningTime) {\n StdOut.printf(\"%10d %18.1f %40.1f %55.1f\\n\", arraySize, quickSort3WayRunningTime, quickSortWithFast3WayPartitioningRunningTime,\n quickSortWithFast3WayPartitioningTukeyNintherRunningTime);\n }\n}\n\nAdditional notes/results:\n2.3.23 - Tukey's ninther\n \nThe default 3-way partitioning QuickSort had a better running time than both the Bentley-McIlroy 3-way partitioning QuickSort and the Bentley-McIlroy 3-way partitioning QuickSort + Turkey Ninther.\nThe Bentley-McIlroy 3-way partitioning QuickSort + Turkey Ninther had a better running time than the Bentley-McIlroy 3-way partitioning QuickSort.\n\nArray Size | QuickSort 3-Way | QuickSort with fast 3-way partitioning | QuickSort w/ fast 3-way partitioning + Tukey Ninther\n 1048576 0.1 0.1 0.1\n 2097152 0.1 0.1 0.1\n 4194304 0.2 0.2 0.2\n 8388608 0.5 0.5 0.6\n 16777216 1.1 1.2 1.2\n 33554432 2.4 2.6 2.6\n 67108864 5.3 5.5 5.6\n 134217728 11.6 12.7 12.1", "support_files": [], "metadata": {"number": "2.3.23", "chapter": 2, "chapter_title": "Sorting", "section": 2.3, "section_title": "Quicksort", "type": "Creative Problem", "code_execution": false}} {"question": "Samplesort. (W. Frazer and A. McKellar) Implement a quicksort based on using a sample of size 2k - 1. First, sort the sample, then arrange to have the recursive routine partition on the median of the sample and to move the two halves of the rest of the sample to each subarray, such that they can be used in the subarrays, without having to be sorted again. This algorithm is called samplesort.", "answer": "// Exercise24_Samplesort.java\npackage chapter2.section3;\n\nimport chapter2.section1.InsertionSort;\nimport edu.princeton.cs.algs4.StdOut;\nimport edu.princeton.cs.algs4.StdRandom;\nimport edu.princeton.cs.algs4.Stopwatch;\nimport util.ArrayUtil;\nimport util.ArrayGenerator;\n\nimport java.util.Map;\n\n/**\n * Created by Rene Argento on 10/03/17.\n */\n// Thanks to ckwastra (https://github.com/ckwastra) for the samplesort implementation.\n// https://github.com/reneargento/algorithms-sedgewick-wayne/issues/263\n@SuppressWarnings(\"unchecked\")\npublic class Exercise24_Samplesort {\n\n private static final int INSERTION_SORT_CUTOFF = 2;\n\n // Parameters example: 8 131072\n public static void main(String[] args) {\n int numberOfExperiments = Integer.parseInt(args[0]);\n int initialArraySize = Integer.parseInt(args[1]);\n\n Map allInputArrays = ArrayGenerator.generateAllArrays(numberOfExperiments, initialArraySize, 2);\n doExperiment(numberOfExperiments, initialArraySize, allInputArrays);\n }\n\n private static > void doExperiment(int numberOfExperiments, int initialArraySize,\n Map allInputArrays) {\n StdOut.printf(\"%13s %23s %25s\\n\", \"Array Size | \", \"QuickSort Running Time |\", \"SampleSort Running Time\");\n\n int arraySize = initialArraySize;\n\n for (int i = 0; i < numberOfExperiments; i++) {\n Comparable[] originalArray = allInputArrays.get(i);\n Comparable[] array = new Comparable[originalArray.length];\n System.arraycopy(originalArray, 0, array, 0, originalArray.length);\n\n // Default QuickSort\n Stopwatch quickSortTimer = new Stopwatch();\n QuickSort.quickSort(originalArray);\n double quickSortRunningTime = quickSortTimer.elapsedTime();\n\n // SampleSort\n Stopwatch sampleSortTimer = new Stopwatch();\n sampleSort(array);\n double sampleSortRunningTime = sampleSortTimer.elapsedTime();\n\n printResults(arraySize, quickSortRunningTime, sampleSortRunningTime);\n arraySize *= 2;\n }\n }\n\n private static > void sampleSort(Comparable[] array) {\n sampleSort(array, array.length);\n }\n\n private static > void sampleSort(Comparable[] array, int size) {\n if (size <= INSERTION_SORT_CUTOFF) {\n InsertionSort.insertionSort(array, 0, size - 1);\n return;\n }\n\n // Based on Python's (2.23) version of Samplesort\n // numberOfPivots ~= lg(n / ln(n))\n double sizeByLogSize = size / Math.log(size);\n int k = (int) Math.round(Math.log(sizeByLogSize) / Math.log(2));\n int numberOfPivots = (int) Math.pow(2, k) - 1;\n\n // Pick random samples\n for (int i = 0; i < numberOfPivots; i++) {\n int randomIndex = StdRandom.uniform(size);\n ArrayUtil.exchange(array, i, randomIndex);\n }\n\n // Recursively sort the sample\n sampleSort(array, numberOfPivots);\n\n // | 0 1 ... numberOfPivots-1 | numberOfPivots ... n-1 |\n // | <- sorted sample -> | <- unknown -> |\n // | lo hi |\n sampleSort(array, numberOfPivots, size - 1, numberOfPivots);\n }\n\n private static > void sampleSort(Comparable[] array, int low, int high,\n int numberOfPivots) {\n if (low > high) {\n return;\n }\n if (numberOfPivots == 0) {\n InsertionSort.insertionSort(array, low, high);\n return;\n }\n\n // Move pivots in-place to always have them on both partitions.\n if (numberOfPivots > 0) {\n // The pivots are to the left of low. Move half to the right end.\n int halfPivots = numberOfPivots / 2;\n for (int i = 0; i < halfPivots; i++) {\n low--;\n ArrayUtil.exchange(array, low, high);\n high--;\n }\n } else {\n // The pivots are to the right of high. Move half to the left end.\n numberOfPivots = -numberOfPivots;\n int halfPivots = (numberOfPivots + 1) / 2;\n for (int i = 0; i < halfPivots; i++) {\n high++;\n ArrayUtil.exchange(array, low, high);\n low++;\n }\n }\n\n low--;\n int partition = partition(array, low, high);\n\n int halfPivots;\n int halfPivotsOnLeftPartition;\n if (numberOfPivots % 2 == 0) {\n halfPivots = numberOfPivots / 2;\n halfPivotsOnLeftPartition = halfPivots - 1;\n } else {\n halfPivots = numberOfPivots / 2;\n halfPivotsOnLeftPartition = halfPivots;\n }\n sampleSort(array, low, partition - 1, halfPivotsOnLeftPartition);\n sampleSort(array, partition + 1, high, -halfPivots);\n }\n\n private static > int partition(Comparable[] array, int low, int high) {\n Comparable pivot = array[low];\n\n int i = low;\n int j = high + 1;\n\n while (true) {\n while (ArrayUtil.less(array[++i], pivot)) {\n if (i == high) {\n break;\n }\n }\n\n while (ArrayUtil.less(pivot, array[--j])) {\n if (j == low) {\n break;\n }\n }\n\n if (i >= j) {\n break;\n }\n\n ArrayUtil.exchange(array, i, j);\n }\n\n // Place pivot in the right place\n ArrayUtil.exchange(array, low, j);\n return j;\n }\n\n private static void printResults(int arraySize, double quickSortRunningTime, double sampleSortRunningTime) {\n StdOut.printf(\"%10d %25.1f %27.1f\\n\", arraySize, quickSortRunningTime, sampleSortRunningTime);\n }\n}\n\nAdditional notes/results:\n2.3.24 - Samplesort\n\nSampleSort's running time is faster than Quicksort, especially for higher array sizes.\n\nArray Size | QuickSort Running Time | SampleSort Running Time\n 131072 0.1 0.0\n 262144 0.1 0.1\n 524288 0.2 0.1\n 1048576 0.4 0.3\n 2097152 0.9 0.6\n 4194304 2.2 1.4\n 8388608 5.3 3.3\n 16777216 11.9 7.3", "support_files": [], "metadata": {"number": "2.3.24", "chapter": 2, "chapter_title": "Sorting", "section": 2.3, "section_title": "Quicksort", "type": "Creative Problem", "code_execution": false}} {"question": "Suppose that the sequence P R I O * R * * I * T * Y * * * Q U E * * * U * E (where a letter means insert and an asterisk means remove the maximum) is applied to an initially empty priority queue. Give the sequence of letters returned by the remove the maximum operations.", "answer": "2.4.1\n\nR R P O T Y I I U Q E U\n(E is left on the priority queue)\n", "support_files": [], "metadata": {"number": "2.4.1", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Exercise", "code_execution": false}} {"question": "Criticize the following idea: To implement find the maximum in constant time, why not use a stack or a queue, but keep track of the maximum value inserted so far, then return that value for find the maximum?", "answer": "2.4.2\n\nThis idea would not work because it only keeps track of the current maximum. After a remove-the-maximum operation it would not be possible to know which is the next maximum in constant time, requiring a linear operation to find the new maximum.\n", "support_files": [], "metadata": {"number": "2.4.2", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Exercise", "code_execution": false}} {"question": "Provide priority-queue implementations that support insert and remove the maximum, one for each of the following underlying data structures: unordered array, ordered array, unordered linked list, and linked list. Give a table of the worst-case bounds for each operation for each of your four implementations.", "answer": "2.4.3\n\nData Structure Method Worst-case\nUnordered array Insert 1\nUnordered array Remove the Maximum N\nOrdered array Insert N\nOrdered array Remove the Maximum 1 \nUnordered linked list Insert 1\nUnordered linked list Remove the Maximum N \nOrdered linked list Insert N\nOrdered linked list Remove the Maximum 1\n", "support_files": [], "metadata": {"number": "2.4.3", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Exercise", "code_execution": false}} {"question": "Is an array that is sorted in decreasing order a max-oriented heap?", "answer": "2.4.4\n\nYes, an array that is sorted in decreasing order is a max-oriented heap.\n", "support_files": [], "metadata": {"number": "2.4.4", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Exercise", "code_execution": false}} {"question": "Give the heap that results when the keys E A S Y Q U E S T I O N are inserted in that order into an initially empty max-oriented heap.", "answer": "2.4.5 \n\n1- E\n\n2- E\n A\n\n3- S\n A E\n\n4- Y\n S E\n A\n\n5- Y\n S E\n A Q \n\n6- Y\n S U\n A Q E\n\n7- Y\n S U\n A Q E E\n\n8- Y\n S U\n S Q E E\nA\n\n9- Y\n T U\n S Q E E\nA S\n\n10- Y\n T U\n S Q E E\nA S I\n\n11- Y\n T U\n S Q E E\nA S I O\n\n12- Y\n T U\n S Q N E\nA S I O E\n", "support_files": [], "metadata": {"number": "2.4.5", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Exercise", "code_execution": false}} {"question": "Using the conventions of Exercise 2.4.1, give the sequence of heaps produced when the operations P R I O * R * * I * T * Y * * * Q U E * * * U * E are performed on an initially empty max-oriented heap.", "answer": "2.4.6\n\nHeaps:\n\n1- P\n\n2- R\n P\n\n3- R\n P I\n\n4- R\n P I\n O\n\n5- P\n O I\n\n6- R\n P I\n O\n\n7- P\n O I\n\n8- O\n I\n\n9- O\n I I\n\n10- I\n I\n\n11- T\n I I\n\n12- I\n I\n\n13- Y\n I I\n\n14- I\n I\n\n15- I\n\n16- \n\n17- Q\n\n18- U\n Q\n\n19- U\n Q E\n\n20- Q\n E\n\n21- E\n\n22- \n\n23- U\n\n24- \n\n25- E\n", "support_files": [], "metadata": {"number": "2.4.6", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Exercise", "code_execution": false}} {"question": "The largest item in a heap must appear in position 1, and the second largest must be in position 2 or position 3. Give the list of positions in a heap of size 31 where the kth largest (i) can appear, and (ii) cannot appear, for k=2, 3, 4 (assuming the values to be distinct).", "answer": "2.4.7\n\nHeap-of-size-31 positions\n\n 1\n 2 3\n 4 5 6 7\n 8 9 10 11 12 13 14 15\n16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31\n\nKth largest item Can appear Cannot appear\n2 2,3 1,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31\n3 2,3,4,5,6,7 1,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31\n4 2,3,4,5,6,7,8,9,10,11,12,13,14,15 1,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31\n\nThanks to oeyh (https://github.com/oeyh) for mentioning that the 4th largest item may also appear on positions 2 and 3.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/26\n", "support_files": [], "metadata": {"number": "2.4.7", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Exercise", "code_execution": false}} {"question": "Answer the previous exercise for the kth smallest item.", "answer": "2.4.8\n\nKth smallest item Can appear Cannot appear\n2 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15\n3 8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 1,2,3,4,5,6,7 \n4 8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 1,2,3,4,5,6,7\n", "support_files": [], "metadata": {"number": "2.4.8", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Exercise", "code_execution": false}} {"question": "Draw all of the different heaps that can be made from the five keys A B C D E, then draw all of the different heaps that can be made from the five keys A A A B B.", "answer": "2.4.9\n\nUsing A,B,C,D,E keys\n\n1- E\n D C\n B A\n\n2- E\n D C\n A B\n\n3- E\n C D\n B A\n\n4- E\n C D\n A B\n\n5- E\n D A\n C B\n\n6- E\n D A\n B C\n\n7- E\n D B\n C A\n\n8- E\n D B\n A C\n\nUsing A,A,A,B,B keys\n\n1- B\n B A\n A A\n \n2- B\n A B\n A A\n", "support_files": [], "metadata": {"number": "2.4.9", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Exercise", "code_execution": false}} {"question": "Suppose that we wish to avoid wasting one position in a heap-ordered array pq[], putting the largest value in pq[0], its children in pq[1] and pq[2], and so forth, proceeding in level order. Where are the parents and children of pq[k]?", "answer": "2.4.10\n\nParent of pq[k]: pq[(k - 1) / 2] (Rounded down)\n\nChildren of pq[k]:\nLeft: pq[k * 2 + 1]\nRight: pq[k * 2 + 2]\n", "support_files": [], "metadata": {"number": "2.4.10", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Exercise", "code_execution": false}} {"question": "Describe a way to avoid the j < N test in sink().", "answer": "2.4.13\n\nChanging the line: \nwhile (2*k <= N)\n\nTo:\nwhile (2*k < N)\n\nWould guarantee that all indices (2*k + 1) are <= N and with that, the j < N verification would not be necessary.\n\nHowever, an additional verification would be necessary for the last level of the heap if the node being compared in level n-1 only has a left child.\n\nprivate void sink(int k) {\n while (2*k < N) {\n int j = 2*k;\n if (less(j, j+1)) j++;\n if (!less(k, j)) break;\n exch(k, j);\n k = j;\n }\n\n //If we reached the n-1 level of the heap and it only has 1 child (the left child), we need one more verification\n if (2 * k == N) {\n //If the current element is smaller than its child, exchange them\n if (less(k, 2 * k)) {\n exch(k, 2 * k);\n }\n }\n}\n", "support_files": [], "metadata": {"number": "2.4.13", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Exercise", "code_execution": false}} {"question": "What is the minimum number of items that must be exchanged during a remove the maximum operation in a heap of size N with no duplicate keys? Give a heap of size 15 for which the minimum is achieved. Answer the same questions for two and three successive remove the maximum operations.", "answer": "2.4.14\n\nThe minimum number of items that must be exchanged during a remove the maximum operation in a heap of size N with no duplicate keys is 2.\n\nHeap:\n 100\n 99 98\n 9 10 97 96\n 5 6 7 8 95 94 93 92\n \nFor two successive remove the maximum operations the minimum number of exchanges is 5.\n\nHeap:\n 100\n 99 98\n 9 10 94 97\n 5 6 7 8 90 91 93 92\n\nFor three successive remove the maximum operations the minimum number of exchanges is 8.\n\nHeap:\n 100\n 99 98\n 9 10 94 97\n 5 6 7 8 90 91 93 92\n", "support_files": [], "metadata": {"number": "2.4.14", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Exercise", "code_execution": false}} {"question": "Design a linear-time certification algorithm to check whether an array pq[] is a min-oriented heap.", "answer": "public static boolean isMinHeap(Comparable[] pq, int n) {\n for (int k = 1; k <= n / 2; k++) {\n if (2 * k <= n && greater(pq[k], pq[2 * k])) {\n return false;\n }\n if (2 * k + 1 <= n && greater(pq[k], pq[2 * k + 1])) {\n return false;\n }\n }\n return true;\n}\n\nprivate static boolean greater(Comparable a, Comparable b) {\n return a.compareTo(b) > 0;\n}\n\nThis is linear time because it checks each parent-child heap-order relation once. Equal keys are accepted, as they should be in a min-oriented heap.\n", "support_files": [], "metadata": {"number": "2.4.15", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Exercise", "code_execution": false}} {"question": "Prove that sink-based heap construction uses fewer than 2N compares and fewer than N exchanges.", "answer": "2.4.20\n\nSink-based heap construction uses fewer than 2N compares and fewer than N exchanges.\n\nProof: It suffices to prove that sink-based heap construction uses fewer than n exchanges because the number of compares is at most twice the number of exchanges.\nFor simplicity, assume that the binary heap is perfect (i.e., a binary tree in which every level is completely filled) and has height h.\n\n 4\n 3 3\n 2 2 2 2\n 1 1 1 1 1 1 1 1\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n\nThe values are the height of the subtrees rooted in each node.\n\nWe define the height of a node in a tree to be the height of the subtree rooted at that node. A key at height k can be exchanged with at most k keys beneath it when it is sunk down.\nSince there are 2^h-k nodes at height k, the total number of exchanges is at most:\nh + 2(h - 1) + 4(h - 2) + 8(h - 3) + ... + 2^h(0) = 2^(h+1) - h - 2\n= N - h - 1 < N\n\nThe first equality is for a nonstandard sum, but it is straightforward to verify that the formula holds via mathematical induction. The second equality holds because a perfect binary tree of height h has 2^(h+1) - 1 nodes.\n\nWhen the binary tree is not perfect, the result still holds by using the same analysis and considering the fact that the number of nodes at height k in a binary heap on n nodes is at most ceil(n / 2^(k+1)).\n\nAlternate solution: Again, for simplicity, assume that the binary heap is perfect (i.e., a binary tree in which every level is completely filled). We define the height of a node in a tree to be the height of the subtree rooted at that node.\n\n* First, observe that a binary heap on n nodes has n - 1 links (because each link is the parent of one node and every node has a parent link except the root).\n* Sinking a node of height k requires at most k exchanges.\n* We will charge k links to each node at height k, but not necessarily the links on the path taken when sinking the node. Instead, we charge the node the k links along the path from the node that goes left-right-right-right-...\n* Note that no link is charged to more than one node. (In fact, there are two links not charged to any node: the right link from the root and the parent link from the bottom rightmost node).\n* Thus, the total number of exchanges is at most n. Since there are at most 2 compares per exchange, the number of compares is at most 2n.\n\nReference: http://algs4.cs.princeton.edu/24pq/\n", "support_files": [], "metadata": {"number": "2.4.20", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Exercise", "code_execution": false}} {"question": "Multiway heaps. Considering the cost of compares only, and assuming that it takes t compares to find the largest of t items, find the value of t that minimizes the coefficient of N lg N in the compare count when a t-ary heap is used in heapsort. First, assume a straightforward generalization of sink(); then, assume that Floyd’s method can save one compare in the inner loop.", "answer": "In a t-ary heap, the height is log_t N = lg N / lg t. In the straightforward sink(), each level needs t - 1 compares to find the largest child and one more compare to decide whether to exchange with that child, for about t compares per level. The leading coefficient of N lg N is therefore proportional to\n\n t / lg t\n\nThis is minimized near t = e, so among integer arities the best choice is t = 3.\n\nWith Floyd's method, the item being sunk is moved down without comparing it against the largest child at each level; the downward pass only finds the largest child. The leading coefficient is therefore proportional to\n\n (t - 1) / lg t\n\nThis expression is minimized at t = 2 among integer arities. So the answers are: t = 3 for the straightforward generalization, and t = 2 when Floyd's method saves one compare in the inner loop.\n", "support_files": [], "metadata": {"number": "2.4.23", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Creative Problem", "code_execution": false}} {"question": "Priority queue with explicit links. Implement a priority queue using a heap-ordered binary tree, but use a triply linked structure instead of an array. You will need three links per node: two to traverse down the tree and one to traverse up the tree. Your implementation should guarantee logarithmic running time per operation, even if no maximum priority-queue size is known ahead of time.", "answer": "package chapter2.section4;\n\nimport edu.princeton.cs.algs4.StdOut;\nimport util.ArrayUtil;\n\n/**\n * Created by Rene Argento on 23/03/17.\n */\n@SuppressWarnings(\"unchecked\")\npublic class Exercise24_PriorityQueueExplicitLinks {\n\n private class PQNode {\n PQNode parent;\n PQNode leftChild;\n PQNode rightChild;\n\n Key value;\n }\n\n private class PriorityQueueExplicitLinks {\n\n private PQNode priorityQueue;\n private int size = 0; // The first node will not be used to simplify index computation\n\n PriorityQueueExplicitLinks() {\n priorityQueue = new PQNode(); // 0 position is not used\n }\n\n public boolean isEmpty() {\n return size == 0;\n }\n\n public int size() {\n return size;\n }\n\n // O(lg N)\n public void insert(Key key) {\n size++;\n\n PQNode newNode = new PQNode();\n newNode.value = key;\n\n int parentIndex = size / 2; //The index of the parent of the new node\n int[] pathToParentNode = generatePathToNode(parentIndex);\n PQNode parentNode = getNode(pathToParentNode);\n\n if (parentNode.leftChild == null) {\n parentNode.leftChild = newNode;\n } else {\n parentNode.rightChild = newNode;\n }\n newNode.parent = parentNode;\n\n swim(newNode);\n }\n\n // O(lg N)\n public Key deleteMax() {\n if (size == 0) {\n throw new RuntimeException(\"Priority queue underflow\");\n }\n\n Key max = priorityQueue.leftChild.value;\n int parentNodeIndex = size / 2; //The index of the parent of the last node\n\n // If we are deleting the root\n if (parentNodeIndex == 0) {\n priorityQueue.leftChild = null;\n size--;\n return max;\n }\n\n int[] pathToLastNodeParent = generatePathToNode(parentNodeIndex);\n PQNode lastNodeParent = getNode(pathToLastNodeParent);\n\n Key lastItemValue;\n\n if (lastNodeParent.rightChild != null) {\n lastItemValue = lastNodeParent.rightChild.value;\n lastNodeParent.rightChild.parent = null;\n lastNodeParent.rightChild = null;\n } else {\n lastItemValue = lastNodeParent.leftChild.value;\n lastNodeParent.leftChild.parent = null;\n lastNodeParent.leftChild = null;\n }\n\n priorityQueue.leftChild.value = lastItemValue;\n sink(priorityQueue.leftChild);\n\n size--;\n return max;\n }\n\n // O(lg N)\n private void swim(PQNode node) {\n\n while (node.parent.value != null && ArrayUtil.less(node.parent.value, node.value)) {\n // Swap node values\n Key temp = node.value;\n node.value = node.parent.value;\n node.parent.value = temp;\n\n node = node.parent;\n }\n }\n\n // O(lg N)\n private void sink(PQNode node) {\n boolean isTheLeftChildTheHighestItem;\n Key highestItemValue;\n\n // Repeat while the current node exists and has at least 1 child\n while (node != null && node.leftChild != null) {\n // Check which child is bigger\n if (node.rightChild != null) {\n if (ArrayUtil.less(node.leftChild.value, node.rightChild.value)) {\n isTheLeftChildTheHighestItem = false;\n highestItemValue = node.rightChild.value;\n } else {\n isTheLeftChildTheHighestItem = true;\n highestItemValue = node.leftChild.value;\n }\n } else {\n isTheLeftChildTheHighestItem = true;\n highestItemValue = node.leftChild.value;\n }\n\n // Compare highest value child and parent\n if (ArrayUtil.less(node.value, highestItemValue)) {\n Key temp = node.value;\n\n if (isTheLeftChildTheHighestItem) {\n node.value = node.leftChild.value;\n node.leftChild.value = temp;\n\n node = node.leftChild;\n } else {\n node.value = node.rightChild.value;\n node.rightChild.value = temp;\n\n node = node.rightChild;\n }\n } else {\n break;\n }\n }\n }\n\n // O(lg N)\n private int[] generatePathToNode(int nodeIndex) {\n int pathSize = (int) Math.ceil(Math.log10(nodeIndex) / Math.log10(2)) + 1;\n\n if (pathSize <= 0) {\n return new int[0];\n }\n\n int[] pathToNode = new int[pathSize];\n\n for (int i = pathSize - 1; i >= 0; i--) {\n pathToNode[i] = nodeIndex;\n\n nodeIndex /= 2;\n }\n\n return pathToNode;\n }\n\n // O(lg N)\n private PQNode getNode(int[] pathToNode) {\n int currentIndex = 1;\n PQNode currentNode = priorityQueue.leftChild;\n\n for (int i = 0; i < pathToNode.length && currentNode != null; i++) {\n if (pathToNode[i] == currentIndex * 2) {\n currentNode = currentNode.leftChild;\n currentIndex = currentIndex * 2;\n } else if (pathToNode[i] == currentIndex * 2 + 1) {\n currentNode = currentNode.rightChild;\n currentIndex = currentIndex * 2 + 1;\n }\n }\n\n if (currentNode == null) {\n return priorityQueue;\n }\n\n return currentNode;\n }\n }\n\n public static void main(String[] args) {\n Exercise24_PriorityQueueExplicitLinks.PriorityQueueExplicitLinks priorityQueueExplicitLinks =\n new Exercise24_PriorityQueueExplicitLinks().new PriorityQueueExplicitLinks();\n\n StdOut.println(\"isEmpty: \" + priorityQueueExplicitLinks.isEmpty() + \" Expected: true\");\n\n priorityQueueExplicitLinks.insert(10);\n priorityQueueExplicitLinks.insert(2);\n priorityQueueExplicitLinks.insert(7);\n priorityQueueExplicitLinks.insert(20);\n\n StdOut.println(\"Size: \" + priorityQueueExplicitLinks.size() + \" Expected: 4\");\n StdOut.println(\"isEmpty: \" + priorityQueueExplicitLinks.isEmpty() + \" Expected: false\");\n\n StdOut.println(\"Item removed: \" + priorityQueueExplicitLinks.deleteMax());\n StdOut.println(\"Item removed: \" + priorityQueueExplicitLinks.deleteMax());\n StdOut.println(\"Item removed: \" + priorityQueueExplicitLinks.deleteMax());\n StdOut.println(\"Item removed: \" + priorityQueueExplicitLinks.deleteMax());\n }\n}\n", "support_files": [], "metadata": {"number": "2.4.24", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Creative Problem", "code_execution": false}} {"question": "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, 0), (2^3, 2, 0), . . . , (N^3, N, 0). 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.", "answer": "Maintain one pending item for each possible `a`, where the item stores `(sum, a, b)` and `sum = a^3 + b^3`. Delete the minimum sum, print it, and then insert the next value for the same `a`.\n\n```java\nimport edu.princeton.cs.algs4.MinPQ;\nimport edu.princeton.cs.algs4.StdOut;\n\npublic class CubeSum implements Comparable {\n private final int a;\n private final int b;\n private final long sum;\n\n public CubeSum(int a, int b) {\n this.a = a;\n this.b = b;\n this.sum = (long) a * a * a + (long) b * b * b;\n }\n\n public int compareTo(CubeSum that) {\n return Long.compare(this.sum, that.sum);\n }\n\n public String toString() {\n return sum + \" = \" + a + \"^3 + \" + b + \"^3\";\n }\n\n public static void main(String[] args) {\n int n = Integer.parseInt(args[0]);\n MinPQ pq = new MinPQ<>();\n for (int a = 0; a <= n; a++) pq.insert(new CubeSum(a, 0));\n\n while (!pq.isEmpty()) {\n CubeSum x = pq.delMin();\n StdOut.println(x);\n if (x.b < n) pq.insert(new CubeSum(x.a, x.b + 1));\n }\n }\n}\n```\n\nThis prints all `(N+1)^2` sums in sorted order using only `O(N)` priority-queue space.", "support_files": [], "metadata": {"number": "2.4.25", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Creative Problem", "code_execution": false}} {"question": "Heap without exchanges. Because the exch() primitive is used in the sink() and swim() operations, the items are loaded and stored twice as often as necessary. Give more efficient implementations that avoid this inefficiency, a la insertion sort (see Exercise 2.1.25).", "answer": "package chapter2.section4;\n\nimport edu.princeton.cs.algs4.StdOut;\nimport util.ArrayUtil;\n\n/**\n * Created by Rene Argento on 25/03/17.\n */\n@SuppressWarnings(\"unchecked\")\npublic class Exercise26_HeapWithoutExchanges {\n\n private enum Orientation {\n MAX, MIN;\n }\n\n private class PriorityQueue> {\n\n private Key[] priorityQueue;\n private int size = 0; // in priorityQueue[1..n] with pq[0] unused\n private Orientation orientation;\n\n PriorityQueue(int size, Orientation orientation) {\n priorityQueue = (Key[]) new Comparable[size + 1];\n this.orientation = orientation;\n }\n\n public boolean isEmpty() {\n return size == 0;\n }\n\n public int size() {\n return size;\n }\n\n public void insert(Key key) {\n if (size != priorityQueue.length - 1) {\n size++;\n\n priorityQueue[size] = key;\n swim(size);\n }\n }\n\n Key deleteTop() {\n if (size == 0) {\n throw new RuntimeException(\"Priority queue underflow\");\n }\n\n size--;\n\n Key topElement = priorityQueue[1];\n ArrayUtil.exchange(priorityQueue, 1, size + 1);\n\n priorityQueue[size + 1] = null;\n sink(1);\n\n return topElement;\n }\n\n private void swim(int index) {\n Key aux = priorityQueue[index];\n\n boolean exchangeRequired = false;\n\n while (index / 2 >= 1) {\n if ((orientation == Orientation.MAX && ArrayUtil.less(priorityQueue[index / 2], aux))\n || (orientation == Orientation.MIN && ArrayUtil.more(priorityQueue[index / 2], aux))) {\n priorityQueue[index] = priorityQueue[index / 2];\n exchangeRequired = true;\n } else {\n break;\n }\n\n index = index / 2;\n }\n\n if (exchangeRequired) {\n priorityQueue[index] = aux;\n }\n }\n\n private void sink(int index) {\n\n Key aux = priorityQueue[index];\n\n while (index * 2 <= size) {\n int selectedChildIndex = index * 2;\n\n if (index * 2 + 1 <= size &&\n (\n (orientation == Orientation.MAX && ArrayUtil.less(priorityQueue[index * 2], priorityQueue[index * 2 + 1]))\n || (orientation == Orientation.MIN && ArrayUtil.more(priorityQueue[index * 2], priorityQueue[index * 2 + 1]))\n )\n ) {\n selectedChildIndex = index * 2 + 1;\n }\n\n if ((orientation == Orientation.MAX && ArrayUtil.more(priorityQueue[selectedChildIndex], aux))\n || (orientation == Orientation.MIN && ArrayUtil.less(priorityQueue[selectedChildIndex], aux))) {\n priorityQueue[index] = priorityQueue[selectedChildIndex];\n } else {\n break;\n }\n\n index = selectedChildIndex;\n }\n\n // No need to check if an exchange is required.\n // The value of index is only updated when an exchange happens.\n priorityQueue[index] = aux;\n }\n }\n\n public static void main(String[] args) {\n Exercise26_HeapWithoutExchanges.PriorityQueue priorityQueue =\n new Exercise26_HeapWithoutExchanges().new PriorityQueue(4, Orientation.MAX);\n\n priorityQueue.insert(10);\n priorityQueue.insert(2);\n priorityQueue.insert(7);\n priorityQueue.insert(20);\n\n StdOut.println(\"Size: \" + priorityQueue.size());\n StdOut.println(\"isEmpty: \" + priorityQueue.isEmpty());\n\n StdOut.println(\"Item removed: \" + priorityQueue.deleteTop() + \" Expected: 20\");\n StdOut.println(\"Item removed: \" + priorityQueue.deleteTop() + \" Expected: 10\");\n StdOut.println(\"Item removed: \" + priorityQueue.deleteTop() + \" Expected: 7\");\n StdOut.println(\"Item removed: \" + priorityQueue.deleteTop() + \" Expected: 2\");\n }\n}\n", "support_files": [], "metadata": {"number": "2.4.26", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Creative Problem", "code_execution": false}} {"question": "Find the minimum. Add a min() method to MaxPQ. Your implementation should use constant time and constant extra space.", "answer": "package chapter2.section4;\n\nimport edu.princeton.cs.algs4.StdOut;\nimport util.ArrayUtil;\n\n/**\n * Created by Rene Argento on 25/03/17.\n */\n@SuppressWarnings(\"unchecked\")\npublic class Exercise27_FindTheMinimum {\n\n private class PriorityQueue> {\n\n private Key[] priorityQueue;\n private int size = 0; // in priorityQueue[1..n] with pq[0] unused\n\n private Key min;\n\n PriorityQueue(int size) {\n priorityQueue = (Key[]) new Comparable[size + 1];\n }\n\n public boolean isEmpty() {\n return size == 0;\n }\n\n public int size() {\n return size;\n }\n\n public void insert(Key key) {\n if (size != priorityQueue.length - 1) {\n size++;\n\n if (min == null || ArrayUtil.less(key, min)) {\n min = key;\n }\n\n priorityQueue[size] = key;\n swim(size);\n }\n }\n\n Key deleteMax() {\n if (size == 0) {\n throw new RuntimeException(\"Priority queue underflow\");\n }\n\n size--;\n\n Key max = priorityQueue[1];\n ArrayUtil.exchange(priorityQueue, 1, size + 1);\n\n if (size == 0) {\n min = null;\n }\n\n priorityQueue[size + 1] = null;\n sink(1);\n\n return max;\n }\n\n private void swim(int index) {\n while (index / 2 >= 1 && ArrayUtil.less(priorityQueue[index / 2], priorityQueue[index])) {\n ArrayUtil.exchange(priorityQueue, index / 2, index);\n\n index = index / 2;\n }\n }\n\n private void sink(int index) {\n while (index * 2 <= size) {\n int selectedChildIndex = index * 2;\n\n if (index * 2 + 1 <= size && ArrayUtil.less(priorityQueue[index * 2], priorityQueue[index * 2 + 1])) {\n selectedChildIndex = index * 2 + 1;\n }\n\n if (ArrayUtil.more(priorityQueue[selectedChildIndex], priorityQueue[index])) {\n ArrayUtil.exchange(priorityQueue, index, selectedChildIndex);\n } else {\n break;\n }\n\n index = selectedChildIndex;\n }\n }\n\n public Key min() {\n return min;\n }\n }\n\n public static void main(String[] args) {\n Exercise27_FindTheMinimum.PriorityQueue priorityQueue =\n new Exercise27_FindTheMinimum().new PriorityQueue(5);\n\n StdOut.println(\"Min: \" + priorityQueue.min() + \" Expected: null\");\n\n priorityQueue.insert(10);\n\n StdOut.println(\"Min: \" + priorityQueue.min() + \" Expected: 10\");\n\n priorityQueue.insert(2);\n\n StdOut.println(\"Min: \" + priorityQueue.min() + \" Expected: 2\");\n\n priorityQueue.insert(7);\n\n StdOut.println(\"Min: \" + priorityQueue.min() + \" Expected: 2\");\n\n priorityQueue.insert(20);\n priorityQueue.insert(1);\n\n StdOut.println(\"Min: \" + priorityQueue.min() + \" Expected: 1\");\n\n StdOut.println(\"Item removed: \" + priorityQueue.deleteMax());\n StdOut.println(\"Item removed: \" + priorityQueue.deleteMax());\n StdOut.println(\"Item removed: \" + priorityQueue.deleteMax());\n StdOut.println(\"Item removed: \" + priorityQueue.deleteMax());\n\n StdOut.println(\"Min: \" + priorityQueue.min() + \" Expected: 1\");\n\n StdOut.println(\"Item removed: \" + priorityQueue.deleteMax());\n\n priorityQueue.insert(99);\n StdOut.println(\"Min: \" + priorityQueue.min() + \" Expected: 99\");\n }\n}\n", "support_files": [], "metadata": {"number": "2.4.27", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Creative Problem", "code_execution": false}} {"question": "Selection filter. Write a TopM client that reads points (x, y, z) from standard input, takes a value M from the command line, and prints the M points that are closest to the origin in Euclidean distance. Estimate the running time of your client for N = 10^8 and M = 10^4.", "answer": "// Exercise28_SelectionFilter.java\npackage chapter2.section4;\n\nimport edu.princeton.cs.algs4.StdIn;\nimport edu.princeton.cs.algs4.StdOut;\nimport edu.princeton.cs.algs4.StdRandom;\nimport edu.princeton.cs.algs4.Stopwatch;\n\nimport java.util.Stack;\n\n/**\n * Created by Rene Argento on 25/03/17.\n */\npublic class Exercise28_SelectionFilter {\n\n private class Point implements Comparable{\n double x, y, z;\n\n Point(double x, double y, double z) {\n this.x = x;\n this.y = y;\n this.z = z;\n }\n\n @Override\n public int compareTo(Point other) {\n //Distance to 0,0 (origin)\n double euclideanDistance = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2));\n double otherPointEuclideanDistance = Math.sqrt(Math.pow(other.x, 2) + Math.pow(other.y, 2) +\n Math.pow(other.z, 2));\n\n if (euclideanDistance < otherPointEuclideanDistance) {\n return -1;\n } else if (euclideanDistance > otherPointEuclideanDistance) {\n return 1;\n } else {\n return 0;\n }\n }\n\n @Override\n public String toString() {\n return \"x = \" + x + \" y = \" + y + \" z = \" + z;\n }\n }\n\n // Parameter example: 10000\n public static void main(String[] args) {\n\n int m = Integer.parseInt(args[0]);\n\n PriorityQueue priorityQueue = new PriorityQueue<>(m + 1, PriorityQueue.Orientation.MAX);\n\n while (StdIn.hasNextLine()) {\n String pointsLine = StdIn.readLine();\n\n String[] pointsString = pointsLine.split(\" \");\n double x = Double.parseDouble(pointsString[0]);\n double y = Double.parseDouble(pointsString[1]);\n double z = Double.parseDouble(pointsString[2]);\n\n Point point = new Exercise28_SelectionFilter().new Point(x, y, z);\n priorityQueue.insert(point);\n\n if (priorityQueue.size() > m) {\n priorityQueue.deleteTop();\n }\n }\n\n Stack pointsStack = reversePointsOrder(priorityQueue);\n printPoints(pointsStack);\n\n //Estimate running time\n int initialArraySize = 100000; //10^5\n int numberOfExperiments = 3; //10^5, 10^6, 10^7\n doExperimentToEstimateRunningTime(initialArraySize, numberOfExperiments);\n }\n\n private static Stack reversePointsOrder(PriorityQueue priorityQueue) {\n Stack stack = new Stack<>();\n\n while (priorityQueue.size() > 0) {\n stack.push(priorityQueue.deleteTop());\n }\n\n return stack;\n }\n\n private static void printPoints(Stack pointsStack) {\n while (pointsStack.size() > 0) {\n StdOut.println(pointsStack.pop());\n }\n }\n\n private static void doExperimentToEstimateRunningTime(int arraySize, int numberOfExperiments) {\n int m = 10000; //10^4\n\n for (int i = 0; i < numberOfExperiments; i++) {\n\n PriorityQueue priorityQueue = new PriorityQueue<>(m + 1, PriorityQueue.Orientation.MAX);\n\n Point[] pointArray = generateRandomPointsArray(arraySize);\n\n Stopwatch timer = new Stopwatch();\n\n for (Point point : pointArray) {\n priorityQueue.insert(point);\n\n if (priorityQueue.size() > m) {\n priorityQueue.deleteTop();\n }\n }\n\n Stack pointsStack = reversePointsOrder(priorityQueue);\n printPoints(pointsStack);\n\n double runningTime = timer.elapsedTime();\n StdOut.println(\"Running time for N = \" + arraySize + \" and M = \" + m + \": \" + runningTime);\n\n arraySize *= 10;\n }\n }\n\n private static Point[] generateRandomPointsArray(int length) {\n Point[] array = new Point[length];\n\n for (int i = 0; i < length; i++) {\n double x = StdRandom.uniform();\n double y = StdRandom.uniform();\n double z = StdRandom.uniform();\n\n Point point = new Exercise28_SelectionFilter().new Point(x, y, z);\n array[i] = point;\n }\n return array;\n }\n}\n\nAdditional notes/results:\n2.4.28 - Selection filter\n\nRunning time for N = 100000 and M = 10000: 0.053\nRunning time for N = 1000000 and M = 10000: 0.365\nRunning time for N = 10000000 and M = 10000: 3.362\n\nN = 10^5 to N^6 increased the running time by 6.9 times. \nN = 10^6 to N^7 increased the running time by 9.21 times.\nEstimated increase from N^7 to N^8: 12.29 times the running time of N^7. \n\nEstimated running time for N = 10^8 and M = 10^4 = 41.32 seconds\n\nSample input\n\n10 20 10\n1 2 3\n90 91 92\n10 11 10\n3 3 4\n-1 -4 0\n20 10 13\n100 102 999\n1001 98 10\n\nSample output\nx = 1.0 y = 2.0 z = 3.0\nx = -1.0 y = -4.0 z = 0.0\nx = 3.0 y = 3.0 z = 4.0\nx = 10.0 y = 11.0 z = 10.0\nx = 10.0 y = 20.0 z = 10.0", "support_files": [], "metadata": {"number": "2.4.28", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Creative Problem", "code_execution": false}} {"question": "Min/max priority queue. Design a data type that supports the following operations: insert, delete the maximum, and delete the minimum (all in logarithmic time); and find the maximum and find the minimum (both in constant time). Hint: Use two heaps.", "answer": "package chapter2.section4;\n\nimport edu.princeton.cs.algs4.StdOut;\nimport util.ArrayUtil;\n\n/**\n * Created by Rene Argento on 25/03/17.\n */\n// Based on: http://eranle.blogspot.com.br/2012/08/min-max-heap-java-implementation.html\n// Thanks to YRFT (https://github.com/YRFT) for finding that the method deleteItem() also needs to call the swim() method:\n// https://github.com/reneargento/algorithms-sedgewick-wayne/issues/181\n@SuppressWarnings(\"unchecked\")\npublic class Exercise29_MinMaxPriorityQueue {\n\n private enum Orientation {\n MAX, MIN;\n }\n\n private class PQNode implements Comparable{\n Comparable key;\n int minHeapIndex;\n int maxHeapIndex;\n\n @Override\n public int compareTo(PQNode other) {\n return key.compareTo(other.key);\n }\n }\n\n private class MinMaxPriorityQueue> {\n private PQNode[] minPriorityQueue;\n private PQNode[] maxPriorityQueue;\n private int size = 0;\n\n MinMaxPriorityQueue() {\n minPriorityQueue = new PQNode[2];\n maxPriorityQueue = new PQNode[2];\n }\n\n public boolean isEmpty() {\n return size == 0;\n }\n\n public int size() {\n return size;\n }\n\n public void insert(Key key) {\n if (size == minPriorityQueue.length - 1) {\n resize(minPriorityQueue.length * 2);\n }\n\n PQNode pqNode = new PQNode();\n pqNode.key = key;\n\n size++;\n\n insertOnMinHeap(pqNode);\n insertOnMaxHeap(pqNode);\n }\n\n private void insertOnMinHeap(PQNode pqNode) {\n minPriorityQueue[size] = pqNode;\n swim(minPriorityQueue, size, Orientation.MIN);\n }\n\n private void insertOnMaxHeap(PQNode pqNode) {\n maxPriorityQueue[size] = pqNode;\n swim(maxPriorityQueue, size, Orientation.MAX);\n }\n\n // O(1)\n public Comparable findMin() {\n if (size == 0) {\n return null;\n }\n\n return minPriorityQueue[1].key;\n }\n\n // O(1)\n public Comparable findMax() {\n if (size == 0) {\n return null;\n }\n\n return maxPriorityQueue[1].key;\n }\n\n // O(lg N)\n public Comparable deleteMax() {\n if (size == 0) {\n throw new RuntimeException(\"Priority queue underflow\");\n }\n\n size--;\n\n PQNode max = maxPriorityQueue[1];\n\n deleteTopItem(maxPriorityQueue, Orientation.MAX);\n deleteItem(minPriorityQueue, Orientation.MIN, max.minHeapIndex);\n\n if (size == minPriorityQueue.length / 4) {\n resize(minPriorityQueue.length / 2);\n }\n\n return max.key;\n }\n\n // O(lg N)\n public Comparable deleteMin() {\n if (size == 0) {\n throw new RuntimeException(\"Priority queue underflow\");\n }\n\n size--;\n\n PQNode min = minPriorityQueue[1];\n\n deleteTopItem(minPriorityQueue, Orientation.MIN);\n deleteItem(maxPriorityQueue, Orientation.MAX, min.maxHeapIndex);\n\n if (size == minPriorityQueue.length / 4) {\n resize(minPriorityQueue.length / 2);\n }\n\n return min.key;\n }\n\n private void deleteTopItem(PQNode[] priorityQueue, Orientation orientation) {\n deleteItem(priorityQueue, orientation, 1);\n }\n\n private void deleteItem(PQNode[] priorityQueue, Orientation orientation, int index) {\n ArrayUtil.exchange(priorityQueue, index, size + 1);\n priorityQueue[size + 1] = null;\n\n if (index == size + 1) {\n // We deleted the last value, so no need to sink\n return;\n }\n\n sink(priorityQueue, index, orientation);\n swim(priorityQueue, index, orientation);\n }\n\n private void swim(PQNode[] priorityQueue, int index, Orientation orientation) {\n while (index / 2 >= 1) {\n if ((orientation == Orientation.MAX && ArrayUtil.less(priorityQueue[index / 2], priorityQueue[index]))\n || (orientation == Orientation.MIN && ArrayUtil.more(priorityQueue[index / 2], priorityQueue[index]))) {\n ArrayUtil.exchange(priorityQueue, index / 2, index);\n\n if (orientation == Orientation.MIN) {\n priorityQueue[index].minHeapIndex = index;\n priorityQueue[index / 2].minHeapIndex = index / 2;\n } else {\n priorityQueue[index].maxHeapIndex = index;\n priorityQueue[index / 2].maxHeapIndex = index / 2;\n }\n } else {\n break;\n }\n\n index = index / 2;\n }\n\n // Even if there were no exchanges, we still need to update the index\n if (orientation == Orientation.MIN) {\n priorityQueue[index].minHeapIndex = index;\n } else {\n priorityQueue[index].maxHeapIndex = index;\n }\n }\n\n private void sink(PQNode[] priorityQueue, int index, Orientation orientation) {\n while (index * 2 <= size) {\n int selectedChildIndex = index * 2;\n\n if (index * 2 + 1 <= size &&\n (\n (orientation == Orientation.MAX && ArrayUtil.less(priorityQueue[index * 2], priorityQueue[index * 2 + 1]))\n || (orientation == Orientation.MIN && ArrayUtil.more(priorityQueue[index * 2], priorityQueue[index * 2 + 1]))\n )\n ) {\n selectedChildIndex = index * 2 + 1;\n }\n\n if ((orientation == Orientation.MAX && ArrayUtil.more(priorityQueue[selectedChildIndex], priorityQueue[index]))\n || (orientation == Orientation.MIN && ArrayUtil.less(priorityQueue[selectedChildIndex], priorityQueue[index]))) {\n ArrayUtil.exchange(priorityQueue, index, selectedChildIndex);\n\n if (orientation == Orientation.MIN) {\n priorityQueue[index].minHeapIndex = index;\n priorityQueue[selectedChildIndex].minHeapIndex = selectedChildIndex;\n } else {\n priorityQueue[index].maxHeapIndex = index;\n priorityQueue[selectedChildIndex].maxHeapIndex = selectedChildIndex;\n }\n } else {\n break;\n }\n\n index = selectedChildIndex;\n }\n\n // Even if there were no exchanges, we still need to update the index\n if (orientation == Orientation.MIN) {\n priorityQueue[index].minHeapIndex = index;\n } else {\n priorityQueue[index].maxHeapIndex = index;\n }\n }\n\n private void resize(int newSize) {\n // Min heap\n PQNode[] newMinPriorityQueue = new PQNode[newSize];\n System.arraycopy(minPriorityQueue, 1, newMinPriorityQueue, 1, size);\n minPriorityQueue = newMinPriorityQueue;\n\n // Max heap\n PQNode[] newMaxPriorityQueue = new PQNode[newSize];\n System.arraycopy(maxPriorityQueue, 1, newMaxPriorityQueue, 1, size);\n maxPriorityQueue = newMaxPriorityQueue;\n }\n }\n\n public static void main(String[] args) {\n Exercise29_MinMaxPriorityQueue.MinMaxPriorityQueue minMaxPriorityQueue =\n new Exercise29_MinMaxPriorityQueue().new MinMaxPriorityQueue();\n\n minMaxPriorityQueue.insert(10);\n minMaxPriorityQueue.insert(2);\n minMaxPriorityQueue.insert(40);\n minMaxPriorityQueue.insert(1);\n\n StdOut.println(\"Delete Max: \" + minMaxPriorityQueue.deleteMax() + \" Expected: 40\");\n StdOut.println(\"Delete Min: \" + minMaxPriorityQueue.deleteMin() + \" Expected: 1\");\n\n StdOut.println(\"Find Max: \" + minMaxPriorityQueue.findMax() + \" Expected: 10\");\n StdOut.println(\"Find Min: \" + minMaxPriorityQueue.findMin() + \" Expected: 2\");\n\n minMaxPriorityQueue.insert(99);\n minMaxPriorityQueue.insert(-1);\n\n StdOut.println(\"Find Max: \" + minMaxPriorityQueue.findMax() + \" Expected: 99\");\n StdOut.println(\"Find Min: \" + minMaxPriorityQueue.findMin() + \" Expected: -1\");\n }\n}\n", "support_files": [], "metadata": {"number": "2.4.29", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Creative Problem", "code_execution": false}} {"question": "Dynamic median-finding. Design a data type that supports insert in logarithmic time, find the median in constant time, and delete the median in logarithmic time. Hint: Use a min-heap and a max-heap.", "answer": "package chapter2.section4;\n\nimport edu.princeton.cs.algs4.StdOut;\nimport util.ArrayUtil;\n\n/**\n * Created by Rene Argento on 26/03/17.\n */\npublic class Exercise30_DynamicMedianFinding {\n\n private class DynamicMedianFindingHeap> {\n\n private PriorityQueueResize minPriorityQueue;\n private PriorityQueueResize maxPriorityQueue;\n\n private int size;\n\n DynamicMedianFindingHeap() {\n minPriorityQueue = new PriorityQueueResize<>(PriorityQueueResize.Orientation.MIN);\n maxPriorityQueue = new PriorityQueueResize<>(PriorityQueueResize.Orientation.MAX);\n size = 0;\n }\n\n //O(lg N)\n public void insert(Key key) {\n\n if (size == 0 || ArrayUtil.less(key, maxPriorityQueue.peek())) {\n maxPriorityQueue.insert(key);\n } else {\n minPriorityQueue.insert(key);\n }\n\n if (minPriorityQueue.size() > maxPriorityQueue.size() + 1) {\n Key keyToBeMoved = minPriorityQueue.deleteTop();\n maxPriorityQueue.insert(keyToBeMoved);\n } else if (maxPriorityQueue.size() > minPriorityQueue.size() + 1) {\n Key keyToBeMoved = maxPriorityQueue.deleteTop();\n minPriorityQueue.insert(keyToBeMoved);\n }\n\n size++;\n }\n\n //O(1)\n public Key findTheMedian() {\n Key median;\n\n if (minPriorityQueue.size() > maxPriorityQueue.size()) {\n median = minPriorityQueue.peek();\n } else {\n median = maxPriorityQueue.peek();\n }\n\n return median;\n }\n\n //O(lg N)\n public Key deleteMedian() {\n Key median;\n\n if (minPriorityQueue.size() > maxPriorityQueue.size()) {\n median = minPriorityQueue.deleteTop();\n } else {\n median = maxPriorityQueue.deleteTop();\n }\n\n size--;\n\n return median;\n }\n }\n\n public static void main(String[] args) {\n Exercise30_DynamicMedianFinding.DynamicMedianFindingHeap dynamicMedianFindingHeap =\n new Exercise30_DynamicMedianFinding().new DynamicMedianFindingHeap<>();\n\n dynamicMedianFindingHeap.insert(1);\n dynamicMedianFindingHeap.insert(2);\n dynamicMedianFindingHeap.insert(3);\n dynamicMedianFindingHeap.insert(4);\n dynamicMedianFindingHeap.insert(5);\n dynamicMedianFindingHeap.insert(6);\n dynamicMedianFindingHeap.insert(7);\n\n StdOut.println(\"Median: \" + dynamicMedianFindingHeap.findTheMedian() + \" Expected: 4\");\n StdOut.println(\"Delete Median: \" + dynamicMedianFindingHeap.deleteMedian() + \" Expected: 4\");\n\n //When we have an even number of values, pick the left one\n StdOut.println(\"Median: \" + dynamicMedianFindingHeap.findTheMedian() + \" Expected: 3\");\n\n dynamicMedianFindingHeap.deleteMedian();\n dynamicMedianFindingHeap.insert(99);\n dynamicMedianFindingHeap.insert(100);\n\n StdOut.println(\"Median: \" + dynamicMedianFindingHeap.findTheMedian() + \" Expected: 6\");\n }\n\n}\n", "support_files": [], "metadata": {"number": "2.4.30", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Creative Problem", "code_execution": false}} {"question": "Fast insert. Develop a compare-based implementation of the MinPQ API such that insert uses ~log log N compares and delete the minimum uses ~2 log N compares. Hint: Use binary search on parent pointers to find the ancestor in swim().", "answer": "package chapter2.section4;\n\nimport edu.princeton.cs.algs4.StdOut;\nimport util.ArrayUtil;\n\n/**\n * Created by Rene Argento on 26/03/17.\n */\n// Thanks to dragon-dreamer (https://github.com/dragon-dreamer) for suggesting an improved binarySearchToGetTargetAncestor() method.\n// https://github.com/reneargento/algorithms-sedgewick-wayne/issues/114\n@SuppressWarnings(\"unchecked\")\npublic class Exercise31_FastInsert {\n\n private class PriorityQueueFastInsert> {\n private Key[] priorityQueue;\n private int size = 0; // in priorityQueue[1..n] with pq[0] unused\n\n private int numberOfCompares;\n\n PriorityQueueFastInsert() {\n priorityQueue = (Key[]) new Comparable[2];\n }\n\n public boolean isEmpty() {\n return size == 0;\n }\n\n public int size() {\n return size;\n }\n\n public void insert(Key key) {\n numberOfCompares = 0;\n\n if (size == priorityQueue.length - 1) {\n resize(priorityQueue.length * 2);\n }\n size++;\n priorityQueue[size] = key;\n\n swim(size);\n\n double lgN = Math.log10(size) / Math.log10(2);\n int lgLgN = lgN != 0 ? (int) (Math.log10(lgN) / Math.log10(2)) : 0;\n\n StdOut.println(\"Number of compares: \" + numberOfCompares + \" Expected: ~\" + lgLgN);\n }\n\n public Key deleteMin() {\n numberOfCompares = 0;\n\n if (size == 0) {\n throw new RuntimeException(\"Priority queue underflow\");\n }\n size--;\n\n Key min = priorityQueue[1];\n\n ArrayUtil.exchange(priorityQueue, 1, size + 1);\n priorityQueue[size + 1] = null;\n\n sink(1);\n\n if (size == priorityQueue.length / 4) {\n resize(priorityQueue.length / 2);\n }\n\n int lgN = (int) (Math.log10(size) / Math.log10(2));\n StdOut.println(\"Number of compares: \" + numberOfCompares + \" Expected: ~\" + (2 * lgN));\n\n return min;\n }\n\n private void swim(int index) {\n // No need to swim if we only have 1 element\n if (index == 1) {\n return;\n }\n\n int targetAncestor = binarySearchToGetTargetAncestor(index);\n\n while (index / 2 >= targetAncestor) {\n ArrayUtil.exchange(priorityQueue, index / 2, index);\n index = index / 2;\n }\n }\n\n private int binarySearchToGetTargetAncestor(int index) {\n int higherLevel = 0;\n int indexLevel = log2(index);\n int lowerLevel = indexLevel;\n\n while (lowerLevel != higherLevel) {\n int middleLevel = higherLevel + (lowerLevel - higherLevel) / 2;\n int parentIndex = index / (1 << (indexLevel - middleLevel));\n\n numberOfCompares++;\n if (ArrayUtil.more(priorityQueue[parentIndex], priorityQueue[index])) {\n lowerLevel = middleLevel;\n } else {\n higherLevel = middleLevel + 1;\n }\n }\n return index / (1 << (indexLevel - higherLevel));\n }\n\n private int log2(int value) {\n int result = 0;\n while ((value >>= 1) != 0) {\n result++;\n }\n return result;\n }\n\n private void sink(int index) {\n while (index * 2 <= size) {\n int selectedChildIndex = index * 2;\n\n numberOfCompares++;\n if (index * 2 + 1 <= size && ArrayUtil.more(priorityQueue[index * 2], priorityQueue[index * 2 + 1])) {\n selectedChildIndex = index * 2 + 1;\n }\n\n numberOfCompares++;\n if (ArrayUtil.less(priorityQueue[selectedChildIndex], priorityQueue[index])) {\n ArrayUtil.exchange(priorityQueue, index, selectedChildIndex);\n } else {\n break;\n }\n\n index = selectedChildIndex;\n }\n }\n\n private void resize(int newSize) {\n Key[] newPriorityQueue = (Key[]) new Comparable[newSize];\n System.arraycopy(priorityQueue, 1, newPriorityQueue, 1, size);\n priorityQueue = newPriorityQueue;\n }\n }\n\n public static void main(String[] args) {\n Exercise31_FastInsert.PriorityQueueFastInsert priorityQueueFastInsert =\n new Exercise31_FastInsert().new PriorityQueueFastInsert<>();\n\n // Insert many items and later insert smaller items to check the number of compares\n for (int i = 10; i <= 42; i++) {\n priorityQueueFastInsert.insert(i);\n }\n\n priorityQueueFastInsert.insert(2);\n priorityQueueFastInsert.insert(1);\n\n // Also test delete min\n StdOut.println(\"Delete Min: \" + priorityQueueFastInsert.deleteMin() + \" Expected: 1\");\n StdOut.println(\"Delete Min: \" + priorityQueueFastInsert.deleteMin() + \" Expected: 2\");\n StdOut.println(\"Delete Min: \" + priorityQueueFastInsert.deleteMin() + \" Expected: 10\");\n }\n}\n", "support_files": [], "metadata": {"number": "2.4.31", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Creative Problem", "code_execution": false}} {"question": "Index priority-queue implementation (additional operations). Add minIndex(), change(), and delete() to your implementation of Exercise 2.4.33.", "answer": "package chapter2.section4;\n\nimport edu.princeton.cs.algs4.StdOut;\nimport edu.princeton.cs.algs4.StdRandom;\n\nimport java.util.NoSuchElementException;\n\n/**\n * Created by Rene Argento on 26/03/17.\n */\n//Based on http://algs4.cs.princeton.edu/24pq/IndexMaxPQ.java.html\n@SuppressWarnings(\"unchecked\")\npublic class Exercise34_IndexPQAdditionalOps {\n\n private class IndexMinPQ> {\n\n private Key[] keys;\n private int[] pq; // Holds the indices of the keys\n private int[] qp; // Inverse of pq -> qp[i] gives the position of i in pq[] (the index j such that pq[j] is i).\n // qp[pq[i]] = pq[qp[i]] = i\n private int size = 0;\n\n @SuppressWarnings(\"unchecked\")\n public IndexMinPQ(int size) {\n keys = (Key[]) new Comparable[size + 1];\n pq = new int[size + 1];\n qp = new int[size + 1];\n\n for (int i = 0; i < qp.length; i++) {\n qp[i] = -1;\n }\n }\n\n public boolean isEmpty() {\n return size == 0;\n }\n\n public int size() {\n return size;\n }\n\n public boolean contains(int index) {\n return qp[index] != -1;\n }\n\n //Return key associated with index\n public Key keyOf(int index) {\n if (!contains(index)) {\n throw new NoSuchElementException(\"Index is not in the priority queue\");\n }\n\n return keys[index];\n }\n\n public void insert(int index, Key key) {\n if (contains(index)) {\n throw new IllegalArgumentException(\"Index is already in the priority queue\");\n }\n\n if (size != keys.length - 1) {\n size++;\n\n keys[index] = key;\n pq[size] = index;\n qp[index] = size;\n\n swim(size);\n }\n }\n\n //Remove a minimal key and return its index\n public int deleteMin() {\n if (size == 0) {\n throw new NoSuchElementException(\"Priority queue underflow\");\n }\n\n int minElementIndex = pq[1];\n exchange(1, size);\n size--;\n sink(1);\n\n keys[pq[size + 1]] = null;\n qp[pq[size + 1]] = -1;\n\n return minElementIndex;\n }\n\n public void delete(int i) {\n if (!contains(i)) {\n throw new NoSuchElementException(\"Index is not in the priority queue\");\n }\n\n int index = qp[i];\n\n exchange(index, size);\n size--;\n\n swim(index);\n sink(index);\n\n keys[i] = null; //Same thing as keys[pq[size + 1]] = null\n qp[i] = -1; //Same thing as qp[pq[size + 1]] = -1;\n }\n\n //Change the key associated with index to key argument\n public void change(int index, Key key) {\n if (!contains(index)) {\n throw new NoSuchElementException(\"Index is not in the priority queue\");\n }\n\n keys[index] = key;\n\n swim(qp[index]);\n sink(qp[index]);\n }\n\n public Key minKey() {\n if (size == 0) {\n throw new NoSuchElementException(\"Priority queue underflow\");\n }\n\n return keys[pq[1]];\n }\n\n public int minIndex() {\n if (size == 0) {\n throw new NoSuchElementException(\"Priority queue underflow\");\n }\n\n return pq[1];\n }\n\n private void swim(int index) {\n while (index / 2 >= 1 && more(index / 2, index)) {\n exchange(index / 2, index);\n index = index / 2;\n }\n }\n\n private void sink(int index) {\n while (index * 2 <= size) {\n int selectedChildIndex = index * 2;\n\n if (index * 2 + 1 <= size && more(index * 2, index * 2 + 1)) {\n selectedChildIndex = index * 2 + 1;\n }\n\n if (less(selectedChildIndex, index)) {\n exchange(index, selectedChildIndex);\n } else {\n break;\n }\n\n index = selectedChildIndex;\n }\n }\n\n private boolean less(int keyIndex1, int keyIndex2) {\n return keys[pq[keyIndex1]].compareTo(keys[pq[keyIndex2]]) < 0;\n }\n\n private boolean more(int keyIndex1, int keyIndex2) {\n return keys[pq[keyIndex1]].compareTo(keys[pq[keyIndex2]]) > 0;\n }\n\n private void exchange(int keyIndex1, int keyIndex2) {\n int temp = pq[keyIndex1];\n pq[keyIndex1] = pq[keyIndex2];\n pq[keyIndex2] = temp;\n\n qp[pq[keyIndex1]] = keyIndex1;\n qp[pq[keyIndex2]] = keyIndex2;\n }\n }\n\n public static void main(String[] args) {\n // Insert a bunch of strings\n String[] strings = { \"it\", \"was\", \"the\", \"best\", \"of\", \"times\", \"it\", \"was\", \"the\", \"worst\" };\n\n Exercise34_IndexPQAdditionalOps.IndexMinPQ priorityQueue =\n new Exercise34_IndexPQAdditionalOps().new IndexMinPQ<>(strings.length);\n\n for (int i = 0; i < strings.length; i++) {\n priorityQueue.insert(i, strings[i]);\n }\n\n StdOut.println(\"Min index: \" + priorityQueue.minIndex() + \" Expected: 3\");\n\n priorityQueue.changeKey(4, \"changed\");\n StdOut.println(\"Changed key: \" + priorityQueue.keyOf(4) + \" Expected: changed\");\n\n // Delete and print each key\n StdOut.println(\"Keys:\");\n\n while (!priorityQueue.isEmpty()) {\n String key = priorityQueue.minKey();\n int index = priorityQueue.deleteMin();\n StdOut.println(index + \" \" + key);\n }\n StdOut.println();\n\n // Reinsert the same strings\n for (int i = 0; i < strings.length; i++) {\n priorityQueue.insert(i, strings[i]);\n }\n\n // Delete and print them in random order\n int[] randomIndices = new int[strings.length];\n for (int i = 0; i < strings.length; i++) {\n randomIndices[i] = i;\n }\n\n StdRandom.shuffle(randomIndices);\n\n StdOut.println(\"Randomly deleting keys\");\n for (int i = 0; i < randomIndices.length; i++) {\n String key = priorityQueue.keyOf(randomIndices[i]);\n priorityQueue.delete(randomIndices[i]);\n StdOut.println(randomIndices[i] + \" \" + key);\n }\n }\n}\n", "support_files": [], "metadata": {"number": "2.4.34", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Creative Problem", "code_execution": false}} {"question": "Sampling from a discrete probability distribution. Write a class Sample with a constructor that takes an array p[] of double values as argument and supports the following two operations: random()—return an index i with probability p[i]/T (where T is the sum of the numbers in p[])—and change(i, v)—change the value of p[i] to v. Hint: Use a complete binary tree where each node has implied weight p[i]. Store in each node the cumulative weight of all the nodes in its subtree. To generate a random index, pick a random number between 0 and T and use the cumulative weights to determine which branch of the subtree to explore. When updating p[i], change all of the weights of the nodes on the path from the root to i. Avoid explicit pointers, as we do for heaps.", "answer": "package chapter2.section4;\n\nimport edu.princeton.cs.algs4.StdOut;\nimport edu.princeton.cs.algs4.StdRandom;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * Created by Rene Argento on 27/03/17.\n */\n// Thanks to dragon-dreamer (https://github.com/dragon-dreamer) for fixing the random() method.\n// https://github.com/reneargento/algorithms-sedgewick-wayne/issues/116\npublic class Sample {\n\n private class Node {\n double weight;\n double cumulativeWeight;\n\n public Node(double weight) {\n this.weight = weight;\n }\n }\n\n private Node[] nodes;\n private double sum = 0;\n\n public Sample(double[] probabilities) {\n nodes = new Node[probabilities.length + 1];\n\n for (int i = 1; i <= probabilities.length; i++) {\n double weight = probabilities[i - 1];\n nodes[i] = new Node(weight);\n sum += weight;\n }\n computeCumulativeWeights();\n }\n\n private void computeCumulativeWeights() {\n for (int i = nodes.length - 1; i >= 2; i--) {\n nodes[i / 2].cumulativeWeight += nodes[i].cumulativeWeight + nodes[i].weight;\n }\n }\n\n public int random() {\n double randomValue = StdRandom.uniform(0, sum);\n int index = 1;\n\n while (randomValue < nodes[index].cumulativeWeight) {\n index *= 2;\n double leftSubtreeWeight = nodes[index].cumulativeWeight + nodes[index].weight;\n\n if (randomValue >= leftSubtreeWeight) {\n randomValue -= leftSubtreeWeight;\n index++;\n }\n }\n return index - 1;\n }\n\n public void change(int index, double value) {\n index++;\n double difference = value - nodes[index].weight;\n nodes[index].weight = value;\n\n sum += difference;\n updateCumulativeWeights(index / 2, difference);\n }\n\n private void updateCumulativeWeights(int index, double difference) {\n while (index >= 1) {\n nodes[index].cumulativeWeight += difference;\n index /= 2;\n }\n }\n\n public static void main(String[] args) {\n double[] weights = { 5, 1, 3, 4, 2, 20 };\n Sample sampling = new Sample(weights);\n\n sampling.change(5, 5);\n\n Map result = new HashMap<>();\n for (int i = 0; i < 20000; i++) {\n int index = sampling.random();\n result.put(index, result.getOrDefault(index, 0) + 1);\n }\n\n for (Map.Entry entry : result.entrySet()) {\n StdOut.println(\"Key = \" + entry.getKey() +\n \" (value = \" + weights[entry.getKey()] +\n \") count = \" + entry.getValue());\n }\n }\n}\n", "support_files": [], "metadata": {"number": "2.4.35", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Creative Problem", "code_execution": false}} {"question": "Consider the following implementation of the compareTo() method for String. How does the third line help with efficiency?\npublic int compareTo(String that) \n{\n if (this == that) return 0; // this line\n int n = Math.min(this.length(), that.length());\n for (int i = 0; i < n; i++)\n {\n if (this.charAt(i) < that.charAt(i)) return -1;\n else if (this.charAt(i) > that.charAt(i)) return +1;\n }\n return this.length() - that.length(); \n}", "answer": "2.5.1\n\nThe third line helps with efficiency by checking if the two objects being compared are the same (when both references point to the same object). This verification helps to avoid iterating through all characters on both Strings in the case that both objects are the same.\n", "support_files": [], "metadata": {"number": "2.5.1", "chapter": 2, "chapter_title": "Sorting", "section": 2.5, "section_title": "Applications", "type": "Exercise", "code_execution": false}} {"question": "Write a program that reads a list of words from standard input and prints all two-word compound words in the list. For example, if after, thought, and afterthought are in the list, then afterthought is a compound word.", "answer": "package chapter2.section5;\n\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.*;\n\n/**\n * Created by Rene Argento on 09/04/17.\n */\n// Thanks to Vivek Bhojawala (https://github.com/VBhojawala) for suggesting a simpler code to solve this exercise.\n// https://github.com/reneargento/algorithms-sedgewick-wayne/issues/15\npublic class Exercise2 {\n\n public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n ArrayList wordList = new ArrayList<>();\n\n /**\n * Testcase\n *\n begin\n end\n test\n afterthought\n Brazil\n thought\n after\n beginend\n abc\n */\n\n // Expected:\n // afterthought\n // beginend\n while (scanner.hasNext()) {\n wordList.add(scanner.next());\n }\n\n Exercise2 exercise2 = new Exercise2();\n List compoundWords = exercise2.getCompoundWords(wordList);\n\n if (compoundWords.size() > 0) {\n StdOut.println(\"Compound words:\");\n\n for (String compoundWord : compoundWords) {\n StdOut.println(compoundWord);\n }\n }\n }\n\n // O(n^2)\n private List getCompoundWords(ArrayList wordList) {\n Collections.sort(wordList);\n Set wordsSet = new HashSet<>(wordList);\n\n List compoundWords = new ArrayList<>();\n\n for (int i = 0; i < wordList.size(); i++) {\n for (int j = i + 1; j < wordList.size(); j++) {\n if (wordList.get(j).startsWith(wordList.get(i))) {\n\n String restOfTheWord = wordList.get(j).substring(wordList.get(i).length());\n if (wordsSet.contains(restOfTheWord)) {\n compoundWords.add(wordList.get(j));\n }\n } else {\n break;\n }\n }\n }\n return compoundWords;\n }\n}\n", "support_files": [], "metadata": {"number": "2.5.2", "chapter": 2, "chapter_title": "Sorting", "section": 2.5, "section_title": "Applications", "type": "Exercise", "code_execution": false}} {"question": "Criticize the following implementation of a class intended to represent account balances. Why is compareTo() a flawed implementation of the Comparable interface?\npublic class Balance implements Comparable \n{\n ...\n private double amount;\n public int compareTo(Balance that)\n {\n if (this.amount < that.amount - 0.005) return -1;\n if (this.amount > that.amount + 0.005) return +1;\n return 0;\n }\n ... \n}\nDescribe a way to fix this problem.", "answer": "2.5.3\n\nThe compareTo() is a flawed implementation of the Comparable interface because it violates the Comparable contract.\nThe contract says that if x.compareTo(y) == 0 then the sign of x.compareTo(z) must be equal to the sign of y.compareTo(z), for all z.\nIn the implementation described in the exercise, if x = 0.001, y = 0.005 and z = 0.007, the rule will be violated:\nx.compareTo(y) will be equal to 0, x.compareTo(z) will have a negative sign and y.compareTo(z) will be equal to zero.\n\nIn other words, it is possible that x.compareTo(y) and y.compareTo(z) are both 0, but x.compareTo(z) is negative (or positive).\n\nAnother issue is that floating point numbers cannot be represented with exact precision in binary with java's double primitive data type.\nCritical information such as account balances should be stored in BigDecimal objects instead.\nThis will also allow direct comparison between both values to work correctly:\n\npublic class Balance implements Comparable {\n ...\n private BigDecimal amount;\n public int compareTo(Balance that) {\n return this.amount.compareTo(that.amount);\n }\n @Override\n public boolean equals(Object object) {\n if (object instanceof Balance) {\n return this.amount.compareTo(((Balance) object).amount) == 0;\n }\n return false;\n }\n ...\n}\n\nFor the BigDecimal class we also have to override the equals method to guarantee that it is consistent with compareTo().\nThis ensures that values with the same amount but different scales (such as 1.0 and 1.00) are considered equivalent, adhering to the Comparable contract.\n\nThanks to dragon-dreamer (https://github.com/dragon-dreamer) for showing that using double values is not the best approach to represent the balance amount.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/117\n", "support_files": [], "metadata": {"number": "2.5.3", "chapter": 2, "chapter_title": "Sorting", "section": 2.5, "section_title": "Applications", "type": "Exercise", "code_execution": false}} {"question": "Implement a method String[] dedup(String[] a) that returns the objects in a[] in sorted order, with duplicates removed.", "answer": "package chapter2.section5;\n\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\n/**\n * Created by Rene Argento on 09/04/17.\n */\npublic class Exercise4 {\n\n public static void main(String[] args) {\n String[] input = {\"Algorithms\", \"Sedgewick\", \"Wayne\", \"Argento\", \"Djikstra\", \"Wayne\", \"Argento\", \"Prim\"};\n\n Exercise4 exercise4 = new Exercise4();\n String[] dedupStrings = exercise4.dedup(input);\n\n StdOut.println(\"Strings:\");\n for (String string : dedupStrings) {\n StdOut.println(string);\n }\n\n StdOut.println();\n StdOut.println(\"Expected: \\n\" +\n \"Algorithms\\n\" +\n \"Argento\\n\" +\n \"Djikstra\\n\" +\n \"Prim\\n\" +\n \"Sedgewick\\n\" +\n \"Wayne\");\n }\n\n private String[] dedup(String[] strings) {\n if (strings == null || strings.length == 0) {\n return new String[0];\n }\n\n Arrays.sort(strings);\n\n List dedupStringList = new ArrayList<>();\n\n String currentString = strings[0];\n dedupStringList.add(strings[0]);\n\n for (int i = 1; i < strings.length; i++) {\n if (strings[i].equals(currentString)) {\n continue;\n } else {\n currentString = strings[i];\n }\n\n dedupStringList.add(strings[i]);\n }\n\n String[] dedupStringArray = new String[dedupStringList.size()];\n for (int i = 0; i < dedupStringArray.length; i++) {\n dedupStringArray[i] = dedupStringList.get(i);\n }\n\n return dedupStringArray;\n }\n}\n", "support_files": [], "metadata": {"number": "2.5.4", "chapter": 2, "chapter_title": "Sorting", "section": 2.5, "section_title": "Applications", "type": "Exercise", "code_execution": false}} {"question": "Explain why selection sort is not stable.", "answer": "2.5.5\n\nSelection sort is not stable because it exchanges nonadjacent elements.\nOn the example below, the first B gets swapped to the right of the second B.\n\ni min 0 1 2\n0 2 B1 B2 A\n1 1 A B2 B1\n2 2 A B2 B1\n A B2 B1\n", "support_files": [], "metadata": {"number": "2.5.5", "chapter": 2, "chapter_title": "Sorting", "section": 2.5, "section_title": "Applications", "type": "Exercise", "code_execution": false}} {"question": "Implement a recursive version of select().", "answer": "package chapter2.section5;\n\nimport edu.princeton.cs.algs4.StdOut;\nimport edu.princeton.cs.algs4.StdRandom;\nimport util.ArrayUtil;\n\n/**\n * Created by Rene Argento on 09/04/17.\n */\n// Thanks to ckwastra (https://github.com/ckwastra) for reporting a bug in recursiveSelect().\n// https://github.com/reneargento/algorithms-sedgewick-wayne/issues/265\n@SuppressWarnings(\"unchecked\")\npublic class Exercise6 {\n\n public static void main(String[] args) {\n Comparable[] array = { 1, 9, 2, 8, 3, 7, 4, 6, 5, 0 };\n\n Exercise6 exercise6 = new Exercise6();\n Comparable selectedItem1 = exercise6.recursiveSelect(array, 4);\n Comparable selectedItem2 = exercise6.recursiveSelect(array, 1);\n Comparable selectedItem3 = exercise6.recursiveSelect(array, 0);\n Comparable selectedItem4 = exercise6.recursiveSelect(array, 9);\n\n StdOut.println(\"Element at index 4: \" + selectedItem1 + \" Expected: 4\");\n StdOut.println(\"Element at index 1: \" + selectedItem2 + \" Expected: 1\");\n StdOut.println(\"Element at index 0: \" + selectedItem3 + \" Expected: 0\");\n StdOut.println(\"Element at index 9: \" + selectedItem4 + \" Expected: 9\");\n }\n\n private Comparable recursiveSelect(Comparable[] array, int index) {\n if (index >= array.length) {\n throw new IllegalArgumentException(\"Index must be smaller than array size\");\n }\n StdRandom.shuffle(array);\n return recursiveSelect(array, index, 0, array.length - 1);\n }\n\n private Comparable recursiveSelect(Comparable[] array, int index, int low, int high) {\n if (low == high) {\n return array[low];\n }\n\n int pivotIndex = partition(array, low, high);\n if (pivotIndex == index) {\n return array[index];\n } else {\n if (pivotIndex < index) {\n return recursiveSelect(array, index, pivotIndex + 1, high);\n } else {\n return recursiveSelect(array, index, low, pivotIndex - 1);\n }\n }\n }\n\n private int partition(Comparable[] array, int low, int high) {\n Comparable pivot = array[low];\n int i = low;\n int j = high + 1;\n\n while (true) {\n while (ArrayUtil.less(array[++i], pivot)) {\n if (i == high) {\n break;\n }\n }\n\n while (ArrayUtil.more(array[--j], pivot)) {\n if (j == low) {\n break;\n }\n }\n\n if (i >= j) {\n break;\n }\n ArrayUtil.exchange(array, i, j);\n }\n\n ArrayUtil.exchange(array, low, j);\n return j;\n }\n}\n", "support_files": [], "metadata": {"number": "2.5.6", "chapter": 2, "chapter_title": "Sorting", "section": 2.5, "section_title": "Applications", "type": "Exercise", "code_execution": false}} {"question": "About how many compares are required, on the average, to find the smallest of N items using select()?", "answer": "2.5.7\n\nOn the average, to find the smallest of N items using select(), it is required 2N + 2 * lnN + (2N - 2) * ln(N / (N - 1)) compares.\nThis follows from proposition U in the book that says that the average number of compares to find the kth item in a shuffled array is ~2N + 2k * ln(N / k) + 2(N - k) * ln(N / (N - k)) and replacing k for 1.\n\nThanks to ckwastra (https://github.com/ckwastra) for suggesting a fix to the compare formula.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/266\n", "support_files": [], "metadata": {"number": "2.5.7", "chapter": 2, "chapter_title": "Sorting", "section": 2.5, "section_title": "Applications", "type": "Exercise", "code_execution": false}} {"question": "Write a program Frequency that reads strings from standard input and prints the number of times each string occurs, in descending order of frequency.", "answer": "package chapter2.section5;\n\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.*;\n\n/**\n * Created by Rene Argento on 09/04/17.\n */\npublic class Exercise8 {\n\n private class StringFrequency implements Comparable{\n String string;\n int frequency;\n\n StringFrequency(String string, int frequency) {\n this.string = string;\n this.frequency = frequency;\n }\n\n @Override\n public int compareTo(StringFrequency that) {\n if (this.frequency > that.frequency) {\n return -1;\n } else if (this.frequency < that.frequency) {\n return 1;\n } else {\n return 0;\n }\n }\n }\n\n public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n List stringList = new ArrayList<>();\n\n /**\n * Testcase\n *\n test\n test\n begin\n begin\n test\n begin\n abc\n abc\n test\n end\n */\n while (scanner.hasNext()) {\n stringList.add(scanner.next());\n }\n\n Exercise8 exercise8 = new Exercise8();\n StringFrequency[] frequencies = exercise8.frequency2(stringList);\n for (StringFrequency frequency : frequencies) {\n StdOut.println(frequency.string + \" \" + frequency.frequency + \" occurrence(s)\");\n }\n\n StdOut.println();\n StdOut.println(\"Expected: \\n\" +\n \"test 4 occurrence(s)\\n\" +\n \"begin 3 occurrence(s)\\n\" +\n \"abc 2 occurrence(s)\\n\" +\n \"end 1 occurrence(s)\");\n }\n\n private StringFrequency[] frequency(List strings) {\n Map occurrenciesMap = new HashMap<>();\n\n for (String string : strings) {\n int frequency = 0;\n\n if (occurrenciesMap.containsKey(string)) {\n frequency = occurrenciesMap.get(string);\n }\n\n frequency++;\n occurrenciesMap.put(string, frequency);\n }\n\n StringFrequency[] stringFrequencies = new StringFrequency[occurrenciesMap.size()];\n int stringFrequenciesIndex = 0;\n\n for (String key : occurrenciesMap.keySet()) {\n int frequency = occurrenciesMap.get(key);\n\n StringFrequency stringFrequency = new StringFrequency(key, frequency);\n stringFrequencies[stringFrequenciesIndex++] = stringFrequency;\n }\n\n Arrays.sort(stringFrequencies);\n return stringFrequencies;\n }\n\n //Optimized for space - no need to use a HashMap\n //Based on http://algs4.cs.princeton.edu/25applications/Frequency.java.html\n private StringFrequency[] frequency2(List strings) {\n\n StringFrequency[] stringFrequencies = new StringFrequency[strings.size()];\n int stringFrequenciesIndex = 0;\n\n Collections.sort(strings);\n String currentString = strings.get(0);\n int frequency = 1;\n\n for (int i = 1; i < strings.size(); i++) {\n if (!currentString.equals(strings.get(i))) {\n stringFrequencies[stringFrequenciesIndex++] = new StringFrequency(currentString, frequency);\n currentString = strings.get(i);\n frequency = 1;\n } else {\n frequency++;\n }\n }\n\n stringFrequencies[stringFrequenciesIndex++] = new StringFrequency(currentString, frequency);\n\n Arrays.sort(stringFrequencies, 0, stringFrequenciesIndex);\n StringFrequency[] stringFrequenciesOutput = new StringFrequency[stringFrequenciesIndex];\n System.arraycopy(stringFrequencies, 0, stringFrequenciesOutput, 0, stringFrequenciesIndex);\n\n return stringFrequenciesOutput;\n }\n}\n", "support_files": [], "metadata": {"number": "2.5.8", "chapter": 2, "chapter_title": "Sorting", "section": 2.5, "section_title": "Applications", "type": "Exercise", "code_execution": false}} {"question": "Develop a data type that allows you to write a client that can sort stock-volume records such as the following by volume:\n\n```text\n1-Oct-28 3500000\n2-Oct-28 3850000\n3-Oct-28 4060000\n```\n\nEach input line contains a date and a volume; the natural order of the data type should be by volume.", "answer": "package chapter2.section5;\n\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.Arrays;\n\n/**\n * Created by Rene Argento on 09/04/17.\n */\npublic class Exercise9 {\n\n class VolumesPerDay implements Comparable{\n private String date;\n private long volume;\n\n VolumesPerDay(String date, long volume) {\n this.date = date;\n this.volume = volume;\n }\n\n @Override\n public int compareTo(VolumesPerDay that) {\n if (this.volume < that.volume) {\n return -1;\n } else if (this.volume > that.volume) {\n return 1;\n } else {\n return 0;\n }\n }\n\n @Override\n public String toString() {\n return date + \" \" + volume;\n }\n }\n\n public static void main(String[] args) {\n Exercise9 exercise9 = new Exercise9();\n VolumesPerDay volumesPerDay1 = exercise9.new VolumesPerDay(\"1-Oct-28\", 2775559936L);\n VolumesPerDay volumesPerDay2 = exercise9.new VolumesPerDay(\"2-Oct-28\", 500);\n VolumesPerDay volumesPerDay3 = exercise9.new VolumesPerDay(\"3-Oct-28\", 1000);\n\n VolumesPerDay[] volumesPerDays = new VolumesPerDay[3];\n volumesPerDays[0] = volumesPerDay1;\n volumesPerDays[1] = volumesPerDay2;\n volumesPerDays[2] = volumesPerDay3;\n\n Arrays.sort(volumesPerDays);\n\n for (VolumesPerDay volumesPerDay : volumesPerDays) {\n StdOut.println(volumesPerDay);\n }\n\n StdOut.println(\"\\nExpected:\\n\" +\n \"2-Oct-28 500\\n\" +\n \"3-Oct-28 1000\\n\" +\n \"1-Oct-28 2775559936\");\n }\n}\n", "support_files": [], "metadata": {"number": "2.5.9", "chapter": 2, "chapter_title": "Sorting", "section": 2.5, "section_title": "Applications", "type": "Exercise", "code_execution": false}} {"question": "Create a data type Version that represents a software version number, such as 115.1.1, 115.10.1, 115.10.2. Implement the Comparable interface so that 115.1.1 is less than 115.10.1, and so forth.", "answer": "package chapter2.section5;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 09/04/17.\n */\npublic class Exercise10 {\n\n class Version implements Comparable{\n\n private String version;\n\n Version(String version) {\n String[] versionSplit = version.split(\"\\\\.\");\n if (versionSplit.length < 3) {\n throw new IllegalArgumentException(\"Incorrect version format. A version requires 3 parts such as 115.10.1\");\n }\n\n this.version = version;\n }\n\n @Override\n public int compareTo(Version that) {\n String[] splitVersion = version.split(\"\\\\.\");\n String[] otherSplitVersion = that.version.split(\"\\\\.\");\n\n if (Integer.parseInt(splitVersion[0]) < Integer.parseInt(otherSplitVersion[0])) {\n return -1;\n } else if (Integer.parseInt(splitVersion[0]) > Integer.parseInt(otherSplitVersion[0])) {\n return 1;\n } else if (Integer.parseInt(splitVersion[1]) < Integer.parseInt(otherSplitVersion[1])) {\n return -1;\n } else if (Integer.parseInt(splitVersion[1]) > Integer.parseInt(otherSplitVersion[1])) {\n return 1;\n } else if (Integer.parseInt(splitVersion[2]) < Integer.parseInt(otherSplitVersion[2])) {\n return -1;\n } else if (Integer.parseInt(splitVersion[2]) > Integer.parseInt(otherSplitVersion[2])) {\n return 1;\n } else {\n return 0;\n }\n }\n\n @Override\n public String toString() {\n return version;\n }\n }\n\n public static void main(String[] args) {\n Exercise10 exercise10 = new Exercise10();\n Version version1 = exercise10.new Version(\"115.1.1\");\n Version version2 = exercise10.new Version(\"115.10.1\");\n Version version3 = exercise10.new Version(\"115.10.2\");\n\n if (version1.compareTo(version2) < 0) {\n StdOut.println(version1 + \" is less than \" + version2 + \" - Correct!\");\n } else {\n StdOut.println(version1 + \" is more than \" + version2 + \" - Wrong!\");\n }\n StdOut.println(\"Expected: Correct!\\n\");\n\n if (version2.compareTo(version3) < 0) {\n StdOut.println(version2 + \" is less than \" + version3 + \" - Correct!\");\n } else {\n StdOut.println(version2 + \" is more than \" + version3 + \" - Wrong!\");\n }\n StdOut.println(\"Expected: Correct!\");\n }\n\n}\n", "support_files": [], "metadata": {"number": "2.5.10", "chapter": 2, "chapter_title": "Sorting", "section": 2.5, "section_title": "Applications", "type": "Exercise", "code_execution": false}} {"question": "Load balancing. Write a program LPT.java that takes an integer M as a command-line argument, reads job names and processing times from standard input and prints a schedule assigning the jobs to M processors that approximately minimizes the time when the last job completes using the longest processing time first rule, as described on page 349.", "answer": "package chapter2.section5;\n\nimport edu.princeton.cs.algs4.StdIn;\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.PriorityQueue;\n\n/**\n * Created by Rene Argento on 10/04/17.\n */\n//The resulting solution is guaranteed to be within 33% of the best possible (actually 4/3 - 1/(3N)).\npublic class Exercise13_LoadBalancing {\n\n private class Job implements Comparable {\n\n private String name;\n private int processingTime;\n\n Job(String name, int processingTime) {\n this.name = name;\n this.processingTime = processingTime;\n }\n\n @Override\n //Longest processing time first rule\n public int compareTo(Job that) {\n if (this.processingTime > that.processingTime) {\n return -1;\n } else if (this.processingTime < that.processingTime) {\n return 1;\n } else {\n return 0;\n }\n }\n\n @Override\n public String toString() {\n return name + \" \" + processingTime;\n }\n }\n\n private class Processor implements Comparable {\n private String name;\n private List jobsAssigned;\n private int sumOfJobsAssignedProcessingTime;\n\n Processor(String name) {\n this.name = name;\n this.sumOfJobsAssignedProcessingTime = 0;\n jobsAssigned = new ArrayList<>();\n }\n\n void assignJob(Job job) {\n jobsAssigned.add(job);\n }\n\n @Override\n public int compareTo(Processor that) {\n if (this.sumOfJobsAssignedProcessingTime < that.sumOfJobsAssignedProcessingTime) {\n return -1;\n } else if (this.sumOfJobsAssignedProcessingTime > that.sumOfJobsAssignedProcessingTime) {\n return 1;\n } else {\n return 0;\n }\n }\n\n @Override\n public String toString() {\n return name;\n }\n }\n\n public static void main(String[] args) {\n int numberOfProcessors = Integer.parseInt(args[0]); //testcase: numberOfProcessors = 3\n\n new Exercise13_LoadBalancing().lpt(numberOfProcessors);\n }\n\n private void lpt(int numberOfProcessors) {\n\n /**\n * Test case\n *\n * JobA 100\n * JobB 1\n * JobC 999\n * JobD 1000\n * JobE 0\n * JobF 999999999\n */\n String[] input = StdIn.readAllLines();\n Job[] jobs = new Job[input.length];\n int jobsIndex = 0;\n\n for (String jobString : input) {\n String[] jobDescription = jobString.split(\" \");\n String name = jobDescription[0];\n int processingTime = Integer.parseInt(jobDescription[1]);\n\n jobs[jobsIndex++] = new Job(name, processingTime);\n }\n\n Arrays.sort(jobs);\n\n PriorityQueue heap = new PriorityQueue<>();\n for (int i = 0; i < numberOfProcessors; i++) {\n Processor processor = new Processor(\"Processor \" + i);\n heap.add(processor);\n }\n\n loadBalanceAndPrintSchedule(jobs, heap);\n\n StdOut.println();\n StdOut.println(\"Expected:\");\n StdOut.println(\"JobF assigned to Processor 0\\n\" +\n \"JobD assigned to Processor 2\\n\" +\n \"JobC assigned to Processor 1\\n\" +\n \"JobA assigned to Processor 1\\n\" +\n \"JobB assigned to Processor 2\\n\" +\n \"JobE assigned to Processor 2\");\n }\n\n private void loadBalanceAndPrintSchedule(Job[] jobs, PriorityQueue heap) {\n for (int i = 0; i < jobs.length; i++) {\n Processor nextProcessorAvailable = heap.remove();\n // Assign job to the next available processor\n nextProcessorAvailable.assignJob(jobs[i]);\n nextProcessorAvailable.sumOfJobsAssignedProcessingTime += jobs[i].processingTime;\n\n StdOut.println(jobs[i].name + \" assigned to \" + nextProcessorAvailable.name);\n\n heap.add(nextProcessorAvailable);\n }\n }\n}\n", "support_files": [], "metadata": {"number": "2.5.13", "chapter": 2, "chapter_title": "Sorting", "section": 2.5, "section_title": "Applications", "type": "Creative Problem", "code_execution": false}} {"question": "Sort by reverse domain. Write a data type Domain that represents domain names, including an appropriate compareTo() method where the natural order is in order of the reverse domain name. For example, the reverse domain of cs.princeton.edu is edu.princeton.cs. This is useful for web log analysis. Hint: Use s.split(\"\\\\.\") to split the string s into tokens, delimited by dots. Write a client that reads domain names from standard input and prints the reverse domains in sorted order.", "answer": "package chapter2.section5;\n\nimport edu.princeton.cs.algs4.StdIn;\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.Arrays;\n\n/**\n * Created by Rene Argento on 10/04/17.\n */\npublic class Exercise14_SortByReverseDomain {\n\n private class Domain implements Comparable{\n\n String domainName;\n String reverseDomainName;\n\n Domain(String domainName) {\n this.domainName = domainName;\n\n String[] reverseDomain = domainName.split(\"\\\\.\");\n StringBuilder reverseDomainConcatenation = new StringBuilder();\n for (int i = reverseDomain.length - 1; i >= 0; i--) {\n reverseDomainConcatenation.append(reverseDomain[i]);\n\n if (i != 0) {\n reverseDomainConcatenation.append(\".\");\n }\n }\n this.reverseDomainName = reverseDomainConcatenation.toString();\n }\n\n @Override\n public int compareTo(Domain that) {\n return this.reverseDomainName.compareTo(that.reverseDomainName);\n }\n }\n\n public static void main(String[] args) {\n Exercise14_SortByReverseDomain sortByReverseDomain = new Exercise14_SortByReverseDomain();\n\n /**\n * Test case\n *\n * cs.princeton.edu\n * www.google.com\n * www.rene.argento\n * www.somewebsite.gov\n * cs.harvard.edu\n */\n String[] domainNames = StdIn.readAllLines();\n Domain[] domains = new Domain[domainNames.length];\n\n for (int i = 0; i < domainNames.length; i++) {\n Domain domain = sortByReverseDomain.new Domain(domainNames[i]);\n domains[i] = domain;\n }\n\n Arrays.sort(domains);\n\n for (Domain domain : domains) {\n StdOut.println(domain.reverseDomainName);\n }\n\n StdOut.println();\n StdOut.println(\"Expected:\");\n StdOut.println(\"argento.rene.www\\n\" +\n \"com.google.www\\n\" +\n \"edu.harvard.cs\\n\" +\n \"edu.princeton.cs\\n\" +\n \"gov.somewebsite.www\");\n }\n}\n", "support_files": [], "metadata": {"number": "2.5.14", "chapter": 2, "chapter_title": "Sorting", "section": 2.5, "section_title": "Applications", "type": "Creative Problem", "code_execution": false}} {"question": "Spam campaign. To initiate an illegal spam campaign, you have a list of email addresses from various domains (the part of the email address that follows the @ symbol). To better forge the return addresses, you want to send the email from another user at the same domain. For example, you might want to forge an email from wayne@princeton.edu to rs@princeton.edu. How would you process the email list to make this an efficient task?", "answer": "2.5.15 - Spam campaign\n\nI would sort the email list by the reverse domain.\nThen I would choose emails among the same domain to serve as sender and receiver and repeat this process for each domain.\n", "support_files": [], "metadata": {"number": "2.5.15", "chapter": 2, "chapter_title": "Sorting", "section": 2.5, "section_title": "Applications", "type": "Creative Problem", "code_execution": false}} {"question": "Idle time. Suppose that a parallel machine processes N jobs. Write a program that, given the list of job start and finish times, finds the largest interval where the machine is idle and the largest interval where the machine is not idle.", "answer": "package chapter2.section5;\n\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.Arrays;\n\n/**\n * Created by Rene Argento on 12/04/17.\n */\npublic class Exercise20_IdleTime {\n\n private class Job implements Comparable {\n\n private int startTime;\n private int endTime;\n\n Job(int startTime, int endTime) {\n this.startTime = startTime;\n this.endTime = endTime;\n }\n\n @Override\n public int compareTo(Job that) {\n if (this.startTime < that.startTime) {\n return -1;\n } else if (this.startTime > that.startTime) {\n return 1;\n } else {\n if (this.endTime < that.endTime) {\n return -1;\n } else if (this.endTime > that.endTime) {\n return 1;\n }\n }\n\n return 0;\n }\n }\n\n public static void main(String[] args) {\n\n Exercise20_IdleTime idleTime = new Exercise20_IdleTime();\n\n Job job1 = idleTime.new Job(5, 6);\n Job job2 = idleTime.new Job(12, 14);\n Job job3 = idleTime.new Job(1, 3);\n Job job4 = idleTime.new Job(9, 12);\n Job job5 = idleTime.new Job(15, 16);\n\n Job[] jobs = {job1, job2, job3, job4, job5};\n\n int[] intervals = idleTime.getAsynchronousJobsIntervals(jobs);\n\n StdOut.println(\"Largest idle interval: \" + intervals[0] + \" to \" + intervals[1]);\n StdOut.println(\"Largest non-idle interval: \" + intervals[2] + \" to \" + intervals[3]);\n\n StdOut.println(\"\\nExpected\");\n StdOut.println(\"Largest idle interval: 6 to 9\");\n StdOut.println(\"Largest non-idle interval: 9 to 14\");\n\n Job job6 = idleTime.new Job(1, 10);\n Job job7 = idleTime.new Job(6, 10);\n Job job8 = idleTime.new Job(2, 4);\n Job job9 = idleTime.new Job(5, 12);\n Job job10 = idleTime.new Job(15, 17);\n Job job11 = idleTime.new Job(16, 20);\n\n Job[] jobs2 = {job6, job7, job8, job9, job10, job11};\n\n int[] intervals2 = idleTime.getAsynchronousJobsIntervals(jobs2);\n\n StdOut.println(\"\\nLargest idle interval: \" + intervals2[0] + \" to \" + intervals2[1]);\n StdOut.println(\"Largest non-idle interval: \" + intervals2[2] + \" to \" + intervals2[3]);\n\n StdOut.println(\"\\nExpected\");\n StdOut.println(\"Largest idle interval: 12 to 15\");\n StdOut.println(\"Largest non-idle interval: 1 to 12\");\n }\n\n private int[] getAsynchronousJobsIntervals(Job[] jobs) {\n\n if (jobs == null || jobs.length == 0) {\n return new int[]{0, 0, 0, 0};\n }\n\n int currentIntervalStartIndex = 0;\n\n int largestIdleTimeStartIndex = 0;\n int largestIdleTimeEndIndex = 0;\n int largestBusyTimeStartIndex = 0;\n int largestBusyTimeEndIndex = 0;\n\n Arrays.sort(jobs);\n\n int currentMaxEndTime = jobs[0].endTime;\n int currentMaxEndTimeIndex = 0;\n\n int maxIdleTime = jobs[0].startTime;\n\n for (int i = 0; i < jobs.length; i++) {\n\n if (i != 0 && jobs[i].startTime > currentMaxEndTime) {\n\n //A new interval is beginning\n if (jobs[i].startTime - currentMaxEndTime > maxIdleTime) {\n largestIdleTimeEndIndex = i;\n largestIdleTimeStartIndex = currentMaxEndTimeIndex;\n\n maxIdleTime = jobs[largestIdleTimeEndIndex].startTime - jobs[largestIdleTimeStartIndex].endTime;\n }\n\n currentIntervalStartIndex = i;\n }\n\n if (jobs[i].endTime - jobs[currentIntervalStartIndex].startTime >\n jobs[largestBusyTimeEndIndex].endTime - jobs[largestBusyTimeStartIndex].startTime) {\n largestBusyTimeStartIndex = currentIntervalStartIndex;\n largestBusyTimeEndIndex = i;\n }\n\n if (jobs[i].endTime > currentMaxEndTime) {\n currentMaxEndTime = jobs[i].endTime;\n currentMaxEndTimeIndex = i;\n }\n }\n\n int largestIdleTimeStart = jobs[largestIdleTimeStartIndex].endTime;\n int largestIdleTimeEnd = jobs[largestIdleTimeEndIndex].startTime;\n\n // Edge case - when the largest idle interval is from time 0 to the beginning of the first job\n if (largestIdleTimeStart > largestIdleTimeEnd) {\n largestIdleTimeStart = 0;\n }\n\n int largestBusyTimeStart = jobs[largestBusyTimeStartIndex].startTime;\n int largestBusyTimeEnd = jobs[largestBusyTimeEndIndex].endTime;\n\n return new int[]{largestIdleTimeStart, largestIdleTimeEnd, largestBusyTimeStart, largestBusyTimeEnd};\n }\n\n // Only used for synchronous jobs\n private int[] getSynchronousJobsIntervals(Job[] jobs) {\n\n if (jobs == null || jobs.length == 0) {\n return new int[]{0, 0, 0, 0};\n }\n\n int currentIntervalStartIndex = 0;\n\n int largestIdleTimeStartIndex = 0;\n int largestIdleTimeEndIndex = 0;\n int largestBusyTimeStartIndex = 0;\n int largestBusyTimeEndIndex = 0;\n\n Arrays.sort(jobs);\n\n int maxIdleTime = jobs[0].startTime;\n\n for (int i = 0; i < jobs.length; i++) {\n\n if (i != 0 && jobs[i].startTime > jobs[i - 1].endTime) {\n\n // A new interval is beginning\n if (jobs[i].startTime - jobs[i - 1].endTime > maxIdleTime) {\n largestIdleTimeEndIndex = i;\n largestIdleTimeStartIndex = i-1;\n\n maxIdleTime = jobs[largestIdleTimeEndIndex].startTime - jobs[largestIdleTimeStartIndex].endTime;\n }\n\n currentIntervalStartIndex = i;\n }\n\n if (jobs[i].endTime - jobs[currentIntervalStartIndex].startTime >\n jobs[largestBusyTimeEndIndex].endTime - jobs[largestBusyTimeStartIndex].startTime) {\n largestBusyTimeStartIndex = currentIntervalStartIndex;\n largestBusyTimeEndIndex = i;\n }\n }\n\n int largestIdleTimeStart = jobs[largestIdleTimeStartIndex].endTime;\n int largestIdleTimeEnd = jobs[largestIdleTimeEndIndex].startTime;\n\n // Edge case - when the largest idle interval is from time 0 to the beginning of the first job\n if (largestIdleTimeStart > largestIdleTimeEnd) {\n largestIdleTimeStart = 0;\n }\n\n int largestBusyTimeStart = jobs[largestBusyTimeStartIndex].startTime;\n int largestBusyTimeEnd = jobs[largestBusyTimeEndIndex].endTime;\n\n return new int[]{largestIdleTimeStart, largestIdleTimeEnd, largestBusyTimeStart, largestBusyTimeEnd};\n }\n}\n", "support_files": [], "metadata": {"number": "2.5.20", "chapter": 2, "chapter_title": "Sorting", "section": 2.5, "section_title": "Applications", "type": "Creative Problem", "code_execution": false}} {"question": "Sampling for selection. Investigate the idea of using sampling to improve selection. Hint: Using the median may not always be helpful.", "answer": "2.5.23 - Sampling for selection\n\nSampling improves selection in cases where the element searched is one of the smallest or highest values in the array.\nFor example, when searching for the 2nd smallest element in an array of size 10^9, selecting one of the smallest elements as the pivot in the initial steps will yield better performance than always choosing the median. \nThis can discard 75%+ of the array, improving selection performance.\n", "support_files": [], "metadata": {"number": "2.5.23", "chapter": 2, "chapter_title": "Sorting", "section": 2.5, "section_title": "Applications", "type": "Creative Problem", "code_execution": false}} {"question": "Stable priority queue. Develop a stable priority-queue implementation (which returns duplicate keys in the same order in which they were inserted).", "answer": "package chapter2.section5;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 15/04/17.\n */\n//Based on http://algs4.cs.princeton.edu/25applications/StableMinPQ.java.html\n@SuppressWarnings(\"unchecked\")\npublic class Exercise24_StablePriorityQueue {\n\n public enum Orientation {\n MAX, MIN;\n }\n\n private class PriorityQueueStable> {\n\n private Key[] priorityQueue;\n private int size = 0; // in priorityQueue[1..n] with pq[0] unused\n private Orientation orientation;\n\n private long[] timestamp;\n private int currentTimestamp = 0;\n\n PriorityQueueStable(Orientation orientation) {\n priorityQueue = (Key[]) new Comparable[2];\n timestamp = new long[2];\n this.orientation = orientation;\n }\n\n public boolean isEmpty() {\n return size == 0;\n }\n\n public int size() {\n return size;\n }\n\n public Key peek() {\n return priorityQueue[1];\n }\n\n public void insert(Key key) {\n\n if (size == priorityQueue.length - 1) {\n resize(priorityQueue.length * 2);\n }\n\n size++;\n priorityQueue[size] = key;\n timestamp[size] = ++currentTimestamp;\n\n swim(size);\n }\n\n public Key deleteTop() {\n\n if (size == 0) {\n throw new RuntimeException(\"Priority queue underflow\");\n }\n\n size--;\n\n Key top = priorityQueue[1];\n\n exchange(1, size + 1);\n priorityQueue[size + 1] = null;\n timestamp[size + 1] = 0;\n\n sink(1);\n\n if (size == priorityQueue.length / 4) {\n resize(priorityQueue.length / 2);\n }\n\n return top;\n }\n\n private void swim(int index) {\n while (index / 2 >= 1) {\n if ((orientation == Orientation.MAX && less(index / 2, index))\n || (orientation == Orientation.MIN && more(index / 2, index))) {\n exchange(index / 2, index);\n } else {\n break;\n }\n\n index = index / 2;\n }\n }\n\n private void sink(int index) {\n while (index * 2 <= size) {\n int selectedChildIndex = index * 2;\n\n if (index * 2 + 1 <= size &&\n ((orientation == Orientation.MAX && less(index * 2, index * 2 + 1))\n || (orientation == Orientation.MIN && more(index * 2, index * 2 + 1)))) {\n selectedChildIndex = index * 2 + 1;\n }\n\n if ((orientation == Orientation.MAX && more(selectedChildIndex, index))\n || (orientation == Orientation.MIN && less(selectedChildIndex, index))) {\n exchange(index, selectedChildIndex);\n } else {\n break;\n }\n\n index = selectedChildIndex;\n }\n }\n\n private void resize(int newSize) {\n Key[] newPriorityQueue = (Key[]) new Comparable[newSize];\n System.arraycopy(priorityQueue, 1, newPriorityQueue, 1, size);\n priorityQueue = newPriorityQueue;\n\n long[] newTimestamp = new long[newSize];\n System.arraycopy(timestamp, 1, newTimestamp, 1, size);\n timestamp = newTimestamp;\n }\n\n private boolean less(int key1Index, int key2Index) {\n int compare = priorityQueue[key1Index].compareTo(priorityQueue[key2Index]);\n\n if (compare < 0) {\n return true;\n } else if (compare > 0) {\n return false;\n } else {\n return timestamp[key1Index] < timestamp[key2Index];\n }\n }\n\n private boolean more(int key1Index, int key2Index) {\n int compare = priorityQueue[key1Index].compareTo(priorityQueue[key2Index]);\n\n if (compare > 0) {\n return true;\n } else if (compare < 0) {\n return false;\n } else {\n return timestamp[key1Index] > timestamp[key2Index];\n }\n }\n\n private void exchange(int key1Index, int key2Index) {\n Key tempKey = priorityQueue[key1Index];\n priorityQueue[key1Index] = priorityQueue[key2Index];\n priorityQueue[key2Index] = tempKey;\n\n long tempTimestamp = timestamp[key1Index];\n timestamp[key1Index] = timestamp[key2Index];\n timestamp[key2Index] = tempTimestamp;\n }\n }\n\n private class Tuple implements Comparable {\n\n private String value;\n private int id;\n\n Tuple(String value, int id) {\n this.value = value;\n this.id = id;\n }\n\n @Override\n public int compareTo(Tuple that) {\n return this.value.compareTo(that.value);\n }\n\n @Override\n public String toString() {\n return value + \" \" + id;\n }\n }\n\n public static void main(String[] args) {\n Exercise24_StablePriorityQueue stablePriorityQueue = new Exercise24_StablePriorityQueue();\n PriorityQueueStable priorityQueueStable = stablePriorityQueue.new PriorityQueueStable<>(Orientation.MIN);\n\n // Insert a bunch of strings\n String text = \"it was the best of times it was the worst of times it was the \"\n + \"age of wisdom it was the age of foolishness it was the epoch \"\n + \"belief it was the epoch of incredulity it was the season of light \"\n + \"it was the season of darkness it was the spring of hope it was the \"\n + \"winter of despair\";\n\n String[] strings = text.split(\" \");\n\n for (int i = 0; i < strings.length; i++) {\n priorityQueueStable.insert(stablePriorityQueue.new Tuple(strings[i], i));\n }\n\n // Delete and print each key\n while (!priorityQueueStable.isEmpty()) {\n StdOut.println(priorityQueueStable.deleteTop());\n }\n }\n}\n", "support_files": [], "metadata": {"number": "2.5.24", "chapter": 2, "chapter_title": "Sorting", "section": 2.5, "section_title": "Applications", "type": "Creative Problem", "code_execution": false}} {"question": "Points in the plane. Write three static comparators for the Point2D data type of page 77, one that compares points by their x coordinate, one that compares them by their y coordinate, and one that compares them by their distance from the origin. Write two non-static comparators for the Point2D data type, one that compares them by their distance to a specified point and one that compares them by their polar angle with respect to a specified point.", "answer": "package chapter2.section5;\n\nimport edu.princeton.cs.algs4.StdDraw;\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.Arrays;\nimport java.util.Comparator;\n\n/**\n * Created by Rene Argento on 15/04/17.\n */\npublic class Exercise25_PointsInThePlane {\n\n static class Point2D implements Comparable {\n\n private double x;\n private double y;\n\n Point2D(double x, double y) {\n if (Double.isInfinite(x) || Double.isInfinite(y)) {\n throw new IllegalArgumentException(\"Coordinates must be finite\");\n }\n\n if (Double.isNaN(x) || Double.isNaN(y)) {\n throw new IllegalArgumentException(\"Coordinates cannot be NaN\");\n }\n\n if (x == 0.0) {\n this.x = 0.0; // convert -0.0 to +0.0\n } else {\n this.x = x;\n }\n\n if (y == 0.0) {\n this.y = 0.0; // convert -0.0 to +0.0\n } else {\n this.y = y;\n }\n }\n\n public double x() {\n return x;\n }\n\n public double y() {\n return y;\n }\n\n //Returns the polar radius of this point.\n public double r() {\n return Math.sqrt(x * x + y * y);\n }\n\n //Returns the angle of this point in polar coordinates.\n public double theta() {\n return Math.atan2(y, x);\n }\n\n private double angleTo(Point2D that) {\n double distanceX = that.x - this.x;\n double distanceY = that.y - this.y;\n\n return Math.atan2(distanceY, distanceX);\n }\n\n public double distance(Point2D that) {\n double distanceX = this.x - that.x;\n double distanceY = this.y - that.y;\n\n return Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2));\n }\n\n public void draw() {\n StdDraw.point(x, y);\n }\n\n @Override\n public int compareTo(Point2D that) {\n if (this.y < that.y) {\n return -1;\n }\n if (this.y > that.y) {\n return 1;\n }\n if (this.x < that.x) {\n return -1;\n }\n if (this.x > that.x) {\n return 1;\n }\n return 0;\n }\n\n Comparator distanceFromPointComparator = new Comparator() {\n @Override\n public int compare(Point2D point2D1, Point2D point2D2) {\n double distanceFromThisPoint1 = distance(point2D1);\n double distanceFromThisPoint2 = distance(point2D2);\n\n if (distanceFromThisPoint1 < distanceFromThisPoint2) {\n return -1;\n } else if (distanceFromThisPoint1 > distanceFromThisPoint2) {\n return 1;\n } else {\n return 0;\n }\n }\n };\n\n Comparator polarAngleFromThisPointComparator = new Comparator() {\n @Override\n public int compare(Point2D point2D1, Point2D point2D2) {\n double distanceXPoint1 = point2D1.x - x;\n double distanceYPoint1 = point2D1.y - y;\n double distanceXPoint2 = point2D2.x - x;\n double distanceYPoint2 = point2D2.y - y;\n\n if (distanceYPoint1 >= 0 && distanceYPoint2 < 0) {\n return -1; // point2D1 is above; point2D2 is below\n } else if (distanceYPoint2 >= 0 && distanceYPoint1 < 0) {\n return 1; // point2D1 below; point2D2 above\n } else if (distanceYPoint1 == 0 && distanceYPoint2 == 0) { // 3-collinear and horizontal\n if (distanceXPoint1 >= 0 && distanceXPoint2 < 0) {\n return -1;\n } else if (distanceXPoint2 >= 0 && distanceXPoint1 < 0) {\n return 1;\n } else {\n return 0;\n }\n } else {\n return -counterClockwise(Point2D.this, point2D1, point2D2); // both above or below\n }\n }\n };\n\n //Returns 1 if point1 → point2 → point3 is a counterclockwise turn\n public int counterClockwise(Point2D point1, Point2D point2, Point2D point3) {\n double area2 = (point2.x - point1.x) * (point3.y - point1.y) - (point2.y - point1.y) * (point3.x - point1.x);\n\n if (area2 < 0) {\n return -1;\n } else if (area2 > 0) {\n return 1;\n } else {\n return 0;\n }\n }\n }\n\n private static class XOrder implements Comparator{\n @Override\n public int compare(Point2D point2D1, Point2D point2D2) {\n if (point2D1.x < point2D2.x) {\n return -1;\n } else if (point2D1.x > point2D2.x) {\n return 1;\n } else {\n return 0;\n }\n }\n }\n\n private static class YOrder implements Comparator{\n @Override\n public int compare(Point2D point2D1, Point2D point2D2) {\n if (point2D1.y < point2D2.y) {\n return -1;\n } else if (point2D1.y > point2D2.y) {\n return 1;\n } else {\n return 0;\n }\n }\n }\n\n private static class DistanceFromOriginOrder implements Comparator {\n @Override\n public int compare(Point2D point2D1, Point2D point2D2) {\n double distanceFromOriginPoint2D1 = point2D1.distance(new Point2D(0, 0));\n double distanceFromOriginPoint2D2 = point2D2.distance(new Point2D(0, 0));\n\n if (distanceFromOriginPoint2D1 < distanceFromOriginPoint2D2) {\n return -1;\n } else if (distanceFromOriginPoint2D1 > distanceFromOriginPoint2D2) {\n return 1;\n } else {\n return 0;\n }\n }\n }\n\n public static void main(String[] args) {\n Point2D point2D1 = new Point2D(0.2, 1.3);\n Point2D point2D2 = new Point2D(92.12, 140.82);\n Point2D point2D3 = new Point2D(20, 22.0);\n Point2D point2D4 = new Point2D(30, 0);\n\n Point2D[] points = {point2D1, point2D2, point2D3, point2D4};\n\n //X coordinate order\n StdOut.println(\"Order by X coordinate\");\n Arrays.sort(points, new XOrder());\n\n for (Point2D point2D : points) {\n StdOut.print(point2D.x + \" \");\n }\n\n StdOut.println(\"\\nExpected: 0.2 20.0 30.0 92.12\");\n\n //Y coordinate order\n StdOut.println(\"\\nOrder by Y coordinate\");\n Arrays.sort(points, new YOrder());\n\n for (Point2D point2D : points) {\n StdOut.print(point2D.y + \" \");\n }\n\n StdOut.println(\"\\nExpected: 0.0 1.3 22.0 140.82\");\n\n //Distance from origin order\n StdOut.println(\"\\nOrder by distance from origin\");\n Arrays.sort(points, new DistanceFromOriginOrder());\n\n for (Point2D point2D : points) {\n StdOut.print(point2D.x + \" \");\n }\n\n StdOut.println(\"\\nExpected: 0.2 20.0 30.0 92.12\");\n\n //Distance from specified point\n StdOut.println(\"\\nOrder by distance from specified point\");\n Arrays.sort(points, point2D2.distanceFromPointComparator);\n\n for (Point2D point2D : points) {\n StdOut.print(point2D.x + \" \");\n }\n\n StdOut.println(\"\\nExpected: 92.12 20.0 30.0 0.2\");\n\n //Polar angle distance from specified point\n StdOut.println(\"\\nOrder by polar angle distance from specified point\");\n Arrays.sort(points, point2D2.polarAngleFromThisPointComparator);\n\n for (Point2D point2D : points) {\n StdOut.print(point2D.x + \" \");\n }\n\n StdOut.println(\"\\nExpected: 92.12 0.2 20.0 30.0\");\n }\n}\n", "support_files": [], "metadata": {"number": "2.5.25", "chapter": 2, "chapter_title": "Sorting", "section": 2.5, "section_title": "Applications", "type": "Creative Problem", "code_execution": false}} {"question": "Simple polygon. Given N points in the plane, draw a simple polygon with N points as vertices. Hint: Find the point p with the smallest y coordinate, breaking ties with the smallest x coordinate. Connect the points in increasing order of the polar angle they make with p.", "answer": "Choose the anchor `p` with minimum y-coordinate, breaking ties by x-coordinate. Sort every other point by the polar angle it makes with `p`, then connect the points in that order and finally connect the last point back to `p`.\n\n```java\nPoint2D[] points = readPoints();\nArrays.sort(points, Point2D.Y_ORDER.thenComparing(Point2D.X_ORDER));\nPoint2D p = points[0];\nArrays.sort(points, 1, points.length, p.polarOrder());\n\nfor (int i = 0; i < points.length; i++) {\n Point2D a = points[i];\n Point2D b = points[(i + 1) % points.length];\n a.drawTo(b);\n}\n```\n\nThe sorted polar order around the lowest point gives a non-self-intersecting polygon for distinct points.", "support_files": [], "metadata": {"number": "2.5.26", "chapter": 2, "chapter_title": "Sorting", "section": 2.5, "section_title": "Applications", "type": "Creative Problem", "code_execution": false}} {"question": "Sorting parallel arrays. When sorting parallel arrays, it is useful to have a version of a sorting routine that returns a permutation, say index[], of the indices in sorted order. Add a method indirectSort() to Insertion that takes an array of Comparable objects a[] as argument, but instead of rearranging the entries of a[] returns an integer array index[] so that a[index[0]] through a[index[N-1]] are the items in ascending order.", "answer": "A direct insertion-sort version keeps the input array fixed and sorts an index array instead.\n\n```java\npublic class Insertion {\n public static int[] indirectSort(Comparable[] a) {\n int n = a.length;\n int[] index = new int[n];\n\n for (int i = 0; i < n; i++) {\n index[i] = i;\n }\n\n for (int i = 1; i < n; i++) {\n int currentIndex = index[i];\n int j = i;\n\n while (j > 0 && less(a[currentIndex], a[index[j - 1]])) {\n index[j] = index[j - 1];\n j--;\n }\n index[j] = currentIndex;\n }\n\n return index;\n }\n\n private static boolean less(Comparable v, Comparable w) {\n return v.compareTo(w) < 0;\n }\n}\n```\n\nThe returned array is a permutation of `0..N-1`. For every adjacent pair in the returned order, `a[index[i]] <= a[index[i + 1]]`, and the original array `a[]` is never rearranged.", "support_files": [], "metadata": {"number": "2.5.27", "chapter": 2, "chapter_title": "Sorting", "section": 2.5, "section_title": "Applications", "type": "Creative Problem", "code_execution": false}} {"question": "Sort files by name. Write a program FileSorter that takes the name of a directory as a command-line argument and prints out all of the files in the current directory, sorted by file name. Hint: Use the File data type.", "answer": "package chapter2.section5;\n\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.io.File;\nimport java.util.Arrays;\n\n/**\n * Created by Rene Argento on 16/04/17.\n */\npublic class Exercise28_SortFilesByName {\n\n // Parameter example: [any file path]\n public static void main(String[] args) {\n String directoryPath = args[0];\n String[] sortedFiles = new Exercise28_SortFilesByName().fileSorter(directoryPath);\n\n if (sortedFiles == null) {\n return;\n }\n\n for (String fileName : sortedFiles) {\n StdOut.println(fileName);\n }\n }\n\n private String[] fileSorter(String directoryPath) {\n File directory = new File(directoryPath);\n\n if (!directory.exists()) {\n throw new IllegalArgumentException(directoryPath + \" does not exist\");\n }\n if (!directory.isDirectory()) {\n throw new IllegalArgumentException(directoryPath + \" is not a directory\");\n }\n\n File[] allFiles = directory.listFiles();\n if (allFiles == null || allFiles.length == 0) {\n return null;\n }\n\n String[] fileNames = new String[allFiles.length];\n for (int i = 0; i < fileNames.length; i++) {\n fileNames[i] = allFiles[i].getName();\n }\n\n Arrays.sort(fileNames);\n return fileNames;\n }\n}\n", "support_files": [], "metadata": {"number": "2.5.28", "chapter": 2, "chapter_title": "Sorting", "section": 2.5, "section_title": "Applications", "type": "Creative Problem", "code_execution": false}} {"question": "Sort files by size and date of last modification. Write comparators for the type File to order by increasing/decreasing order of file size, ascending/descending order of file name, and ascending/descending order of last modification date. Use these comparators in a program LS that takes a command-line argument and lists the files in the current directory according to a specified order, e.g., \"-t\" to sort by timestamp. Support multiple flags to break ties. Be sure to use a stable sort.", "answer": "package chapter2.section5;\n\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.io.File;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Comparator;\nimport java.util.List;\n\n/**\n * Created by Rene Argento on 16/04/17.\n */\n// Thanks to ckwastra (https://github.com/ckwastra) for suggesting a way to sort the files only once.\n// https://github.com/reneargento/algorithms-sedgewick-wayne/issues/269\npublic class Exercise29_SortFilesBySizeAndDate {\n\n public static void main(String[] args) {\n Path currentRelativePath = Paths.get(\"\");\n String path = currentRelativePath.toAbsolutePath().toString();\n\n File directory = new File(path);\n\n //Input example: -s -d -n -t\n File[] sortedFiles = new Exercise29_SortFilesBySizeAndDate().readFlagsAndSortFiles(directory, args);\n if (sortedFiles == null) {\n return;\n }\n\n for (File file : sortedFiles) {\n StdOut.println(file);\n }\n }\n\n private static final Comparator NAME_ORDER = Comparator.comparing(File::getName);\n private static final Comparator SIZE_ORDER = Comparator.comparingLong(File::length);\n private static final Comparator TIME_ORDER = Comparator.comparingLong(File::lastModified);\n private static final Comparator NAME_REVERSED_ORDER = NAME_ORDER.reversed();\n private static final Comparator SIZE_REVERSED_ORDER = SIZE_ORDER.reversed();\n private static final Comparator TIME_REVERSED_ORDER = TIME_ORDER.reversed();\n\n private File[] readFlagsAndSortFiles(File directory, String[] flags) {\n File[] filesInCurrentDirectory = directory.listFiles();\n if (filesInCurrentDirectory == null) {\n return null;\n }\n\n List allFiles = new ArrayList<>();\n for (File file : filesInCurrentDirectory) {\n if (!file.isDirectory()) {\n allFiles.add(file);\n }\n }\n\n File[] files = new File[allFiles.size()];\n allFiles.toArray(files);\n\n /**\n * Flags:\n * -s size\n * -t timestamp\n * -n name\n *\n * -sd size decreasing\n * -td timestamp decreasing\n * -nd name decreasing\n *\n * Usage example:\n * -s -td -n\n * First sort by file size in increasing order, then by timestamp in decreasing order and\n * then by file name in increasing order\n */\n switch (flags[0]) {\n // No duplicate file names\n case \"-n\":\n // Sort by file name in increasing order\n Arrays.sort(files, NAME_ORDER);\n break;\n case \"-nd\":\n // Sort by file name in decreasing order\n Arrays.sort(files, NAME_REVERSED_ORDER);\n break;\n default:\n Comparator comparator;\n switch (flags[0]) {\n case \"-t\":\n // Sort by timestamp in increasing order\n comparator = TIME_ORDER;\n break;\n case \"-td\":\n // Sort by timestamp in decreasing order\n comparator = TIME_REVERSED_ORDER;\n break;\n case \"-s\":\n // Sort by file size in increasing order\n comparator = SIZE_ORDER;\n break;\n case \"-sd\":\n // Sort by file size in decreasing order\n comparator = SIZE_REVERSED_ORDER;\n break;\n default:\n throw new IllegalArgumentException(\"Invalid flag \" + flags[0]);\n }\n // Accept up to 3 flags\n int flagsToProcess = Math.min(3, flags.length);\n outer: for (int i = 1; i < flagsToProcess; i++) {\n switch (flags[i]) {\n case \"-n\":\n comparator = comparator.thenComparing(NAME_ORDER);\n break outer;\n case \"-nd\":\n comparator = comparator.thenComparing(NAME_REVERSED_ORDER);\n break outer;\n case \"-t\":\n comparator = comparator.thenComparing(TIME_ORDER);\n break;\n case \"-td\":\n comparator = comparator.thenComparing(TIME_REVERSED_ORDER);\n break;\n case \"-s\":\n comparator = comparator.thenComparing(SIZE_ORDER);\n break;\n case \"-sd\":\n comparator = comparator.thenComparing(SIZE_REVERSED_ORDER);\n break;\n default:\n throw new IllegalArgumentException(\"Invalid flag \" + flags[i]);\n }\n }\n Arrays.sort(files, comparator);\n }\n return files;\n }\n}\n", "support_files": [], "metadata": {"number": "2.5.29", "chapter": 2, "chapter_title": "Sorting", "section": 2.5, "section_title": "Applications", "type": "Creative Problem", "code_execution": false}} {"question": "Boerner’s theorem. True or false: If you sort each column of a matrix, then sort each row, the columns are still sorted. Justify your answer.", "answer": "True.\n\nSuppose the columns are sorted before the row sort, so row `i` is componentwise no larger than row `i+1`: for every column `j`, `a[i][j] <= a[i+1][j]`. Sorting a row just replaces that row by its order statistics. If every element of one row is componentwise no larger than the corresponding element of the next row before sorting, then the kth smallest element of the first row is no larger than the kth smallest element of the next row. Otherwise the next row would have fewer than `k` elements at least as large as the kth item, contradicting the componentwise domination.\n\nTherefore, after each row is sorted, every column still has `a[i][j] <= a[i+1][j]`, so the columns remain sorted.", "support_files": [], "metadata": {"number": "2.5.30", "chapter": 2, "chapter_title": "Sorting", "section": 2.5, "section_title": "Applications", "type": "Creative Problem", "code_execution": false}} {"question": "Give the number of calls to put() and get() issued by FrequencyCounter, as a function of the number W of words and the number D of distinct words in the input.", "answer": "3.1.6\n\nThe put() method will be called once for every word.\nThe get() method will be called once for every word, except on the first time a word in being inserted in the symbol table.\n\nCalls to put() = W\nCalls to get() = W - D\n\nThanks to faame (https://github.com/faame) for suggesting a better answer.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/221\n", "support_files": [], "metadata": {"number": "3.1.6", "chapter": 3, "chapter_title": "Searching", "section": 3.1, "section_title": "Symbol Tables", "type": "Exercise", "code_execution": false}} {"question": "What is the average number of distinct keys that FrequencyCounter will find among N random nonnegative integers less than 1,000, for N=10, 10^2, 10^3, 10^4, 10^5, and 10^6?", "answer": "For each of the 1,000 possible keys, the probability it appears at least once in `N` independent draws is\n\n`1 - (999/1000)^N`.\n\nBy linearity of expectation, the expected number of distinct keys is\n\n`1000 * (1 - (999/1000)^N)`.\n\n| N | expected distinct keys |\n|---:|---:|\n| 10 | 9.955 |\n| 10^2 | 95.208 |\n| 10^3 | 632.305 |\n| 10^4 | 999.955 |\n| 10^5 | approximately 1000 |\n| 10^6 | approximately 1000 |", "support_files": [], "metadata": {"number": "3.1.7", "chapter": 3, "chapter_title": "Searching", "section": 3.1, "section_title": "Symbol Tables", "type": "Exercise", "code_execution": false}} {"question": "What is the most frequently used word of ten letters or more in Tale of Two Cities?", "answer": "3.1.8\n\nMost frequently used word of ten letters or more in Tale of Two Cities: Monseigneur Frequency: 47\n", "support_files": [], "metadata": {"number": "3.1.8", "chapter": 3, "chapter_title": "Searching", "section": 3.1, "section_title": "Symbol Tables", "type": "Exercise", "code_execution": false}} {"question": "Add code to FrequencyCounter to keep track of the last call to put(). Print the last word inserted and the number of words that were processed in the input stream prior to this insertion. Run your program for tale.txt with length cutoffs 1, 8, and 10.", "answer": "// Exercise9.java\npackage chapter3.section1;\n\nimport edu.princeton.cs.algs4.StdOut;\nimport util.FileUtil;\n\n/**\n * Created by Rene Argento on 23/04/17.\n */\npublic class Exercise9 {\n\n public static void main(String[] args) {\n String filePath = args[0];\n new Exercise9().readBookAndGetLastWordInserted(filePath);\n }\n\n private void readBookAndGetLastWordInserted(String filePath) {\n int[] minLengths = {1, 8, 10};\n\n String[] words = FileUtil.getAllStringsFromFile(filePath);\n\n StdOut.printf(\"%12s %16s %16s\\n\", \"Length cutoff\", \"Last word inserted\", \"Words processed\");\n for (int i = 0; i < minLengths.length; i++) {\n frequencyCounter(words, minLengths[i]);\n }\n }\n\n private void frequencyCounter(String[] words, int minLength) {\n int totalWordsProcessed = 0;\n int wordsProcessedPriorToLastInsertion = 0;\n String lastWordInserted = \"\";\n\n BinarySearchSymbolTable binarySearchSymbolTable = new BinarySearchSymbolTable<>();\n\n for (String word : words) {\n totalWordsProcessed++;\n\n if (word.length() < minLength) {\n continue;\n }\n\n if (!binarySearchSymbolTable.contains(word)) {\n binarySearchSymbolTable.put(word, 1);\n } else {\n binarySearchSymbolTable.put(word, binarySearchSymbolTable.get(word) + 1);\n }\n lastWordInserted = word;\n wordsProcessedPriorToLastInsertion = totalWordsProcessed - 1;\n }\n\n String max = \"\";\n binarySearchSymbolTable.put(max, 0);\n\n for (String word : binarySearchSymbolTable.keys()) {\n if (binarySearchSymbolTable.get(word) > binarySearchSymbolTable.get(max)) {\n max = word;\n }\n }\n printResults(minLength, lastWordInserted, wordsProcessedPriorToLastInsertion);\n }\n\n private void printResults(int lengthCutoff, String lastWordInserted, int wordsProcessedPriorToLastInsertion) {\n StdOut.printf(\"%13d %18s %16d\\n\", lengthCutoff, lastWordInserted, wordsProcessedPriorToLastInsertion);\n }\n}\n\nAdditional notes/results:\n3.1.9\n\nLength cutoff Last word inserted Words processed\n 1 known.\" 135937\n 8 faltering 135905\n 10 disfigurement 135890\n", "support_files": [], "metadata": {"number": "3.1.9", "chapter": 3, "chapter_title": "Searching", "section": 3.1, "section_title": "Symbol Tables", "type": "Exercise", "code_execution": false}} {"question": "Give a trace of the process of inserting the keys E A S Y Q U E S T I O N into an initially empty table using SequentialSearchST. How many compares are involved?", "answer": "3.1.10\n\nkey value first\n E 0 E0 0 compares\n A 1 A1 E0 1 compare\n S 2 S2 A1 E0 2 compares\n Y 3 Y3 S2 A1 E0 3 compares\n Q 4 Q4 Y3 S2 A1 E0 4 compares\n U 5 U5 Q4 Y3 S2 A1 E0 5 compares\n E 6 U5 Q4 Y3 S2 A1 E6 6 compares\n S 7 U5 Q4 Y3 S7 A1 E6 4 compares\n T 8 T8 U5 Q4 Y3 S7 A1 E6 6 compares\n I 9 I9 T8 U5 Q4 Y3 S7 A1 E6 7 compares\n O 10 O10 I9 T8 U5 Q4 Y3 S7 A1 E6 8 compares\n N 11 N11 O10 I9 T8 U5 Q4 Y3 S7 A1 E6 9 compares\n\nTotal: 55 compares\n\nThanks to ebber22 (https://github.com/ebber22) for finding an issue with the way the nodes were being added.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/102\n", "support_files": [], "metadata": {"number": "3.1.10", "chapter": 3, "chapter_title": "Searching", "section": 3.1, "section_title": "Symbol Tables", "type": "Exercise", "code_execution": false}} {"question": "Give a trace of the process of inserting the keys E A S Y Q U E S T I O N into an initially empty table using BinarySearchST. How many compares are involved?", "answer": "Final keys in the table are:\n\n`A E I N O Q S T U Y`\n\nUsing the textbook `BinarySearchST.put()` implementation, the ranks/comparisons for the insertions `E A S Y Q U E S T I O N` are:\n\n| key | compares |\n|---|---:|\n| E | 0 |\n| A | 2 |\n| S | 2 |\n| Y | 2 |\n| Q | 3 |\n| U | 4 |\n| E | 4 |\n| S | 4 |\n| T | 4 |\n| I | 4 |\n| O | 4 |\n| N | 5 |\n\nTotal compares: `38`. If you count only comparisons inside `rank()` and not the final equality check in `put()`, the total is `29`.", "support_files": [], "metadata": {"number": "3.1.11", "chapter": 3, "chapter_title": "Searching", "section": 3.1, "section_title": "Symbol Tables", "type": "Exercise", "code_execution": false}} {"question": "Which of the symbol-table implementations in this section would you use for an application that does 10^3 put() operations and 10^6 get() operations, randomly intermixed? Justify your answer.", "answer": "3.1.13\n\nFor an application that does 10^3 put() operations and 10^6 get() operations I would use a binary search symbol table implementation.\nThe application does a lot more get() than put() operations and a binary search symbol table implementation has a O(log(n)) runtime complexity for the get() operation, which is better than the O(n) runtime complexity of the sequential search symbol table implementation.\n", "support_files": [], "metadata": {"number": "3.1.13", "chapter": 3, "chapter_title": "Searching", "section": 3.1, "section_title": "Symbol Tables", "type": "Exercise", "code_execution": false}} {"question": "Which of the symbol-table implementations in this section would you use for an application that does 10^6 put() operations and 10^3 get() operations, randomly intermixed? Justify your answer.", "answer": "3.1.14\n\nFor an application that does 10^6 put() operations and 10^3 get() operations I would use a sequential search symbol table implementation.\n\nThe worst-case runtime cost of the put() operation for a binary search symbol table is 2N while for a sequential search symbol table it is N.\nFor the get() operation, the worst-case runtime cost of a binary search symbol table is lg(n) while for the sequential search symbol table it is N.\n\nComparing the total number of operations in the worst-case:\nSequential search symbol table: 10^6 + 10^3 ~ 10^6 operations\nBinary search symbol table: 2 * 10^6 + lg(10^3) ~ 2 * 10^6 operations\n\nThe average-case runtime cost of both implementations in this case is similar because most of the operations are put() and both the sequential search symbol table and the binary search symbol table implementations have an average-case cost of N for it.\n\nSo for this application the sequential search symbol table performs better than the binary search symbol table in the worst-case and both perform similarly in the average-case, making the sequential search symbol table the best choice.\n\nThanks to dragon-dreamer (https://github.com/dragon-dreamer) for showing that the sequential search symbol table is the best option in this question.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/119\n", "support_files": [], "metadata": {"number": "3.1.14", "chapter": 3, "chapter_title": "Searching", "section": 3.1, "section_title": "Symbol Tables", "type": "Exercise", "code_execution": false}} {"question": "Assume that searches are 1,000 times more frequent than insertions for a BinarySearchST client. Estimate the percentage of the total time that is devoted to insertions, when the number of searches is 10^3, 10^6, and 10^9.", "answer": "3.1.15\n\n Searches Percentage of total time spent on insertions\n 1000 0.00%\n 1000000 6.10%\n 1000000000 96.26%\n\nThe average insertion cost is N, so the total insertion cost for N keys is N^2.\nThe average search cost is lg N, so the total search cost for M keys is M * lg N.\nAccording to the question, M = 1000 * N.\n\nThe total cost is then:\ntotal cost = N^2 + M * lg N = N^2 + 1000N * lg N\n\nThe insertion percentage is:\nP = (N^2) / (N^2 + 1000N * lg N)\nN^2 is the higher-order element in the equation, so as N increases, the insertion percentage approaches 100%.\n\nThanks to faame (https://github.com/faame) for improving this answer.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/222\n", "support_files": [], "metadata": {"number": "3.1.15", "chapter": 3, "chapter_title": "Searching", "section": 3.1, "section_title": "Symbol Tables", "type": "Exercise", "code_execution": false}} {"question": "Prove that the rank() method in BinarySearchST is correct.", "answer": "3.1.18\n\nThe rank() method in BinarySearchST always starts the search in the middle of the array if it has an odd number of elements.\nIf the array has an even number of elements, the rank() method starts the search on the left of the two middle elements.\nAfter comparing the middle element with the search key, if it is smaller, the search continues on the right side of the array.\nIf it is bigger, the search continues on the left side of the array.\nIf they have the same value, the current element's index is the rank we are looking for.\n\nThis guarantees that if an element exists in the symbol table its rank will be found in the rank() method.\n\nWhen the element does not exist the value of the \"low\" variable will have passed the value of the \"high\" variable, pointing to the correct rank of where the key should be. This only happens when both the element on the left of the final rank has been checked and the element on the current (final) rank has been checked. After these checks, low will be pointing to the correct rank location.\n\nExample:\n\nSymbol Table: 0 1 2 3 5 6\nRank of key 4 (non-existent)\n\n1- The initial search range is [0..5]. The rank() method checks the left of the middle elements on index 2 -> value 2\n2- 2 is less than 4, so the new range to search is [3..5]. The rank() method checks the middle element on index 4 -> value 5\n3- 5 is more than 4, so the new range to search is [3..3]. The rank() method checks the only element left (index 3) -> value 3\n4- 3 is less than 4, so the new range to search is [4..3]. Now the \"low\" variable is bigger than the \"high\" variable.\n5- The rank() method returns the value of the \"low\" variable, 4. This is the correct rank for key 4.\n", "support_files": [], "metadata": {"number": "3.1.18", "chapter": 3, "chapter_title": "Searching", "section": 3.1, "section_title": "Symbol Tables", "type": "Exercise", "code_execution": false}} {"question": "Complete the proof of Proposition B (show that it holds for all values of N). Hint: Start by showing that C(N) is monotonic: C(N) <= C(N+1) for all N > 0.", "answer": "3.1.20\n\nProposition B. Binary search in an ordered array with N keys uses no more than lg N + 1 compares for a search (successful or unsuccessful). \n\nProof: Let C(N) be the number of compares to search for a key in a symbol table of size N.\nWe have C(0) = 0, C(1) = 1, and for N > 0 we can write a recurrence relationship that directly mirrors the recursive method:\nC(N) <= C(FLOOR(N / 2)) + 1\n\nWhether the search goes to the left or to the right, the size of the subarray is no more than FLOOR(N / 2), and we can use one compare to check for equality and to choose whether to go left or right.\n\nLet's first prove by induction that C(N) is monotonic: C(N) <= C(N + 1) for all N > 0.\n\nIt is trivial to prove that:\nC(1) = 1\nC(2) = 1 or 2\n\nThus we have:\nC(1) <= C(2)\n\nAssume for all N=[0, K]\nC(N + 1) >= C(N)\n\nThus we have:\nC(K + 1) >= C(K)\n\nAt the beginning of the binary search, low has value 0 and high has value N. Mid is computed as:\nmid = low + (high - low) / 2 = high / 2\n\nLet's use L to represent the size of the left half and R to represent the size of the right half.\nThe mid element has size 1.\nWhen N = K + 1 the total size is L + 1 + R.\n\nWhen N = K + 2:\nmid = low + (high - low) / 2 = (high + 1) / 2 = (N + 1) / 2\n\nWhen N is incremented by 1 (from K + 1 to K + 2), the mid point either remains in the same place or shifts to the right by 1.\n1- If mid remains in the same place, then L remains the same, and R is incremented by 1.\nSince (R + 1) <= K + 1, we have:\nC(K + 2) = C(L) + 1 + C(R + 1) >= C(L) + 1 + C(R) = C(K + 1)\n2- If mid shifts to the right by 1, then L is incremented by 1 and R remains the same.\nSince (L + 1) <= K + 1, we have:\nC(K + 2) = C(L + 1) + 1 + C(R) >= C(L) + 1 + C(R) = C(K + 1)\n\nTherefore, given C(K + 1) >= C(K) it is also true that C(K + 2) >= C(K + 1), which proves that C(N) is monotonic.\n\nFor a general N, we have that:\n\nC(N) <= C(N / 2) + 1 (one comparison to check equality or decide which way of the subarray to go)\nC(N / 2) <= C(N / 4) + 1\n\nPutting the value of C(N / 2) in the first equation:\nC(N) <= C(N / 4) + 1 + 1\n\nAnd adding all values to the first equation until C = 1:\nC(N) <= C(N / 8) + 1 + 1 + 1\nC(N) <= C(N / 16) + 1 + 1 + 1 + 1\nC(N) <= C(N / 2^k) + 1 + 1 + 1 + 1 + ... + 1\n\nuntil we get to\nC(N) <= 1 + 1 + 1 + 1 + 1 + ... + 1 (even if N is not divisible by 2 there is still a compare operation)\nC(N) <= k + 1\n\nIn this case, 2^k = N\nk <= lg N + 1\n\nWe can also prove it using the Master theorem:\n\nBinary search recurrence relation:\nT(N) = T(N/2) + O(1)\n\nMaster theorem:\nT(N) = aT(N/b) + f(N)\n\nHere, a = 1, b = 2 and f(n) is O(1) (constant)\n\nc = log(a base b) = log(1 base 2) = 0\n\nWe can see that this is the case 2 of the Master theorem by taking k = 0 in this equation:\nO(n^c * (log n)^k)\nO(n^0 * (log n)^0) = O(1) = f(n) -> This means we are in case 2 of the Master theorem\n\nFrom the Case 2 of the Master Theorem we know that:\nT(n) = O(n^(log a base b) * (log n)^(k + 1))\nT(n) = O(n^0 * log(n)^1) = O(log n)\n\nWith binary search, we achieve a logarithmic-time search guarantee.\n\nReference: https://en.wikipedia.org/wiki/Master_theorem\n\nThanks to faame (https://github.com/faame) for adding the section proving that C(N) is monotonic.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/223\n", "support_files": [], "metadata": {"number": "3.1.20", "chapter": 3, "chapter_title": "Searching", "section": 3.1, "section_title": "Symbol Tables", "type": "Exercise", "code_execution": false}} {"question": "Memory usage. Compare the memory usage of BinarySearchST with that of SequentialSearchST for N key-value pairs, under the assumptions described in Section 1.4. Do not count the memory for the keys and values themselves, but do count references to them. For BinarySearchST, assume that array resizing is used, so that the array is between 25 percent and 100 percent full.", "answer": "3.1.21 - Memory usage\n\n* BinarySearchST\n object overhead -> 16 bytes\n Key[] reference (keys) -> 8 bytes\n Value[] reference (values) -> 8 bytes\n int value (size) -> 4 bytes\n padding -> 4 bytes\n Key[]\n object overhead -> 16 bytes\n int value (length) -> 4 bytes\n padding -> 4 bytes\n N Key references -> between 8N and 32N bytes (the resizing array may be 25% to 100% full)\n Value[]\n object overhead -> 16 bytes\n int value (length) -> 4 bytes\n padding -> 4 bytes\n N Value references -> between 8N and 32N bytes (the resizing array may be 25% to 100% full)\nAmount of memory needed: 16 + 8 + 8 + 4 + 4 + 16 + 4 + 4 + (8N to 32N) + 16 + 4 + 4 + (8N to 32N) = (16N to 64N) + 88 bytes\n\n* SequentialSearchST\n object overhead -> 16 bytes\n Node reference (first) -> 8 bytes\n Node\n object overhead -> 16 bytes\n extra overhead for reference to the enclosing instance -> 8 bytes\n Key reference (key) -> 8 bytes\n Value reference (value) -> 8 bytes\n Node reference (next) -> 8 bytes\n (N Node references -> 48N bytes)\n int value (size) -> 4 bytes\n padding -> 4 bytes\nAmount of memory needed: 16 + 8 + (16 + 8 + 8 + 8 + 8)N + 4 + 4 = 48N + 32 bytes\n", "support_files": [], "metadata": {"number": "3.1.21", "chapter": 3, "chapter_title": "Searching", "section": 3.1, "section_title": "Symbol Tables", "type": "Creative Problem", "code_execution": false}} {"question": "Analysis of binary search. Prove that the maximum number of compares used for a binary search in a table of size N is precisely the number of bits in the binary representation of N, because the operation of shifting 1 bit to the right converts the binary representation of N into the binary representation of floor(N/2).", "answer": "3.1.23 - Analysis of binary search\n\nAs the book and exercise 3.1.20 have proven, the maximum number of compares used for a binary search in a table of size N is lg N + 1.\n\nA number N has exactly lg N + 1 bits. This is because shifting 1 bit to the right reduces the number by half (rounded down).\n\nFor example:\n\nN Bit representation Number of bits lg N + 1\n1 1 1 1\n2 10 2 2\n4 100 3 3\n5 101 3 3\n9 1001 4 4\n\nTherefore, the maximum number of compares used for a binary search in a table of size N is precisely the number of bits in the binary representation of N.\n", "support_files": [], "metadata": {"number": "3.1.23", "chapter": 3, "chapter_title": "Searching", "section": 3.1, "section_title": "Symbol Tables", "type": "Creative Problem", "code_execution": false}} {"question": "Small tables. Suppose that a BinarySearchST client has S search operations and N distinct keys. Give the order of growth of S such that the cost of building the table is the same as the cost of all the searches.", "answer": "3.1.27 - Small tables\n\nBuilding the binary search symbol table requires N calls to put().\nEvery put() operation makes a call to rank() and does a search, an operation with order of growth O(lg N).\nAssuming that we can choose the order of the keys to insert, we can create the table in a sorted order, starting with the smallest element and ending with the highest element.\nBy doing this, every element will be inserted at the end of the keys[] and values[] array, making the put() operation use O(lg N) for the rank() operation and O(1) for the insert (there will be no need to move keys and values to the right since the new element is the rightmost element). N inserts will have an order of growth of O(N lg N).\n\nA search operation has the order of growth O(lg N).\nTherefore, the order of growth of S should be O(N), with S search operations having an order of growth O(N lg N), making the cost of building the table the same as the cost of all searches.\n\nIf the items are inserted in random order, the put operation has an order of growth O(N): O(lg N) for the rank operation and O(N) for inserting an element. N inserts will have an order of growth of O(N^2).\nIn this case, the order of growth of S should be O(N^2 / lg N).\n\nThanks to dragon-dreamer (https://github.com/dragon-dreamer) for correcting the orders of growth of S.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/120\n", "support_files": [], "metadata": {"number": "3.1.27", "chapter": 3, "chapter_title": "Searching", "section": 3.1, "section_title": "Symbol Tables", "type": "Creative Problem", "code_execution": false}} {"question": "Add to BST 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 a method like size() that adds a field to each node in the tree (and takes linear space and constant time per query).", "answer": "package chapter3.section2;\n\nimport edu.princeton.cs.algs4.Queue;\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.NoSuchElementException;\n\n/**\n * Created by Rene Argento on 09/05/17.\n */\npublic class Exercise6 {\n\n private class BinarySearchTree, Value>{\n\n private class Node {\n private Key key;\n private Value value;\n\n private Node left;\n private Node right;\n\n private int size; //# of nodes in subtree rooted here\n private int height; //height of the subtree rooted here\n\n public Node(Key key, Value value, int size) {\n this.key = key;\n this.value = value;\n this.size = size;\n }\n }\n\n private Node root;\n\n public int size() {\n return size(root);\n }\n\n private int size(Node node) {\n if (node == null) {\n return 0;\n }\n\n return node.size;\n }\n\n public int heightRecursive() {\n return heightRecursive(root);\n }\n\n private int heightRecursive(Node node) {\n if (node == null) {\n return -1;\n }\n\n return Math.max(heightRecursive(node.left), heightRecursive(node.right)) + 1;\n }\n\n public int heightConstant() {\n return heightConstant(root);\n }\n\n private int heightConstant(Node node) {\n if (node == null) {\n return -1;\n }\n\n return node.height;\n }\n\n public Value get(Key key) {\n return get(root, key);\n }\n\n private Value get(Node node, Key key) {\n if (node == null) {\n return null;\n }\n\n int compare = key.compareTo(node.key);\n if (compare < 0) {\n return get(node.left, key);\n } else if (compare > 0) {\n return get(node.right, key);\n } else {\n return node.value;\n }\n }\n\n public void put(Key key, Value value) {\n root = put(root, key, value);\n }\n\n private Node put(Node node, Key key, Value value) {\n if (node == null) {\n return new Node(key, value, 1);\n }\n\n int compare = key.compareTo(node.key);\n\n if (compare < 0) {\n node.left = put(node.left, key, value);\n } else if (compare > 0) {\n node.right = put(node.right, key, value);\n } else {\n node.value = value;\n }\n\n node.size = size(node.left) + 1 + size(node.right);\n node.height = Math.max(heightConstant(node.left), heightConstant(node.right)) + 1;\n\n return node;\n }\n\n public Key min() {\n if (root == null) {\n throw new NoSuchElementException(\"Empty binary search tree\");\n }\n\n return min(root).key;\n }\n\n private Node min(Node node) {\n if (node.left == null) {\n return node;\n }\n\n return min(node.left);\n }\n\n public Key max() {\n if (root == null) {\n throw new NoSuchElementException(\"Empty binary search tree\");\n }\n\n return max(root).key;\n }\n\n private Node max(Node node) {\n if (node.right == null) {\n return node;\n }\n\n return max(node.right);\n }\n\n public Key floor(Key key) {\n Node node = floor(root, key);\n if (node == null) {\n return null;\n }\n\n return node.key;\n }\n\n private Node floor(Node node, Key key) {\n if (node == null) {\n return null;\n }\n\n int compare = key.compareTo(node.key);\n\n if (compare == 0) {\n return node;\n } else if (compare < 0) {\n return floor(node.left, key);\n } else {\n Node rightNode = floor(node.right, key);\n if (rightNode != null) {\n return rightNode;\n } else {\n return node;\n }\n }\n }\n\n public Key ceiling(Key key) {\n Node node = ceiling(root, key);\n if (node == null) {\n return null;\n }\n\n return node.key;\n }\n\n private Node ceiling(Node node, Key key) {\n if (node == null) {\n return null;\n }\n\n int compare = key.compareTo(node.key);\n\n if (compare == 0) {\n return node;\n } else if (compare > 0) {\n return ceiling(node.right, key);\n } else {\n Node leftNode = ceiling(node.left, key);\n if (leftNode != null) {\n return leftNode;\n } else {\n return node;\n }\n }\n }\n\n public Key select(int index) {\n if (index >= size()) {\n throw new IllegalArgumentException(\"Index is higher than tree size\");\n }\n\n return select(root, index).key;\n }\n\n private Node select(Node node, int index) {\n int leftSubtreeSize = size(node.left);\n\n if (leftSubtreeSize == index) {\n return node;\n } else if (leftSubtreeSize > index) {\n return select(node.left, index);\n } else {\n return select(node.right, index - leftSubtreeSize - 1);\n }\n }\n\n public int rank(Key key) {\n return rank(root, key);\n }\n\n private int rank(Node node, Key key) {\n if (node == null) {\n return 0;\n }\n\n //Returns the number of keys less than node.key in the subtree rooted at node\n int compare = key.compareTo(node.key);\n if (compare < 0) {\n return rank(node.left, key);\n } else if (compare > 0) {\n return size(node.left) + 1 + rank(node.right, key);\n } else {\n return size(node.left);\n }\n }\n\n public void deleteMin() {\n root = deleteMin(root);\n }\n\n private Node deleteMin(Node node) {\n if (node == null) {\n return null;\n }\n\n if (node.left == null) {\n return node.right;\n }\n\n node.left = deleteMin(node.left);\n\n node.size = size(node.left) + 1 + size(node.right);\n node.height = Math.max(heightConstant(node.left), heightConstant(node.right)) + 1;\n\n return node;\n }\n\n public void deleteMax() {\n root = deleteMax(root);\n }\n\n private Node deleteMax(Node node) {\n if (node == null) {\n return null;\n }\n\n if (node.right == null) {\n return node.left;\n }\n\n node.right = deleteMax(node.right);\n\n node.size = size(node.left) + 1 + size(node.right);\n node.height = Math.max(heightConstant(node.left), heightConstant(node.right)) + 1;\n\n return node;\n }\n\n public void delete(Key key) {\n root = delete(root, key);\n }\n\n private Node delete(Node node, Key key) {\n if (node == null) {\n return null;\n }\n\n int compare = key.compareTo(node.key);\n if (compare < 0) {\n node.left = delete(node.left, key);\n } else if (compare > 0) {\n node.right = delete(node.right, key);\n } else {\n if (node.left == null) {\n return node.right;\n } else if (node.right == null) {\n return node.left;\n } else {\n Node aux = node;\n node = min(aux.right);\n node.right = deleteMin(aux.right);\n node.left = aux.left;\n }\n }\n\n node.size = size(node.left) + 1 + size(node.right);\n node.height = Math.max(heightConstant(node.left), heightConstant(node.right)) + 1;\n return node;\n }\n\n public Iterable keys() {\n return keys(min(), max());\n }\n\n public Iterable keys(Key low, Key high) {\n Queue queue = new Queue<>();\n keys(root, queue, low, high);\n return queue;\n }\n\n private void keys(Node node, Queue queue, Key low, Key high) {\n if (node == null) {\n return;\n }\n\n int compareLow = low.compareTo(node.key);\n int compareHigh = high.compareTo(node.key);\n\n if (compareLow < 0) {\n keys(node.left, queue, low, high);\n }\n\n if (compareLow <= 0 && compareHigh >= 0) {\n queue.enqueue(node.key);\n }\n\n if (compareHigh > 0) {\n keys(node.right, queue, low, high);\n }\n }\n\n }\n\n public static void main(String[] args) {\n Exercise6 exercise6 = new Exercise6();\n\n exercise6.testRecursiveHeightMethod();\n exercise6.testNonRecursiveHeightMethod();\n }\n\n private void testRecursiveHeightMethod() {\n BinarySearchTree binarySearchTree = new BinarySearchTree<>();\n\n StdOut.println(\"Recursive height method tests\");\n StdOut.println(\"Height 1: \" + binarySearchTree.heightRecursive() + \" Expected: -1\");\n\n binarySearchTree.put(0, 0);\n binarySearchTree.put(1, 1);\n binarySearchTree.put(2, 2);\n binarySearchTree.put(3, 3);\n\n StdOut.println(\"Height 2: \" + binarySearchTree.heightRecursive() + \" Expected: 3\");\n\n binarySearchTree.put(-1, -1);\n binarySearchTree.put(-2, -2);\n\n StdOut.println(\"Height 3: \" + binarySearchTree.heightRecursive() + \" Expected: 3\");\n\n binarySearchTree.put(-10, -10);\n binarySearchTree.put(-7, -7);\n\n StdOut.println(\"Height 4: \" + binarySearchTree.heightRecursive() + \" Expected: 4\");\n\n binarySearchTree.delete(-7);\n StdOut.println(\"Height 5: \" + binarySearchTree.heightRecursive() + \" Expected: 3\");\n\n binarySearchTree.deleteMin();\n binarySearchTree.deleteMax();\n StdOut.println(\"Height 6: \" + binarySearchTree.heightRecursive() + \" Expected: 2\");\n }\n\n private void testNonRecursiveHeightMethod() {\n BinarySearchTree binarySearchTree = new BinarySearchTree<>();\n\n StdOut.println(\"\\nAdded-field height method tests\");\n StdOut.println(\"Height 1: \" + binarySearchTree.heightConstant() + \" Expected: -1\");\n\n binarySearchTree.put(0, 0);\n binarySearchTree.put(1, 1);\n binarySearchTree.put(2, 2);\n binarySearchTree.put(3, 3);\n\n StdOut.println(\"Height 2: \" + binarySearchTree.heightConstant() + \" Expected: 3\");\n\n binarySearchTree.put(-1, -1);\n binarySearchTree.put(-2, -2);\n\n StdOut.println(\"Height 3: \" + binarySearchTree.heightConstant() + \" Expected: 3\");\n\n binarySearchTree.put(-10, -10);\n binarySearchTree.put(-7, -7);\n\n StdOut.println(\"Height 4: \" + binarySearchTree.heightConstant() + \" Expected: 4\");\n\n binarySearchTree.delete(-7);\n StdOut.println(\"Height 5: \" + binarySearchTree.heightConstant() + \" Expected: 3\");\n\n binarySearchTree.deleteMin();\n binarySearchTree.deleteMax();\n StdOut.println(\"Height 6: \" + binarySearchTree.heightConstant() + \" Expected: 2\");\n }\n\n}\n", "support_files": [], "metadata": {"number": "3.2.6", "chapter": 3, "chapter_title": "Searching", "section": 3.2, "section_title": "Binary Search Trees", "type": "Exercise", "code_execution": false}} {"question": "Add to BST a recursive method avgCompares() that computes the average number of compares required by a random search hit in a given BST (the internal path length of the tree divided by its size, plus one). Develop two implementations: a recursive method (which takes linear time and space proportional to the height), and a method like size() that adds a field to each node in the tree (and takes linear space and constant time per query).", "answer": "package chapter3.section2;\n\nimport edu.princeton.cs.algs4.Queue;\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.NoSuchElementException;\n\n/**\n * Created by Rene Argento on 16/05/17.\n */\n// Thanks to ckwastra (https://github.com/ckwastra) for fixing the internal path length computation.\n// https://github.com/reneargento/algorithms-sedgewick-wayne/issues/276\npublic class Exercise7 {\n\n private class BinarySearchTree, Value>{\n\n private class Node {\n private Key key;\n private Value value;\n\n private Node left;\n private Node right;\n\n private int size; //# of nodes in subtree rooted here\n private int totalNumberOfComparesRequired; //number of compares required to reach all nodes in the subtree rooted here\n\n public Node(Key key, Value value, int size) {\n this.key = key;\n this.value = value;\n this.size = size;\n }\n }\n\n private Node root;\n\n public int size() {\n return size(root);\n }\n\n private int size(Node node) {\n if (node == null) {\n return 0;\n }\n return node.size;\n }\n\n public double avgComparesRecursive() {\n if (root == null) {\n return 0;\n }\n int internalPathLength = avgComparesRecursive(root);\n return internalPathLength / (double) size() + 1;\n }\n\n private int avgComparesRecursive(Node node) {\n if (node == null) {\n return 0;\n }\n return node.size - 1 +\n avgComparesRecursive(node.left) +\n avgComparesRecursive(node.right);\n }\n\n public double avgComparesConstant() {\n if (root == null) {\n return 0;\n }\n return totalNumberOfComparesRequired(root) / (double) size() + 1;\n }\n\n private int totalNumberOfComparesRequired(Node node) {\n if (node == null) {\n return 0;\n }\n return node.totalNumberOfComparesRequired;\n }\n\n public Value get(Key key) {\n return get(root, key);\n }\n\n private Value get(Node node, Key key) {\n if (node == null) {\n return null;\n }\n\n int compare = key.compareTo(node.key);\n if (compare < 0) {\n return get(node.left, key);\n } else if (compare > 0) {\n return get(node.right, key);\n } else {\n return node.value;\n }\n }\n\n public void put(Key key, Value value) {\n root = put(root, key, value);\n }\n\n private Node put(Node node, Key key, Value value) {\n if (node == null) {\n return new Node(key, value, 1);\n }\n\n int compare = key.compareTo(node.key);\n\n if (compare < 0) {\n node.left = put(node.left, key, value);\n } else if (compare > 0) {\n node.right = put(node.right, key, value);\n } else {\n node.value = value;\n }\n\n node.size = size(node.left) + 1 + size(node.right);\n node.totalNumberOfComparesRequired = node.size - 1 +\n totalNumberOfComparesRequired(node.left) +\n totalNumberOfComparesRequired(node.right);\n return node;\n }\n\n public Key min() {\n if (root == null) {\n throw new NoSuchElementException(\"Empty binary search tree\");\n }\n return min(root).key;\n }\n\n private Node min(Node node) {\n if (node.left == null) {\n return node;\n }\n return min(node.left);\n }\n\n public Key max() {\n if (root == null) {\n throw new NoSuchElementException(\"Empty binary search tree\");\n }\n return max(root).key;\n }\n\n private Node max(Node node) {\n if (node.right == null) {\n return node;\n }\n return max(node.right);\n }\n\n public Key floor(Key key) {\n Node node = floor(root, key);\n if (node == null) {\n return null;\n }\n return node.key;\n }\n\n private Node floor(Node node, Key key) {\n if (node == null) {\n return null;\n }\n int compare = key.compareTo(node.key);\n\n if (compare == 0) {\n return node;\n } else if (compare < 0) {\n return floor(node.left, key);\n } else {\n Node rightNode = floor(node.right, key);\n if (rightNode != null) {\n return rightNode;\n } else {\n return node;\n }\n }\n }\n\n public Key ceiling(Key key) {\n Node node = ceiling(root, key);\n if (node == null) {\n return null;\n }\n return node.key;\n }\n\n private Node ceiling(Node node, Key key) {\n if (node == null) {\n return null;\n }\n int compare = key.compareTo(node.key);\n\n if (compare == 0) {\n return node;\n } else if (compare > 0) {\n return ceiling(node.right, key);\n } else {\n Node leftNode = ceiling(node.left, key);\n if (leftNode != null) {\n return leftNode;\n } else {\n return node;\n }\n }\n }\n\n public Key select(int index) {\n if (index >= size()) {\n throw new IllegalArgumentException(\"Index is higher than tree size\");\n }\n return select(root, index).key;\n }\n\n private Node select(Node node, int index) {\n int leftSubtreeSize = size(node.left);\n\n if (leftSubtreeSize == index) {\n return node;\n } else if (leftSubtreeSize > index) {\n return select(node.left, index);\n } else {\n return select(node.right, index - leftSubtreeSize - 1);\n }\n }\n\n public int rank(Key key) {\n return rank(root, key);\n }\n\n private int rank(Node node, Key key) {\n if (node == null) {\n return 0;\n }\n\n //Returns the number of keys less than node.key in the subtree rooted at node\n int compare = key.compareTo(node.key);\n if (compare < 0) {\n return rank(node.left, key);\n } else if (compare > 0) {\n return size(node.left) + 1 + rank(node.right, key);\n } else {\n return size(node.left);\n }\n }\n\n public void deleteMin() {\n root = deleteMin(root);\n }\n\n private Node deleteMin(Node node) {\n if (node == null) {\n return null;\n }\n if (node.left == null) {\n return node.right;\n }\n node.left = deleteMin(node.left);\n\n node.size = size(node.left) + 1 + size(node.right);\n node.totalNumberOfComparesRequired = node.size - 1 +\n totalNumberOfComparesRequired(node.left) +\n totalNumberOfComparesRequired(node.right);\n return node;\n }\n\n public void deleteMax() {\n root = deleteMax(root);\n }\n\n private Node deleteMax(Node node) {\n if (node == null) {\n return null;\n }\n if (node.right == null) {\n return node.left;\n }\n\n node.right = deleteMax(node.right);\n\n node.size = size(node.left) + 1 + size(node.right);\n node.totalNumberOfComparesRequired = node.size - 1 +\n totalNumberOfComparesRequired(node.left) +\n totalNumberOfComparesRequired(node.right);\n return node;\n }\n\n public void delete(Key key) {\n root = delete(root, key);\n }\n\n private Node delete(Node node, Key key) {\n if (node == null) {\n return null;\n }\n\n int compare = key.compareTo(node.key);\n if (compare < 0) {\n node.left = delete(node.left, key);\n } else if (compare > 0) {\n node.right = delete(node.right, key);\n } else {\n if (node.left == null) {\n return node.right;\n } else if (node.right == null) {\n return node.left;\n } else {\n Node aux = node;\n node = min(aux.right);\n node.right = deleteMin(aux.right);\n node.left = aux.left;\n }\n }\n\n node.size = size(node.left) + 1 + size(node.right);\n node.totalNumberOfComparesRequired = node.size - 1 +\n totalNumberOfComparesRequired(node.left) +\n totalNumberOfComparesRequired(node.right);\n return node;\n }\n\n public Iterable keys() {\n return keys(min(), max());\n }\n\n public Iterable keys(Key low, Key high) {\n Queue queue = new Queue<>();\n keys(root, queue, low, high);\n return queue;\n }\n\n private void keys(Node node, Queue queue, Key low, Key high) {\n if (node == null) {\n return;\n }\n\n int compareLow = low.compareTo(node.key);\n int compareHigh = high.compareTo(node.key);\n\n if (compareLow < 0) {\n keys(node.left, queue, low, high);\n }\n\n if (compareLow <= 0 && compareHigh >= 0) {\n queue.enqueue(node.key);\n }\n\n if (compareHigh > 0) {\n keys(node.right, queue, low, high);\n }\n }\n }\n\n public static void main(String[] args) {\n Exercise7 exercise7 = new Exercise7();\n\n exercise7.testAvgComparesRecursive();\n exercise7.testAvgComparesNonRecursive();\n }\n\n private void testAvgComparesRecursive() {\n BinarySearchTree binarySearchTree = new BinarySearchTree<>();\n\n StdOut.println(\"Recursive average number of compares method tests\");\n StdOut.printf(\"AVG Compares 1: %.1f Expected: 0.0\\n\", binarySearchTree.avgComparesRecursive());\n\n binarySearchTree.put(0, 0);\n binarySearchTree.put(1, 1);\n binarySearchTree.put(2, 2);\n binarySearchTree.put(3, 3);\n\n StdOut.printf(\"AVG Compares 2: %.1f Expected: 2.5\\n\", binarySearchTree.avgComparesRecursive());\n\n binarySearchTree.put(-1, -1);\n binarySearchTree.put(-2, -2);\n\n StdOut.printf(\"AVG Compares 3: %.1f Expected: 2.5\\n\", binarySearchTree.avgComparesRecursive());\n\n binarySearchTree.put(-10, -10);\n binarySearchTree.put(-7, -7);\n\n StdOut.printf(\"AVG Compares 4: %.1f Expected: 3.0\\n\", binarySearchTree.avgComparesRecursive());\n\n binarySearchTree.delete(-7);\n StdOut.printf(\"AVG Compares 5: %.1f Expected: 2.7\\n\", binarySearchTree.avgComparesRecursive());\n\n binarySearchTree.deleteMin();\n binarySearchTree.deleteMax();\n StdOut.printf(\"AVG Compares 6: %.1f Expected: 2.2\\n\", binarySearchTree.avgComparesRecursive());\n }\n\n private void testAvgComparesNonRecursive() {\n BinarySearchTree binarySearchTree = new BinarySearchTree<>();\n\n StdOut.println(\"\\nAdded-field average number of compares method tests\");\n StdOut.printf(\"AVG Compares 1: %.1f Expected: 0.0\\n\", binarySearchTree.avgComparesConstant());\n\n binarySearchTree.put(0, 0);\n binarySearchTree.put(1, 1);\n binarySearchTree.put(2, 2);\n binarySearchTree.put(3, 3);\n\n StdOut.printf(\"AVG Compares 2: %.1f Expected: 2.5\\n\", binarySearchTree.avgComparesConstant());\n\n binarySearchTree.put(-1, -1);\n binarySearchTree.put(-2, -2);\n\n StdOut.printf(\"AVG Compares 3: %.1f Expected: 2.5\\n\", binarySearchTree.avgComparesConstant());\n\n binarySearchTree.put(-10, -10);\n binarySearchTree.put(-7, -7);\n\n StdOut.printf(\"AVG Compares 4: %.1f Expected: 3.0\\n\", binarySearchTree.avgComparesConstant());\n\n binarySearchTree.delete(-7);\n StdOut.printf(\"AVG Compares 5: %.1f Expected: 2.7\\n\", binarySearchTree.avgComparesConstant());\n\n binarySearchTree.deleteMin();\n binarySearchTree.deleteMax();\n StdOut.printf(\"AVG Compares 6: %.1f Expected: 2.2\\n\", binarySearchTree.avgComparesConstant());\n }\n}\n", "support_files": [], "metadata": {"number": "3.2.7", "chapter": 3, "chapter_title": "Searching", "section": 3.2, "section_title": "Binary Search Trees", "type": "Exercise", "code_execution": false}} {"question": "Write a static method optCompares() that takes an integer argument N and computes the number of compares required by a random search hit in an optimal (perfectly balanced) BST, where all the null links are on the same level if the number of links is a power of 2 or on one of two levels otherwise.", "answer": "package chapter3.section2;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 27/05/17.\n */\n// Thanks to ckwastra (https://github.com/ckwastra) for suggesting a O(1) solution.\n// https://github.com/reneargento/algorithms-sedgewick-wayne/issues/277\npublic class Exercise8 {\n\n public static void main(String[] args) {\n StdOut.printf(\"Test 0: %.2f Expected: 0.00\\n\", optCompares(0));\n StdOut.printf(\"Test 1: %.2f Expected: 1.00\\n\", optCompares(1));\n StdOut.printf(\"Test 2: %.2f Expected: 1.50\\n\", optCompares(2));\n StdOut.printf(\"Test 3: %.2f Expected: 1.67\\n\", optCompares(3));\n StdOut.printf(\"Test 7: %.2f Expected: 2.43\\n\", optCompares(7));\n StdOut.printf(\"Test 8: %.2f Expected: 2.63\\n\", optCompares(8));\n StdOut.printf(\"Test 15: %.2f Expected: 3.27\\n\", optCompares(15));\n StdOut.printf(\"Test 16: %.2f Expected: 3.38\\n\", optCompares(16));\n }\n\n // O(1)\n // Consider H = height of the tree.\n // For nodes on the first H levels, the total path length is:\n // SUM(from i = 1 to H - 1) i * 2^i = (H - 2) * 2^H + 2\n // The total path in the last level is:\n // (N - (2^H - 1)) * H = (N - 2^H + 1) * H\n // Adding them, we have:\n // (H - 2) * 2^H + 2 + (N - 2^H + 1) * H = (N + 1) * H - 2^(H + 1) + 2\n private static double optCompares(int n) {\n if (n == 0) {\n return 0;\n }\n int height = (int) (Math.log(n) / Math.log(2));\n return ((n + 1) * height - Math.pow(2, height + 1) + 2) / n + 1;\n }\n\n // O(h)\n private static double optCompares2(int n) {\n if (n == 0) {\n return 0;\n }\n int totalCompares = 0;\n int height = (int) (Math.log(n) / Math.log(2));\n int numberOfNodesBeforeLastLevel = 0;\n\n // Compute the compares in all levels, except the last (because the last level may not be complete)\n for (int i = 1; i <= height; i++) {\n totalCompares += i * Math.pow(2, i - 1);\n numberOfNodesBeforeLastLevel += Math.pow(2, i - 1);\n }\n\n // Add compares required to reach the nodes in the last level\n int nodesInLastLevel = n - numberOfNodesBeforeLastLevel;\n totalCompares += nodesInLastLevel * (height + 1);\n\n // Total compares is the internal path length\n return (totalCompares / (double) n);\n }\n}\n", "support_files": [], "metadata": {"number": "3.2.8", "chapter": 3, "chapter_title": "Searching", "section": 3.2, "section_title": "Binary Search Trees", "type": "Exercise", "code_execution": false}} {"question": "Draw all the different BST shapes that can result when N keys are inserted into an initially empty tree, for N = 2, 3, 4, 5, and 6.", "answer": "There are Catalan-number many BST shapes: `C_2 = 2`, `C_3 = 5`, `C_4 = 14`, `C_5 = 42`, and `C_6 = 132`.\n\nA compact exact way to draw every shape is to use the recursive notation `X(left,right)`, with `.` for an empty subtree. The following generator prints all shapes for each requested `N`:\n\n```java\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class BSTShapes {\n private static List shapes(int n) {\n List result = new ArrayList<>();\n if (n == 0) {\n result.add(\".\");\n return result;\n }\n for (int leftSize = 0; leftSize < n; leftSize++) {\n int rightSize = n - 1 - leftSize;\n for (String left : shapes(leftSize)) {\n for (String right : shapes(rightSize)) {\n result.add(\"X(\" + left + \",\" + right + \")\");\n }\n }\n }\n return result;\n }\n\n public static void main(String[] args) {\n for (int n = 2; n <= 6; n++) {\n List s = shapes(n);\n System.out.println(\"N = \" + n + \" count = \" + s.size());\n for (String shape : s) System.out.println(shape);\n }\n }\n}\n```\n\nThis enumerates exactly all possible BST shapes because choosing the root leaves `k` keys on the left and `N-1-k` keys on the right, independently, for each `k` from `0` to `N-1`.", "support_files": [], "metadata": {"number": "3.2.9", "chapter": 3, "chapter_title": "Searching", "section": 3.2, "section_title": "Binary Search Trees", "type": "Exercise", "code_execution": false}} {"question": "Write a test client TestBST.java for use in testing the implementations of min(), max(), floor(), ceiling(), select(), rank(), delete(), deleteMin(), deleteMax(), and keys() that are given in the text. Start with the standard indexing client given on page 370. Add code to take additional command-line arguments, as appropriate.", "answer": "package chapter3.section2;\n\nimport edu.princeton.cs.algs4.StdIn;\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 28/05/17.\n */\npublic class TestBST {\n\n public static void main(String[] args) {\n\n /** Test type\n * 0- Keys()\n * 1- Min()\n * 2- Max()\n * 3- Floor()\n * 4- Ceiling()\n * 5- Select()\n * 6- Rank()\n * 7- Delete()\n * 8- DeleteMin()\n * 9- DeleteMax()\n * 10- Keys() with range\n *\n * Or no value, for all tests\n */\n\n int testType = -1;\n if (args.length == 1) {\n testType = Integer.parseInt(args[0]);\n }\n\n // Test values:\n // 5 1 9 2 0 99\n\n BinarySearchTree binarySearchTree = new BinarySearchTree<>();\n\n while (!StdIn.isEmpty()) {\n Integer key = StdIn.readInt();\n binarySearchTree.put(key, \"Value \" + key);\n }\n\n if (testType == -1 || testType == 0) {\n StdOut.println(\"Keys() test\");\n\n for (Integer key : binarySearchTree.keys()) {\n StdOut.println(\"Key \" + key + \": \" + binarySearchTree.get(key));\n }\n\n StdOut.println(\"Expected: 0 1 2 5 9 99\\n\");\n }\n\n if (testType == -1 || testType == 1) {\n // Test min()\n StdOut.println(\"Min key: \" + binarySearchTree.min() + \" Expected: 0\");\n }\n\n if (testType == -1 || testType == 2) {\n // Test max()\n StdOut.println(\"Max key: \" + binarySearchTree.max() + \" Expected: 99\");\n }\n\n if (testType == -1 || testType == 3) {\n // Test floor()\n StdOut.println(\"Floor of 5: \" + binarySearchTree.floor(5) + \" Expected: 5\");\n StdOut.println(\"Floor of 15: \" + binarySearchTree.floor(15) + \" Expected: 9\");\n }\n\n if (testType == -1 || testType == 4) {\n // Test ceiling()\n StdOut.println(\"Ceiling of 5: \" + binarySearchTree.ceiling(5) + \" Expected: 5\");\n StdOut.println(\"Ceiling of 15: \" + binarySearchTree.ceiling(15) + \" Expected: 99\");\n }\n\n if (testType == -1 || testType == 5) {\n // Test select()\n StdOut.println(\"Select key of rank 4: \" + binarySearchTree.select(4) + \" Expected: 9\");\n }\n\n if (testType == -1 || testType == 6) {\n // Test rank()\n StdOut.println(\"Rank of key 9: \" + binarySearchTree.rank(9) + \" Expected: 4\");\n StdOut.println(\"Rank of key 10: \" + binarySearchTree.rank(10) + \" Expected: 5\");\n }\n\n if (testType == -1 || testType == 7) {\n // Test delete()\n StdOut.println(\"\\nDelete key 2\");\n binarySearchTree.delete(2);\n\n for (Integer key : binarySearchTree.keys()) {\n StdOut.println(\"Key \" + key + \": \" + binarySearchTree.get(key));\n }\n }\n\n if (testType == -1 || testType == 8) {\n // Test deleteMin()\n StdOut.println(\"\\nDelete min (key 0)\");\n binarySearchTree.deleteMin();\n\n for (Integer key : binarySearchTree.keys()) {\n StdOut.println(\"Key \" + key + \": \" + binarySearchTree.get(key));\n }\n }\n\n if (testType == -1 || testType == 9) {\n // Test deleteMax()\n StdOut.println(\"\\nDelete max (key 99)\");\n binarySearchTree.deleteMax();\n\n for (Integer key : binarySearchTree.keys()) {\n StdOut.println(\"Key \" + key + \": \" + binarySearchTree.get(key));\n }\n }\n\n if (testType == -1 || testType == 10) {\n // Test keys() with range\n StdOut.println(\"\\nKeys in range [2, 10]\");\n for (Integer key : binarySearchTree.keys(2, 10)) {\n StdOut.println(\"Key \" + key + \": \" + binarySearchTree.get(key));\n }\n }\n }\n}\n", "support_files": [], "metadata": {"number": "3.2.10", "chapter": 3, "chapter_title": "Searching", "section": 3.2, "section_title": "Binary Search Trees", "type": "Exercise", "code_execution": false}} {"question": "How many binary tree shapes of N nodes are there with height N? How many different ways are there to insert N distinct keys into an initially empty BST that result in a tree of height N? (See Exercise 3.2.2.)", "answer": "3.2.11\n\nWe can build different shapes of trees of height N with all combinations of right and left links on nodes with children.\nExample with N = 4:\n\nInsertion order: 1 2 3 4\n1\n 2\n 3\n 4\n\nInsertion order: 1 2 4 3\n1\n 2\n 4\n 3\n\nInsertion order: 1 4 3 2\n 1\n 4\n 3\n2\n\nInsertion order: 1 4 2 3\n 1\n 4\n 2\n 3\n\nInsertion order: 4 1 3 2\n 4\n1\n 3\n2\n\nInsertion order: 4 1 2 3\n 4\n1\n 2\n 3\n\nInsertion order: 4 3 1 2\n 4\n 3\n1\n 2\n\nInsertion order: 4 3 2 1\n 4\n 3\n 2\n1\n\nTherefore, there are 2^(N - 1) binary tree shapes of N nodes with height N.\nAnd there are 2^(N - 1) different ways to insert N distinct keys into an initially empty BST that result in a tree of height N.\n\nThanks to Oreshnik (https://github.com/Oreshnik) for finding the correct solution to this exercise.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/63\n", "support_files": [], "metadata": {"number": "3.2.11", "chapter": 3, "chapter_title": "Searching", "section": 3.2, "section_title": "Binary Search Trees", "type": "Exercise", "code_execution": false}} {"question": "Give nonrecursive implementations of get() and put() for BST.", "answer": "package chapter3.section2;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 30/05/17.\n */\n// Thanks to faame (https://github.com/faame) for suggesting an improvement to the put() method.\n// https://github.com/reneargento/algorithms-sedgewick-wayne/issues/228\npublic class Exercise13 {\n\n private class BinarySearchTree, Value> extends chapter3.section2.BinarySearchTree{\n\n public Value get(Key key) {\n Node current = root;\n\n while (current != null) {\n int compare = key.compareTo(current.key);\n\n if (compare < 0) {\n current = current.left;\n } else if (compare > 0) {\n current = current.right;\n } else {\n return current.value;\n }\n }\n return null;\n }\n\n public void put(Key key, Value value) {\n // First pass to check if the key already exists\n Node current = root;\n\n while (current != null) {\n int compare = key.compareTo(current.key);\n\n if (compare < 0) {\n current = current.left;\n } else if (compare > 0) {\n current = current.right;\n } else {\n current.value = value;\n return;\n }\n }\n\n // Second pass\n // If we reached here, the key does not exist yet\n\n if (root == null) {\n root = new Node(key, value, 1);\n return;\n }\n\n current = root;\n\n while (true) {\n int compare = key.compareTo(current.key);\n current.size = current.size + 1;\n\n if (compare < 0) {\n\n if (current.left != null) {\n current = current.left;\n } else {\n current.left = new Node(key, value, 1);\n break;\n }\n } else if (compare > 0) {\n\n if (current.right != null) {\n current = current.right;\n } else {\n current.right = new Node(key, value, 1);\n break;\n }\n }\n }\n }\n }\n\n public static void main(String[] args) {\n Exercise13 exercise13 = new Exercise13();\n BinarySearchTree binarySearchTree = exercise13.new BinarySearchTree<>();\n\n // Test put()\n binarySearchTree.put(5, \"Value 5\");\n binarySearchTree.put(1, \"Value 1\");\n binarySearchTree.put(9, \"Value 9\");\n binarySearchTree.put(2, \"Value 2\");\n binarySearchTree.put(0, \"Value 0\");\n binarySearchTree.put(99, \"Value 99\");\n\n StdOut.println();\n\n // Test size()\n StdOut.println(\"Size: \" + binarySearchTree.size() + \" Expected: 6\");\n\n // Test get() and keys()\n for (Integer key : binarySearchTree.keys()) {\n StdOut.println(\"Key \" + key + \": \" + binarySearchTree.get(key));\n }\n\n // Test delete()\n StdOut.println(\"\\nDelete key 2\");\n binarySearchTree.delete(2);\n for (Integer key : binarySearchTree.keys()) {\n StdOut.println(\"Key \" + key + \": \" + binarySearchTree.get(key));\n }\n\n StdOut.println();\n\n // Test size()\n StdOut.println(\"Size: \" + binarySearchTree.size() + \" Expected: 5\");\n\n // Test min()\n StdOut.println(\"Min key: \" + binarySearchTree.min() + \" Expected: 0\");\n\n // Test max()\n StdOut.println(\"Max key: \" + binarySearchTree.max() + \" Expected: 99\");\n\n // Test floor()\n StdOut.println(\"Floor of 5: \" + binarySearchTree.floor(5) + \" Expected: 5\");\n StdOut.println(\"Floor of 15: \" + binarySearchTree.floor(15) + \" Expected: 9\");\n\n // Test ceiling()\n StdOut.println(\"Ceiling of 5: \" + binarySearchTree.ceiling(5) + \" Expected: 5\");\n StdOut.println(\"Ceiling of 15: \" + binarySearchTree.ceiling(15) + \" Expected: 99\");\n\n // Test select()\n StdOut.println(\"Select key of rank 4: \" + binarySearchTree.select(4) + \" Expected: 99\");\n\n // Test rank()\n StdOut.println(\"Rank of key 9: \" + binarySearchTree.rank(9) + \" Expected: 3\");\n StdOut.println(\"Rank of key 10: \" + binarySearchTree.rank(10) + \" Expected: 4\");\n\n // Test deleteMin()\n StdOut.println(\"\\nDelete min (key 0)\");\n\n binarySearchTree.deleteMin();\n for (Integer key : binarySearchTree.keys()) {\n StdOut.println(\"Key \" + key + \": \" + binarySearchTree.get(key));\n }\n\n // Test deleteMax()\n StdOut.println(\"\\nDelete max (key 99)\");\n\n binarySearchTree.deleteMax();\n for (Integer key : binarySearchTree.keys()) {\n StdOut.println(\"Key \" + key + \": \" + binarySearchTree.get(key));\n }\n\n // Test keys() with range\n StdOut.println();\n StdOut.println(\"Keys in range [2, 10]\");\n for (Integer key : binarySearchTree.keys(2, 10)) {\n StdOut.println(\"Key \" + key + \": \" + binarySearchTree.get(key));\n }\n\n StdOut.println(\"Size: \" + binarySearchTree.size() + \" Expected: 3\");\n }\n}\n", "support_files": [], "metadata": {"number": "3.2.13", "chapter": 3, "chapter_title": "Searching", "section": 3.2, "section_title": "Binary Search Trees", "type": "Exercise", "code_execution": false}} {"question": "Give nonrecursive implementations of min(), max(), floor(), ceiling(), rank(), and select().", "answer": "package chapter3.section2;\n\nimport edu.princeton.cs.algs4.Queue;\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.NoSuchElementException;\nimport java.util.Stack;\n\n/**\n * Created by Rene Argento on 31/05/17.\n */\npublic class Exercise14 {\n\n private class BinarySearchTree, Value> extends chapter3.section2.BinarySearchTree{\n\n public Key min() {\n if (root == null) {\n throw new NoSuchElementException(\"Empty binary search tree\");\n }\n\n Node current = root;\n\n while (current.left != null) {\n current = current.left;\n }\n\n return current.key;\n }\n\n //Used for the delete operation\n public Node min(Node current) {\n\n if (current == null) {\n return null;\n }\n\n while (current.left != null) {\n current = current.left;\n }\n\n return current;\n }\n\n public Key max() {\n if (root == null) {\n throw new NoSuchElementException(\"Empty binary search tree\");\n }\n\n Node current = root;\n\n while (current.right != null) {\n current = current.right;\n }\n\n return current.key;\n }\n\n public Key floor(Key key) {\n\n Node current = root;\n Key currentFloor = null;\n\n while (current != null) {\n int compare = key.compareTo(current.key);\n\n if (compare < 0) {\n current = current.left;\n } else if (compare > 0) {\n currentFloor = current.key;\n current = current.right;\n } else {\n currentFloor = current.key;\n break;\n }\n }\n\n return currentFloor;\n }\n\n public Key ceiling(Key key) {\n\n Node current = root;\n Key currentCeiling = null;\n\n while (current != null) {\n int compare = key.compareTo(current.key);\n\n if (compare < 0) {\n currentCeiling = current.key;\n current = current.left;\n } else if (compare > 0) {\n current = current.right;\n } else {\n currentCeiling = current.key;\n break;\n }\n }\n\n return currentCeiling;\n }\n\n public Key select(int index) {\n if (index >= size()) {\n throw new IllegalArgumentException(\"Index is higher than tree size\");\n }\n\n Node current = root;\n\n while (current != null) {\n int leftSubtreeSize = size(current.left);\n\n if (leftSubtreeSize == index) {\n return current.key;\n } else if (leftSubtreeSize > index) {\n current = current.left;\n } else {\n index -= (leftSubtreeSize + 1);\n current = current.right;\n }\n\n }\n\n return null;\n }\n\n public int rank(Key key) {\n Node current = root;\n\n int rank = 0;\n\n while (current != null) {\n int compare = key.compareTo(current.key);\n\n if (compare < 0) {\n current = current.left;\n } else if (compare > 0) {\n rank += size(current.left) + 1;\n current = current.right;\n } else {\n rank += size(current.left);\n return rank;\n }\n }\n\n return rank;\n }\n\n public Iterable keys() {\n Queue queue = new Queue<>();\n\n Stack stack = new Stack<>();\n\n Node current = root;\n\n while (current != null || !stack.isEmpty()) {\n if (current != null) {\n stack.push(current);\n current = current.left;\n } else {\n current = stack.pop();\n queue.enqueue(current.key);\n\n current = current.right;\n }\n }\n\n return queue;\n }\n\n }\n\n public static void main(String[] args) {\n Exercise14 exercise14 = new Exercise14();\n BinarySearchTree binarySearchTree = exercise14.new BinarySearchTree<>();\n\n // Test put()\n binarySearchTree.put(5, \"Value 5\");\n binarySearchTree.put(1, \"Value 1\");\n binarySearchTree.put(9, \"Value 9\");\n binarySearchTree.put(2, \"Value 2\");\n binarySearchTree.put(0, \"Value 0\");\n binarySearchTree.put(99, \"Value 99\");\n\n StdOut.println();\n\n // Test size()\n StdOut.println(\"Size: \" + binarySearchTree.size() + \" Expected: 6\");\n\n // Test get() and keys()\n for (Integer key : binarySearchTree.keys()) {\n StdOut.println(\"Key \" + key + \": \" + binarySearchTree.get(key));\n }\n\n // Test delete()\n StdOut.println(\"\\nDelete key 2\");\n binarySearchTree.delete(2);\n for (Integer key : binarySearchTree.keys()) {\n StdOut.println(\"Key \" + key + \": \" + binarySearchTree.get(key));\n }\n\n StdOut.println();\n\n // Test size()\n StdOut.println(\"Size: \" + binarySearchTree.size() + \" Expected: 5\");\n\n // Test min()\n StdOut.println(\"Min key: \" + binarySearchTree.min() + \" Expected: 0\");\n\n // Test max()\n StdOut.println(\"Max key: \" + binarySearchTree.max() + \" Expected: 99\");\n\n // Test floor()\n StdOut.println(\"Floor of 5: \" + binarySearchTree.floor(5) + \" Expected: 5\");\n StdOut.println(\"Floor of 15: \" + binarySearchTree.floor(15) + \" Expected: 9\");\n\n // Test ceiling()\n StdOut.println(\"Ceiling of 5: \" + binarySearchTree.ceiling(5) + \" Expected: 5\");\n StdOut.println(\"Ceiling of 15: \" + binarySearchTree.ceiling(15) + \" Expected: 99\");\n\n // Test select()\n StdOut.println(\"Select key of rank 4: \" + binarySearchTree.select(4) + \" Expected: 99\");\n\n // Test rank()\n StdOut.println(\"Rank of key 9: \" + binarySearchTree.rank(9) + \" Expected: 3\");\n StdOut.println(\"Rank of key 10: \" + binarySearchTree.rank(10) + \" Expected: 4\");\n\n // Test deleteMin()\n StdOut.println(\"\\nDelete min (key 0)\");\n\n binarySearchTree.deleteMin();\n for (Integer key : binarySearchTree.keys()) {\n StdOut.println(\"Key \" + key + \": \" + binarySearchTree.get(key));\n }\n\n //Test deleteMax()\n StdOut.println(\"\\nDelete max (key 99)\");\n\n binarySearchTree.deleteMax();\n for (Integer key : binarySearchTree.keys()) {\n StdOut.println(\"Key \" + key + \": \" + binarySearchTree.get(key));\n }\n\n //Test keys() with range\n StdOut.println();\n StdOut.println(\"Keys in range [2, 10]\");\n for (Integer key : binarySearchTree.keys(2, 10)) {\n StdOut.println(\"Key \" + key + \": \" + binarySearchTree.get(key));\n }\n\n StdOut.println(\"Size: \" + binarySearchTree.size() + \" Expected: 3\");\n }\n}\n", "support_files": [], "metadata": {"number": "3.2.14", "chapter": 3, "chapter_title": "Searching", "section": 3.2, "section_title": "Binary Search Trees", "type": "Exercise", "code_execution": false}} {"question": "Give the sequences of nodes examined when the methods in BST are used to compute each of the following quantities for this tree:\n\n```text\n E\n / \\\n D Q\n / \\\n J T\n \\ /\n M S\n```\n\na. floor(\"Q\")\nb. select(5)\nc. ceiling(\"Q\")\nd. rank(\"J\")\ne. size(\"D\", \"T\")\nf. keys(\"D\", \"T\")", "answer": "3.2.15\n\na. floor(\"Q\") - E Q\nb. select(5) - E Q\nc. ceiling(\"Q\") - E Q\nd. rank(\"J\") - E Q J\ne. size(\"D\", \"T\") - E D Q J M T S\nf. keys(\"D\", \"T\") - E D Q J M T S\n", "support_files": [], "metadata": {"number": "3.2.15", "chapter": 3, "chapter_title": "Searching", "section": 3.2, "section_title": "Binary Search Trees", "type": "Exercise", "code_execution": false}} {"question": "Draw the sequence of BSTs that results when you delete the keys from the tree of Exercise 3.2.1, one by one, in alphabetical order.", "answer": "3.2.18\n\nInitial tree\n E\n A S\n Q Y\n I U\n O T\n N\n\nDelete A\n E\n S\n Q Y\n I U\n O T\n N\n\nDelete E\n S\n Q Y\n I U\n O T\n N\n\nDelete I\n S\n Q Y\n O U\n N T\n\nDelete N\n S\n Q Y\n O U\n T\n\nDelete O\n S\n Q Y\n U\n T\n\nDelete Q\n S\n Y\n U\n T\n\nDelete S\n Y\n U\n T\n\nDelete T\n Y\n U\n\nDelete U\n Y\n\nDelete Y\n", "support_files": [], "metadata": {"number": "3.2.18", "chapter": 3, "chapter_title": "Searching", "section": 3.2, "section_title": "Binary Search Trees", "type": "Exercise", "code_execution": false}} {"question": "Prove that the running time of the two-argument keys() in a BST with N nodes is at most proportional to the tree height plus the number of keys in the range.", "answer": "3.2.20\n\nProposition: The running time of the two-argument keys() in a BST is at most proportional to the tree height plus the number of keys in the range.\n\nProof: The two-argument keys() method in a BST works in the following way:\n1- It searches the tree until it finds the element which is equal or higher than the lower bound.\n2- It adds the element to the queue and also adds all its right children that are inside the search range.\n3- It adds all the other elements which are inside the search range by doing an in-order search in the tree (but cutting branches once it finds elements outside the range).\n\nStep 1, searching the element which is equal or higher than the lower bound is a regular search in a BST and takes O(lg N) time, which is equal, in the worst case, to the tree height. Steps 2 and 3 combined take R operations, where R is the number of elements in the range searched. There may be a constant number of other compares, which are the cases where the method finds an element outside the range and stops the search on the current branch of the tree.\nCombining all the steps the two-argument keys() in a BST is at most proportional to the tree height plus the number of keys in the range.\n", "support_files": [], "metadata": {"number": "3.2.20", "chapter": 3, "chapter_title": "Searching", "section": 3.2, "section_title": "Binary Search Trees", "type": "Exercise", "code_execution": false}} {"question": "Add a BST method randomKey() that returns a random key from the symbol table in time proportional to the tree height, in the worst case.", "answer": "package chapter3.section2;\n\nimport edu.princeton.cs.algs4.StdOut;\nimport edu.princeton.cs.algs4.StdRandom;\n\n/**\n * Created by Rene Argento on 02/06/17.\n */\n// Thanks to Daniel Bedrenko (https://github.com/dbedrenko) for correcting and suggesting a better implementation\n// for this exercise: https://github.com/reneargento/algorithms-sedgewick-wayne/issues/19\n// Based on https://github.com/ChangeMyUsername/algorithms-sedgewick-python/blob/master/chapter_3/module_3_2.py\npublic class Exercise21 {\n\n private class BinarySearchTree, Value> extends chapter3.section2.BinarySearchTree {\n\n public Key randomKey() {\n if (isEmpty()) {\n return null;\n }\n\n int randomIndex = StdRandom.uniform(size());\n return select(randomIndex);\n }\n }\n\n public static void main(String[] args) {\n Exercise21 exercise21 = new Exercise21();\n BinarySearchTree binarySearchTree = exercise21.new BinarySearchTree<>();\n\n //Test put()\n binarySearchTree.put(5, \"Value 5\");\n binarySearchTree.put(1, \"Value 1\");\n binarySearchTree.put(9, \"Value 9\");\n binarySearchTree.put(2, \"Value 2\");\n binarySearchTree.put(0, \"Value 0\");\n binarySearchTree.put(99, \"Value 99\");\n\n //Test size()\n StdOut.println(\"Size: \" + binarySearchTree.size() + \" Expected: 6\\n\");\n\n //Test get() and keys()\n for (Integer key : binarySearchTree.keys()) {\n StdOut.println(\"Key \" + key + \": \" + binarySearchTree.get(key));\n }\n\n StdOut.println(\"\\nRandom keys:\");\n StdOut.println(binarySearchTree.randomKey());\n StdOut.println(binarySearchTree.randomKey());\n StdOut.println(binarySearchTree.randomKey());\n StdOut.println(binarySearchTree.randomKey());\n StdOut.println(binarySearchTree.randomKey());\n StdOut.println(binarySearchTree.randomKey());\n }\n\n}\n", "support_files": [], "metadata": {"number": "3.2.21", "chapter": 3, "chapter_title": "Searching", "section": 3.2, "section_title": "Binary Search Trees", "type": "Exercise", "code_execution": false}} {"question": "Is delete() commutative? (Does deleting x, then y give the same result as deleting y, then x?)", "answer": "3.2.23\n\nNo, delete() is not commutative.\n\nCounterexample: \nTree:\n A\n B D\n C \n\n1- Delete A, then B\n C\n B D \n\n C\n D\n\n2- Delete B, then A\n A\n D\n C \n\n D\n C\n\nThanks to faame (https://github.com/faame) for reporting an issue with the counterexample.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/230\n", "support_files": [], "metadata": {"number": "3.2.23", "chapter": 3, "chapter_title": "Searching", "section": 3.2, "section_title": "Binary Search Trees", "type": "Exercise", "code_execution": false}} {"question": "Memory usage. Compare the memory usage of BST with the memory usage of BinarySearchST and SequentialSearchST for N key-value pairs, under the assumptions described in Section 1.4 (see Exercise 3.1.21). Do not count the memory for the keys and values themselves, but do count references to them. Then draw a diagram that depicts the precise memory usage of a BST with String keys and Integer values (such as the ones built by FrequencyCounter), and then estimate the memory usage (in bytes) for the BST built when FrequencyCounter uses BST for Tale of Two Cities.", "answer": "3.2.27 - Memory usage\n\n* BST\n object overhead -> 16 bytes\n Node reference (root) -> 8 bytes\n Node\n object overhead -> 16 bytes\n extra overhead for reference to the enclosing instance -> 8 bytes\n Key reference (key) -> 8 bytes\n Value reference (value) -> 8 bytes\n Node reference (left) -> 8 bytes\n Node reference (right) -> 8 bytes\n int value (size) -> 4 bytes\n padding -> 4 bytes\n (N Node references -> 64N bytes)\nAmount of memory needed: 16 + 8 + (16 + 8 + 8 + 8 + 8 + 8 + 4 + 4)N = 64N + 24 bytes\n\n* BinarySearchST\n object overhead -> 16 bytes\n Key[] reference (keys) -> 8 bytes\n Value[] reference (values) -> 8 bytes\n int value (size) -> 4 bytes\n padding -> 4 bytes\n Key[]\n object overhead -> 16 bytes\n int value (length) -> 4 bytes\n padding -> 4 bytes\n N Key references -> between 8N and 32N bytes (the resizing array may be 25% to 100% full)\n Value[]\n object overhead -> 16 bytes\n int value (length) -> 4 bytes\n padding -> 4 bytes\n N Value references -> between 8N and 32N bytes (the resizing array may be 25% to 100% full)\nAmount of memory needed: 16 + 8 + 8 + 4 + 4 + 16 + 4 + 4 + (8N to 32N) + 16 + 4 + 4 + (8N to 32N) = (16N to 64N) + 88 bytes\n\n* SequentialSearchST\n object overhead -> 16 bytes\n Node reference (first) -> 8 bytes\n Node\n object overhead -> 16 bytes\n extra overhead for reference to the enclosing instance -> 8 bytes\n Key reference (key) -> 8 bytes\n Value reference (value) -> 8 bytes\n Node reference (next) -> 8 bytes\n (N Node references -> 48N bytes)\n int value (size) -> 4 bytes\n padding -> 4 bytes\nAmount of memory needed: 16 + 8 + (16 + 8 + 8 + 8 + 8)N + 4 + 4 = 48N + 32 bytes\n\n\nString object (Java 7 and later) = 56 + 2C bytes, where C is the number of characters in its char[] array\nInteger object = 24 bytes\n\nMemory usage of a BST with String keys and Integer values: 64N + 24 bytes (BST) + (56 + 2C bytes + 24 bytes) * N\n= 64N + 24 + (80 + 2C) * N bytes = 2CN + 144N + 24 bytes\n\nDiagram\n\nAssuming an average of 5 characters per String, the BST uses 2CN + 144N + 24 = 10N + 144N + 24 = 154N + 24 bytes\n\n Memory usage (bytes)\n 15,400,024 | *\n 154,024 | *\n 15,424 | *\n -------------------------------------------------------------\nNumber of keys/values 0 100 1000 100000\n\nFor FrequencyCounter, `N` in the BST formula must be the number of distinct keys, not the total number of word occurrences. If `D` is the number of distinct words and `C` is the average number of characters in those distinct words, the BST memory estimate including String keys and Integer values is:\n\n`64D + 24 + (56 + 2C + 24)D = (144 + 2C)D + 24` bytes.\n\nFor example, if the distinct keys average 6 characters, the estimate is `156D + 24` bytes. Do not multiply by the total word count unless every word occurrence is a distinct key.\n", "support_files": [], "metadata": {"number": "3.2.27", "chapter": 3, "chapter_title": "Searching", "section": 3.2, "section_title": "Binary Search Trees", "type": "Creative Problem", "code_execution": false}} {"question": "Equal key check. Write a method hasNoDuplicates() that takes a Node as argument and returns true if there are no equal keys in the binary tree rooted at the argument node, false otherwise. Assume that the test of the previous exercise has passed.", "answer": "Since the previous order check has passed, an inorder traversal visits equal keys consecutively. Keep the previous key seen during that traversal and fail as soon as the same key appears twice.\n\n```java\nprivate Key previousKey;\n\npublic boolean hasNoDuplicates(Node x) {\n previousKey = null;\n return hasNoDuplicatesInOrder(x);\n}\n\nprivate boolean hasNoDuplicatesInOrder(Node x) {\n if (x == null) {\n return true;\n }\n\n if (!hasNoDuplicatesInOrder(x.left)) {\n return false;\n }\n\n if (previousKey != null && x.key.compareTo(previousKey) == 0) {\n return false;\n }\n previousKey = x.key;\n\n return hasNoDuplicatesInOrder(x.right);\n}\n```\n\nThe traversal is linear in the number of nodes and uses space proportional to the tree height, aside from the one saved key.", "support_files": [], "metadata": {"number": "3.2.31", "chapter": 3, "chapter_title": "Searching", "section": 3.2, "section_title": "Binary Search Trees", "type": "Creative Problem", "code_execution": false}} {"question": "Certification. Write a method isBST() that takes a Node as argument and returns true if the argument node is the root of a binary search tree, false otherwise. Hint: This task is also more difficult than it might seem, because the order in which you call the methods in the previous three exercises is important.", "answer": "The certification should compose the three preceding checks in the order required by their preconditions: first verify that subtree counts describe a binary tree, then verify ordering, then run the duplicate-key check that assumes the keys are already in inorder order.\n\n```java\npublic boolean isBST(Node x) {\n if (x == null) {\n return true;\n }\n if (!isBinaryTree(x)) {\n return false;\n }\n if (!isOrdered(x, minKey(x), maxKey(x))) {\n return false;\n }\n return hasNoDuplicates(x);\n}\n\nprivate boolean isBinaryTree(Node x) {\n if (x == null) {\n return true;\n }\n\n int leftSize = x.left == null ? 0 : x.left.N;\n int rightSize = x.right == null ? 0 : x.right.N;\n\n if (x.N != leftSize + rightSize + 1) {\n return false;\n }\n return isBinaryTree(x.left) && isBinaryTree(x.right);\n}\n\nprivate boolean isOrdered(Node x, Key min, Key max) {\n if (x == null) {\n return true;\n }\n if (x.key.compareTo(min) < 0 || x.key.compareTo(max) > 0) {\n return false;\n }\n return isOrdered(x.left, min, x.key) && isOrdered(x.right, x.key, max);\n}\n\nprivate Key minKey(Node x) {\n Key min = x.key;\n if (x.left != null) {\n Key leftMin = minKey(x.left);\n if (leftMin.compareTo(min) < 0) {\n min = leftMin;\n }\n }\n if (x.right != null) {\n Key rightMin = minKey(x.right);\n if (rightMin.compareTo(min) < 0) {\n min = rightMin;\n }\n }\n return min;\n}\n\nprivate Key maxKey(Node x) {\n Key max = x.key;\n if (x.left != null) {\n Key leftMax = maxKey(x.left);\n if (leftMax.compareTo(max) > 0) {\n max = leftMax;\n }\n }\n if (x.right != null) {\n Key rightMax = maxKey(x.right);\n if (rightMax.compareTo(max) > 0) {\n max = rightMax;\n }\n }\n return max;\n}\n```\n\nThis catches bad subtree counts, keys outside the allowed range, and equal keys. The order matters because `hasNoDuplicates()` relies on the inorder sequence being sorted.", "support_files": [], "metadata": {"number": "3.2.32", "chapter": 3, "chapter_title": "Searching", "section": 3.2, "section_title": "Binary Search Trees", "type": "Creative Problem", "code_execution": false}} {"question": "Select/rank check. Write a method 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)).", "answer": "package chapter3.section2;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 04/06/17.\n */\npublic class Exercise33_SelectRankCheck {\n\n private boolean checkRankAndSelect(BinarySearchTree binarySearchTree) {\n int size = binarySearchTree.size();\n\n //Check rank\n for (int i = 0; i < size; i++) {\n if (i != binarySearchTree.rank(binarySearchTree.select(i))) {\n return false;\n }\n }\n\n //Check select\n for (Integer key : binarySearchTree.keys()) {\n if (key.compareTo(binarySearchTree.select(binarySearchTree.rank(key))) != 0) {\n return false;\n }\n }\n return true;\n }\n\n public static void main(String[] args) {\n BinarySearchTree binarySearchTree = new BinarySearchTree<>();\n binarySearchTree.put(10, \"Value 10\");\n binarySearchTree.put(4, \"Value 4\");\n binarySearchTree.put(6, \"Value 6\");\n binarySearchTree.put(1, \"Value 1\");\n binarySearchTree.put(15, \"Value 15\");\n binarySearchTree.put(12, \"Value 12\");\n binarySearchTree.put(20, \"Value 20\");\n binarySearchTree.put(25, \"Value 25\");\n\n Exercise33_SelectRankCheck selectRankCheck = new Exercise33_SelectRankCheck();\n StdOut.println(selectRankCheck.checkRankAndSelect(binarySearchTree) + \" Expected: true\");\n }\n}\n", "support_files": [], "metadata": {"number": "3.2.33", "chapter": 3, "chapter_title": "Searching", "section": 3.2, "section_title": "Binary Search Trees", "type": "Creative Problem", "code_execution": false}} {"question": "Threading. Your goal is to support an extended API ThreadedST that supports the following additional operations in constant time:\nKey next(Key key) key that follows key (null if key is the maximum)\nKey prev(Key key) key that precedes key (null if key is the minimum)\nTo do so, add fields pred and succ to Node that contain links to the predecessor and successor nodes, and modify put(), deleteMin(), deleteMax(), and delete() to maintain these fields.", "answer": "package chapter3.section2;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 04/06/17.\n */\n@SuppressWarnings(\"unchecked\")\npublic class Exercise34_Threading {\n\n private class DoublyThreadedBST, Value> extends BinarySearchTree {\n\n private class Node {\n\n private Key key;\n private Value value;\n\n private Node left;\n private Node right;\n\n private int size; //# of nodes in subtree rooted here\n\n private Node pred;\n private Node succ;\n\n public Node(Key key, Value value, int size) {\n this.key = key;\n this.value = value;\n this.size = size;\n }\n }\n\n private Node root;\n\n public int size() {\n return size(root);\n }\n\n private int size(Node node) {\n if (node == null) {\n return 0;\n }\n\n return node.size;\n }\n\n public Key next(Key key) {\n if (key == null) {\n return null;\n }\n\n Node current = root;\n while (current != null) {\n\n int compare = key.compareTo(current.key);\n\n if (compare < 0) {\n current = current.left;\n } else if (compare > 0) {\n current = current.right;\n } else {\n if (current.succ != null) {\n return current.succ.key;\n } else {\n return null;\n }\n }\n }\n\n return null;\n }\n\n public Key prev(Key key) {\n if (key == null) {\n return null;\n }\n\n Node current = root;\n while (current != null) {\n\n int compare = key.compareTo(current.key);\n\n if (compare < 0) {\n current = current.left;\n } else if (compare > 0) {\n current = current.right;\n } else {\n if (current.pred != null) {\n return current.pred.key;\n } else {\n return null;\n }\n }\n }\n\n return null;\n }\n\n //Used by delete() method\n private Node min(Node node) {\n if (node.left == null) {\n return node;\n }\n\n return min(node.left);\n }\n\n @Override\n public void put(Key key, Value value) {\n root = put(root, key, value, null, null);\n }\n\n private Node put(Node node, Key key, Value value, Node predecessor, Node successor) {\n if (node == null) {\n Node newNode = new Node(key, value, 1);\n\n if (predecessor != null) {\n predecessor.succ = newNode;\n newNode.pred = predecessor;\n }\n if (successor != null) {\n newNode.succ = successor;\n successor.pred = newNode;\n }\n\n return newNode;\n }\n\n int compare = key.compareTo(node.key);\n\n if (compare < 0) {\n node.left = put(node.left, key, value, predecessor, node);\n } else if (compare > 0) {\n node.right = put(node.right, key, value, node, successor);\n } else {\n node.value = value;\n }\n\n node.size = size(node.left) + 1 + size(node.right);\n return node;\n }\n\n public void deleteMin() {\n root = deleteMin(root, true);\n }\n\n //updatePredAndSucc parameter is used because we don't want to update pred and succ fields\n // when using deleteMin() inside delete()\n private Node deleteMin(Node node, boolean updatePredAndSucc) {\n if (node == null) {\n return null;\n }\n\n if (node.left == null) {\n if (updatePredAndSucc && node.succ != null) {\n node.succ.pred = null;\n }\n\n return node.right;\n }\n\n node.left = deleteMin(node.left, updatePredAndSucc);\n node.size = size(node.left) + 1 + size(node.right);\n return node;\n }\n\n public void deleteMax() {\n root = deleteMax(root);\n }\n\n private Node deleteMax(Node node) {\n if (node == null) {\n return null;\n }\n\n if (node.right == null) {\n if (node.pred != null) {\n node.pred.succ = null;\n }\n\n return node.left;\n }\n\n node.right = deleteMax(node.right);\n node.size = size(node.left) + 1 + size(node.right);\n return node;\n }\n\n public void delete(Key key) {\n root = delete(root, key);\n }\n\n private Node delete(Node node, Key key) {\n if (node == null) {\n return null;\n }\n\n int compare = key.compareTo(node.key);\n if (compare < 0) {\n node.left = delete(node.left, key);\n } else if (compare > 0) {\n node.right = delete(node.right, key);\n } else {\n if (node.left == null || node.right == null) {\n\n if (node.pred != null) {\n node.pred.succ = node.succ;\n }\n if (node.succ != null) {\n node.succ.pred = node.pred;\n }\n\n if (node.left == null) {\n return node.right;\n } else if (node.right == null) { //Always true when we get here, but leaving it here for legibility\n return node.left;\n }\n } else {\n Node aux = node;\n node = min(aux.right);\n node.right = deleteMin(aux.right, false);\n node.left = aux.left;\n\n node.pred = aux.pred;\n if (node.pred != null) {\n node.pred.succ = node;\n }\n //The deleted node's successor's (the new root of this subtree) pred and succ fields were already updated\n }\n }\n\n node.size = size(node.left) + 1 + size(node.right);\n return node;\n }\n\n }\n\n public static void main(String[] args) {\n Exercise34_Threading threading = new Exercise34_Threading();\n\n DoublyThreadedBST binarySearchTree = threading.new DoublyThreadedBST<>();\n binarySearchTree.put(10, \"Value 10\");\n binarySearchTree.put(4, \"Value 4\");\n binarySearchTree.put(6, \"Value 6\");\n binarySearchTree.put(1, \"Value 1\");\n binarySearchTree.put(2, \"Value 2\");\n binarySearchTree.put(15, \"Value 15\");\n binarySearchTree.put(12, \"Value 12\");\n binarySearchTree.put(20, \"Value 20\");\n binarySearchTree.put(25, \"Value 25\");\n\n //Test put()\n StdOut.println(\"Predecessor of 1: \" + binarySearchTree.prev(1) + \" Expected: null\");\n StdOut.println(\"Predecessor of 6: \" + binarySearchTree.prev(6) + \" Expected: 4\");\n StdOut.println(\"Predecessor of 10: \" + binarySearchTree.prev(10) + \" Expected: 6\");\n StdOut.println(\"Predecessor of 25: \" + binarySearchTree.prev(25) + \" Expected: 20\");\n StdOut.println(\"Successor of 1: \" + binarySearchTree.next(1) + \" Expected: 2\");\n StdOut.println(\"Successor of 6: \" + binarySearchTree.next(6) + \" Expected: 10\");\n StdOut.println(\"Successor of 12: \" + binarySearchTree.next(12) + \" Expected: 15\");\n StdOut.println(\"Successor of 25: \" + binarySearchTree.next(25) + \" Expected: null\");\n\n StdOut.println();\n\n //Test deleteMin()\n StdOut.println(\"Predecessor of 2: \" + binarySearchTree.prev(2) + \" Expected: 1\");\n binarySearchTree.deleteMin();\n StdOut.println(\"Predecessor of 2 after deleteMin(): \" + binarySearchTree.prev(2) + \" Expected: null\");\n\n StdOut.println();\n\n //Test deleteMax()\n StdOut.println(\"Successor of 20: \" + binarySearchTree.next(20) + \" Expected: 25\");\n binarySearchTree.deleteMax();\n StdOut.println(\"Successor of 20 after deleteMax(): \" + binarySearchTree.next(20) + \" Expected: null\");\n\n StdOut.println();\n\n //Test delete()\n StdOut.println(\"Predecessor of 20: \" + binarySearchTree.prev(20) + \" Expected: 15\");\n StdOut.println(\"Successor of 12: \" + binarySearchTree.next(12) + \" Expected: 15\");\n binarySearchTree.delete(15);\n StdOut.println(\"Predecessor of 20 after delete(15): \" + binarySearchTree.prev(20) + \" Expected: 12\");\n StdOut.println(\"Successor of 12 after delete(15): \" + binarySearchTree.next(12) + \" Expected: 20\");\n\n StdOut.println();\n\n StdOut.println(\"Predecessor of 12: \" + binarySearchTree.prev(12) + \" Expected: 10\");\n StdOut.println(\"Successor of 6: \" + binarySearchTree.next(6) + \" Expected: 10\");\n binarySearchTree.delete(10);\n StdOut.println(\"Predecessor of 12 after delete(10): \" + binarySearchTree.prev(12) + \" Expected: 6\");\n StdOut.println(\"Successor of 6 after delete(10): \" + binarySearchTree.next(6) + \" Expected: 12\");\n\n StdOut.println();\n\n StdOut.println(\"Predecessor of 4: \" + binarySearchTree.prev(4) + \" Expected: 2\");\n binarySearchTree.delete(2);\n StdOut.println(\"Predecessor of 4 after delete(2): \" + binarySearchTree.prev(4) + \" Expected: null\");\n\n StdOut.println(\"Successor of 12: \" + binarySearchTree.next(12) + \" Expected: 20\");\n binarySearchTree.delete(20);\n StdOut.println(\"Successor of 12 after delete(20): \" + binarySearchTree.next(12) + \" Expected: null\");\n }\n\n}\n", "support_files": [], "metadata": {"number": "3.2.34", "chapter": 3, "chapter_title": "Searching", "section": 3.2, "section_title": "Binary Search Trees", "type": "Creative Problem", "code_execution": false}} {"question": "Refined analysis. Refine the mathematical model to better explain the experimental results in the table given in the text. Specifically, show that the average number of compares for a successful search in a tree built from random keys approaches the limit 2 ln N + 2γ - 3 ≈ 1.39 lg N – 1.85 as N increases, where γ ≈ .57721... is Euler’s constant. Hint: Referring to the quicksort analysis in Section 2.3, use the fact that the integral of 1/x approaches ln N + γ.", "answer": "3.2.35 - Refined analysis\n\nProposition: The average number of compares for a successful search in a tree built from N random keys approaches the limit 2ln N + 2y - 3 ~= 1.39 lg N - 1.85 as N increases, where y = .57721... is Euler's constant.\n\nProof: \nThe number of compares used for a search hit ending at a given node is 1 plus the depth. Adding the depths of all nodes, we get a quantity known as the internal path length of the tree. Thus, the desired quantity is 1 plus the average internal path length of the BST, which we can analyze as follows:\nLet Cn be the internal path length of a BST built from inserting N randomly ordered distinct keys, so that the average cost of a search hit is 1 + Cn / N.\nWe have C0 = C1 = 0 and for N > 1 we can write a recurrence relationship that directly mirrors the recursive BST structure:\nCn = N - 1 + (C0 + Cn-1) / N + (C1 + Cn-2) / N + ... + (Cn-1 + C0) / N\nThe N - 1 term takes into account that the root contributes 1 to the path length of each of the other N - 1 nodes in the tree; the rest of the expression accounts for the subtrees, which are equally likely to be any of the N sizes. \n\nMultiplying by N and collecting terms transforms this equation into:\nNCn = N(N - 1) + 2(C0 + C1 + ... + Cn-2 + Cn-1)\nSubtracting the same equation for N - 1 from this equation gives\nNCn - (N - 1)Cn-1 = 2N - 2 + 2Cn-1\nRearranging terms and dividing by N(N + 1) leaves\nCn / (N + 1) = Cn-1 / N + 2 / (N + 1) - 2 / (N (N + 1))\nwhich telescopes to give the result\nCn ~ 2(N + 1) * (1/3 + 1/4 + ... + 1/(N + 1) - 2)\n\nThe parenthesized quantity is the discrete estimate of the area under the curve 1/x from 3 to N + 1. By integration, 1/x approaches ln N + y.\nSo we have:\nCn ~ 2(N + 1) * (ln N + y - 2)\nCn ~ (2N + 2) * (ln N + y - 2)\nCn ~ 2N ln N + 2N y - 4N + 2ln N + 2y - 4\n\nAs mentioned before, the average cost of a search hit is:\nAVG Cost of Search Hit = 1 + Cn / N\n\nReplacing Cn with 2N ln N + 2N y - 4N + 2ln N + 2y - 4 we have:\nAVG Cost of Search Hit = 1 + (2N ln N + 2N y - 4N + 2ln N + 2y - 4) / N\nAVG Cost of Search Hit = 1 + 2 ln N + 2y + 2y/N - 4 - 4/N\n\nSince 2 ln N ~ 1.39 lg N this gives the following approximation as N increases\nAVG Cost of Search Hit ~ 1.39 lg N + 2y - 3\nReplacing y with .57721\nAVG Cost of Search Hit ~ 1.39 lg N + 1.154 - 3\nAVG Cost of Search Hit ~ 1.39 lg N - 1.85\n", "support_files": [], "metadata": {"number": "3.2.35", "chapter": 3, "chapter_title": "Searching", "section": 3.2, "section_title": "Binary Search Trees", "type": "Creative Problem", "code_execution": false}} {"question": "Iterator. Is it possible to write a nonrecursive version of keys() that uses space proportional to the tree height (independent of the number of keys in the range)?", "answer": "3.2.36 - Iterator\n\nYes, it is possible to write a nonrecursive version of keys() that uses space proportional to the tree height (independent of the number of keys in the range).\n\nThis can be done using a stack. \n1- Add the root of the tree and all of its left children on the stack (as long as they are in the searched range).\n2- If the stack is not empty: Pop the top element, print it, set the current element as the printed element's right child (if it is not null -if it is, repeat this step).\n3- Add the right child (if it is in the searched range) and all of its left children (as long as they are in the searched range) on the stack.\n4- Repeat steps 2 and 3 until the stack is empty or all the range has been printed.\n", "support_files": [], "metadata": {"number": "3.2.36", "chapter": 3, "chapter_title": "Searching", "section": 3.2, "section_title": "Binary Search Trees", "type": "Creative Problem", "code_execution": false}} {"question": "Level-order traversal. Write a method printLevel() that takes a Node as argument and prints the keys in the subtree rooted at that node in level order (in order of their distance from the root, with nodes on each level in order from left to right). Hint: Use a Queue.", "answer": "package chapter3.section2;\n\nimport edu.princeton.cs.algs4.Queue;\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 10/06/17.\n */\npublic class Exercise37_LevelOrderTraversal {\n\n private void printLevel(BinarySearchTree.Node node) {\n Queue queue = new Queue<>();\n queue.enqueue(node);\n\n while (!queue.isEmpty()) {\n BinarySearchTree.Node current = queue.dequeue();\n StdOut.print(current.key + \" \");\n\n if (current.left != null) {\n queue.enqueue(current.left);\n }\n if (current.right != null) {\n queue.enqueue(current.right);\n }\n }\n }\n\n public static void main(String[] args) {\n Exercise37_LevelOrderTraversal levelOrderTraversal = new Exercise37_LevelOrderTraversal();\n\n /**\n * 10\n * 4 15\n * 1 6 12 20\n * 2 25\n */\n\n BinarySearchTree binarySearchTree = new BinarySearchTree<>();\n binarySearchTree.put(10, \"Value 10\");\n binarySearchTree.put(4, \"Value 4\");\n binarySearchTree.put(6, \"Value 6\");\n binarySearchTree.put(1, \"Value 1\");\n binarySearchTree.put(2, \"Value 2\");\n binarySearchTree.put(15, \"Value 15\");\n binarySearchTree.put(12, \"Value 12\");\n binarySearchTree.put(20, \"Value 20\");\n binarySearchTree.put(25, \"Value 25\");\n\n levelOrderTraversal.printLevel(binarySearchTree.root);\n StdOut.println(\"\\nExpected: 10 4 15 1 6 12 20 2 25\");\n }\n\n}\n", "support_files": [], "metadata": {"number": "3.2.37", "chapter": 3, "chapter_title": "Searching", "section": 3.2, "section_title": "Binary Search Trees", "type": "Creative Problem", "code_execution": false}} {"question": "Find the probability that each of the 2-3 trees in Exercise 3.3.5 is the result of the insertion of N random distinct keys into an initially empty tree.\n\nExercise 3.3.5 trees:\n\n```text\n3.3.5\n\nN = 7\n\n ( )\n () ( ) ( )\n\n ()\n () ()\n() () () ()\n\nN = 8\n\n ( )\n( ) ( ) ( )\n\n ()\n () ()\n() () () ( )\n\nN = 9\n\n ()\n () ()\n( ) ( ) () ()\n\n ()\n () ( )\n() () () () ()\n\nN = 10\n\n ()\n () ()\n( ) ( ) ( ) ()\n\n ()\n ( ) ()\n( ) () () () ()\n\n ()\n () ( )\n( ) () () () ()\n```", "answer": "3.3.6\n\nN = 7\n\n ( )\n () ( ) ( )\n\nProbability of this tree being the result: 4 / 7 = 0.57\n\n ()\n () ()\n() () () ()\n\nProbability of this tree being the result: 3 / 7 = 0.43\n\nN = 8\n\n ( )\n( ) ( ) ( )\n\nProbability of this tree being the result: (4 / 7) * (2 / 8) = 1 / 7 = 0.14\n\n ()\n () ()\n() () () ( )\n\nProbability of this tree being the result: (4 / 7) * (6 / 8) + 3 / 7 = 6 / 7 = 0.86\n\nN = 9\n\n ()\n () ()\n( ) ( ) () ()\n\nProbability of this tree being the result: (1 / 7) * (6 / 9) + (6 / 7) * (2 / 9) = 2 / 7 = 0.29\n\n ()\n () ()\n( ) () () ( )\n\nProbability of this tree being the result: (1 / 7) * (3 / 9) + (6 / 7) * (4 / 9) = 3 / 7 = 0.43\n\n ()\n () ( )\n() () () () ()\n\nProbability of this tree being the result: (6 / 7) * (3 / 9) = 2 / 7 = 0.29\n\nN = 10\n\n ()\n () ()\n( ) ( ) ( ) ()\n\nProbability of this tree being the result: (2 / 7) * (4 / 10) + (3 / 7) * (4 / 10) = 2 / 7 = 0.29\n\n ()\n ( ) ()\n( ) () () () ()\n\nProbability of this tree being the result: (2 / 7) * (6 / 10) + (2 / 7) * (6 / 10) = 0.34\n\n ()\n ( ) ()\n() () () ( ) ()\n\nProbability of this tree being the result: (3 / 7) * (6 / 10) + (2 / 7) * (4 / 10) = 0.37\n\n// Thanks to Oreshnik (https://github.com/Oreshnik) for mentioning more tree structures and fixing an issue in the probability computation for trees with N = 9.\n// https://github.com/reneargento/algorithms-sedgewick-wayne/pull/74\n", "support_files": [], "metadata": {"number": "3.3.6", "chapter": 3, "chapter_title": "Searching", "section": 3.3, "section_title": "Balanced Search Trees", "type": "Exercise", "code_execution": false}} {"question": "Draw diagrams like the one at the top of page 428 for the other five cases in the bottom diagram on that page. Use keys in sorted order `a < b < c < d < e`, and cover these insertion cases:\n\n1. insertion into the root 3-node,\n2. insertion into the left child of a 2-node parent,\n3. insertion into the right child of a 2-node parent,\n4. insertion into the left child of a 3-node parent,\n5. insertion into the middle child of a 3-node parent,\n6. insertion into the right child of a 3-node parent.", "answer": "3.3.7\n\n1- root\n abc\nless than a between a and b between b and c greater than c\n\n b\n a c\nless than a between a and b between b and c greater than c\n\n2- parent is a 2-node (left)\n d\n abc greater than d\nless than a between a and b between b and c between c and d\n\n bd\n a c greater than d\nless than a between a and b between b and c between c and d\n\n3- parent is a 2-node (right)\n a\n less than a bcd\n between a and b between b and c between c and d greater than d\n\n ac\n less than a b d\n between a and b between b and c between c and d greater than d\n\n4- parent is a 3-node (left)\n de\n abc between d and e greater than e\nless than a between a and b between b and c between c and d\n\n bde\n a c between d and e greater than e\nless than a between a and b between b and c between c and d\n\n5- parent is a 3-node (right)\n ab\n less than a between a and b cde\n between b and c between c and d between d and e greater than e\n\n abd\n less than a between a and b c e\n between b and c between c and d between d and e greater than e\n", "support_files": [], "metadata": {"number": "3.3.7", "chapter": 3, "chapter_title": "Searching", "section": 3.3, "section_title": "Balanced Search Trees", "type": "Exercise", "code_execution": false}} {"question": "Show all possible ways that one might represent a 4-node with three 2-nodes bound together with red links (not necessarily left-leaning).", "answer": "3.3.8\n\nUnique representations (not considering the order of the nodes):\n\n A\n B\n C\n\n A\n C\n B\n\n B\n A C\n\n C\n A\n B\n\n C\n B\n A\n", "support_files": [], "metadata": {"number": "3.3.8", "chapter": 3, "chapter_title": "Searching", "section": 3.3, "section_title": "Balanced Search Trees", "type": "Exercise", "code_execution": false}} {"question": "Which of the following candidate trees are red-black BSTs?\n\nThe candidates are the four textbook diagrams (i)–(iv) from Exercise 3.3.9 (Sedgewick & Wayne, Section 3.3). Identify which are valid red-black BSTs and briefly justify your answer.", "answer": "3.3.9\n\n(iii) and (iv)\n\n(i) is not balanced\n(ii) is not ordered (F cannot be on the left side of E)\n", "support_files": [], "metadata": {"number": "3.3.9", "chapter": 3, "chapter_title": "Searching", "section": 3.3, "section_title": "Balanced Search Trees", "type": "Exercise", "code_execution": false}} {"question": "Draw the red-black BST that results when you insert items with the keys E A S Y Q U T I O N in that order into an initially empty tree.", "answer": "3.3.10\n\nInsert E (B)E\n\n A (B)E\n (R)A\n\n S (B)E\n (R)A (R)S\n\n S (R)E\n (B)A (B)S\n\n S (B)E\n (B)A (B)S\n\n Y (B)E\n (B)A (B)S\n (R)Y\n\n Y (B)E\n (B)A (B)Y\n (R)S\n\n Q (B)E\n (B)A (B)Y\n (R)S\n (R)Q\n\n Q (B)E\n (B)A (B)S\n (R)Q (R)Y\n\n Q (B)E\n (B)A (R)S\n (B)Q (B)Y\n\n Q (B)S\n (R)E (B)Y\n (B)A (B)Q\n\n U (B)S\n (R)E (B)Y\n (B)A (B)Q (R)U\n\n T (B)S\n (R)E (B)Y\n (B)A (B)Q (R)U\n (R)T\n\n T (B)S\n (R)E (B)U\n (B)A (B)Q (R)T (R)Y\n\n T (B)S\n (R)E (R)U\n (B)A (B)Q (B)T (B)Y\n \n T (R)S\n (B)E (B)U\n (B)A (B)Q (B)T (B)Y\n\n T (B)S\n (B)E (B)U\n (B)A (B)Q (B)T (B)Y\n\n I (B)S\n (B)E (B)U\n (B)A (B)Q (B)T (B)Y\n (R)I\n\n O (B)S\n (B)E (B)U\n (B)A (B)Q (B)T (B)Y\n (R)I\n (R)O\n\n O (B)S\n (B)E (B)U\n (B)A (B)Q (B)T (B)Y\n (R)O\n (R)I\n\n O (B)S\n (B)E (B)U\n (B)A (B)O (B)T (B)Y\n (R)I (R)Q\n \n O (B)S\n (B)E (B)U\n (B)A (R)O (B)T (B)Y\n (B)I (B)Q\n\n O (B)S\n (B)O (B)U\n (R)E (B)Q (B)T (B)Y\n (B)A (B)I \n\n N (B)S\n (B)O (B)U\n (R)E (B)Q (B)T (B)Y\n (B)A (B)I \n (R)N\n\n N (B)S\n (B)O (B)U\n (R)E (B)Q (B)T (B)Y\n (B)A (B)N \n (R)I\n", "support_files": [], "metadata": {"number": "3.3.10", "chapter": 3, "chapter_title": "Searching", "section": 3.3, "section_title": "Balanced Search Trees", "type": "Exercise", "code_execution": false}} {"question": "Draw the red-black BST that results when you insert items with the keys Y L P M X H C R A E S in that order into an initially empty tree.", "answer": "3.3.11\n\nInsert Y (B)Y\n\n L (B)Y\n (R)L\n\n P (B)Y\n (R)L\n (R)P\n\n P (B)Y\n (R)P\n (R)L\n\n P (B)P\n (R)L (R)Y\n \n P (R)P\n (B)L (B)Y\n\n P (B)P\n (B)L (B)Y\n\n M (B)P\n (B)L (B)Y\n (R)M\n\n M (B)P\n (B)M (B)Y\n (R)L \n\n X (B)P\n (B)M (B)Y\n (R)L (R)X\n\n H (B)P\n (B)M (B)Y\n (R)L (R)X\n (R)H\n\n H (B)P\n (B)L (B)Y\n (R)H (R)M (R)X\n \n H (B)P\n (R)L (B)Y\n (B)H (B)M (R)X\n\n C (B)P\n (R)L (B)Y\n (B)H (B)M (R)X\n (R)C\n\n R (B)P\n (R)L (B)Y\n (B)H (B)M (R)X\n (R)C (R)R\n\n R (B)P\n (R)L (B)X\n (B)H (B)M (R)R (R)Y\n (R)C\n\n R (B)P\n (R)L (R)X\n (B)H (B)M (B)R (B)Y\n (R)C\n\n R (R)P\n (B)L (B)X\n (B)H (B)M (B)R (B)Y\n (R)C\n\n R (B)P\n (B)L (B)X\n (B)H (B)M (B)R (B)Y\n (R)C\n\n A (B)P\n (B)L (B)X\n (B)H (B)M (B)R (B)Y\n (R)C\n (R)A\n\n A (B)P\n (B)L (B)X\n (B)C (B)M (B)R (B)Y\n (R)A (R)H\n\n A (B)P\n (B)L (B)X\n (R)C (B)M (B)R (B)Y\n (B)A (B)H\n\n E (B)P\n (B)L (B)X\n (R)C (B)M (B)R (B)Y\n (B)A (B)H\n (R)E\n\n S (B)P\n (B)L (B)X\n (R)C (B)M (B)R (B)Y\n (B)A (B)H (R)S\n (R)E\n\n S (B)P\n (B)L (B)X\n (R)C (B)M (B)S (B)Y\n (B)A (B)H (R)R\n (R)E\n", "support_files": [], "metadata": {"number": "3.3.11", "chapter": 3, "chapter_title": "Searching", "section": 3.3, "section_title": "Balanced Search Trees", "type": "Exercise", "code_execution": false}} {"question": "True or false: If you insert keys in increasing order into a red-black BST, the tree height is monotonically increasing.", "answer": "3.3.13\n\nTrue.\n\nThe following visualization shows 255 keys inserted into a red-black BST in ascending order.\n[visualization](https://algs4.cs.princeton.edu/33balanced/media/red-black-255ascending.mov)\nfrom\n[source](https://algs4.cs.princeton.edu/33balanced/)\n", "support_files": [], "metadata": {"number": "3.3.13", "chapter": 3, "chapter_title": "Searching", "section": 3.3, "section_title": "Balanced Search Trees", "type": "Exercise", "code_execution": false}} {"question": "Draw the red-black BST that results when you insert letters A through K in order into an initially empty tree, then describe what happens in general when trees are built by insertion of keys in ascending order (see also the figure in the text).", "answer": "3.3.14\n\nInsert A (B)A\n\n B (B)A\n (R)B\n\n B (B)B\n (R)A\n\n C (B)B\n (R)A (R)C\n\n C (R)B\n (B)A (B)C\n\n C (B)B\n (B)A (B)C\n\n D (B)B\n (B)A (B)C\n (R)D\n\n D (B)B\n (B)A (B)D\n (R)C\n\n E (B)B\n (B)A (B)D\n (R)C (R)E\n\n E (B)B\n (B)A (R)D\n (B)C (B)E\n\n E (B)D\n (R)B (B)E\n (B)A (B)C \n\n F (B)D\n (R)B (B)E\n (B)A (B)C (R)F\n\n F (B)D\n (R)B (B)F\n (B)A (B)C (R)E \n\n G (B)D\n (R)B (B)F\n (B)A (B)C (R)E (R)G\n\n G (B)D\n (R)B (R)F\n (B)A (B)C (B)E (B)G\n\n G (R)D\n (B)B (B)F\n (B)A (B)C (B)E (B)G \n\n G (B)D\n (B)B (B)F\n (B)A (B)C (B)E (B)G \n\n H (B)D\n (B)B (B)F\n (B)A (B)C (B)E (B)G\n (R)H\n\n H (B)D\n (B)B (B)F\n (B)A (B)C (B)E (B)H\n (R)G\n\n I (B)D\n (B)B (B)F\n (B)A (B)C (B)E (B)H\n (R)G (R)I\n\n I (B)D\n (B)B (B)F\n (B)A (B)C (B)E (R)H\n (B)G (B)I\n\n I (B)D\n (B)B (B)H\n (B)A (B)C (R)F (B)I\n (B)E (B)G \n\n J (B)D\n (B)B (B)H\n (B)A (B)C (R)F (B)I\n (B)E (B)G (R)J\n\n J (B)D\n (B)B (B)H\n (B)A (B)C (R)F (B)J\n (B)E (B)G (R)I\n\n K (B)D\n (B)B (B)H\n (B)A (B)C (R)F (B)J\n (B)E (B)G (R)I (R)K\n\n K (B)D\n (B)B (B)H\n (B)A (B)C (R)F (R)J\n (B)E (B)G (B)I (B)K\n\n K (B)D\n (B)B (R)H\n (B)A (B)C (B)F (B)J\n (B)E (B)G (B)I (B)K\n\n K (B)H\n (R)D (B)J\n (B)B (B)F (B)I (B)K \n (B)A (B)C (B)E (B)G \n\nEvery insert operation requires either coloring (zero or more operations), left rotation (at most one) or a combination of coloring and left rotation. \nThe more nodes in the tree, the more nodes involved in these operations.\nThe tree height is monotonically increasing when inserting keys in increasing order.\n", "support_files": [], "metadata": {"number": "3.3.14", "chapter": 3, "chapter_title": "Searching", "section": 3.3, "section_title": "Balanced Search Trees", "type": "Exercise", "code_execution": false}} {"question": "For left-leaning red-black BSTs, answer Exercises 3.3.13 and 3.3.14 for the case when the keys are inserted in descending order: show the rotations/color flips and state whether the tree height is monotonically increasing.", "answer": "3.3.15\n\nIf keys are inserted in decreasing order into a red-black BST, the tree height is NOT monotonically increasing.\n\nInsert K (B)K\n\nInsert J (B)K\n (R)J\n\nInsert I (B)K\n (R)J\n (R)I\n\nInsert I (B)J\n (R)I (R)K\n\nInsert I (R)J\n (B)I (B)K\n\nInsert I (B)J\n (B)I (B)K\n\nInsert H (B)J\n (B)I (B)K\n (R)H\n\nInsert G (B)J\n (B)I (B)K\n (R)H\n (R)G\n\nInsert G (B)J\n (B)H (B)K\n (R)G (R)I\n\nInsert G (B)J\n (R)H (B)K\n (B)G (B)I\n\nInsert F (B)J\n (R)H (B)K\n (B)G (B)I\n (R)F\n\nInsert E (B)J\n (R)H (B)K\n (B)G (B)I\n (R)F\n (R)E\n\nInsert E (B)J\n (R)H (B)K\n (B)F (B)I\n (R)E (R)G\n\nInsert E (B)J\n (R)H (B)K\n (R)F (B)I\n (B)E (B)G\n\nInsert E (B)H\n (R)F (R)J\n (B)E (B)G (B)I (B)K\n\nInsert E (R)H\n (B)F (B)J\n (B)E (B)G (B)I (B)K\n\nInsert E (B)H\n (B)F (B)J\n (B)E (B)G (B)I (B)K (Tree height decreased from 3 to 2)\n\nInsert D (B)H\n (B)F (B)J\n (B)E (B)G (B)I (B)K\n (R)D\n\nInsert C (B)H\n (B)F (B)J\n (B)E (B)G (B)I (B)K\n (R)D\n (R)C\n\nInsert C (B)H\n (B)F (B)J\n (B)D (B)G (B)I (B)K\n (R)C (R)E\n\nInsert C (B)H\n (B)F (B)J\n (R)D (B)G (B)I (B)K\n (B)C (B)E\n\nInsert B (B)H\n (B)F (B)J\n (R)D (B)G (B)I (B)K\n (B)C (B)E\n (R)B\n\nInsert A (B)H\n (B)F (B)J\n (R)D (B)G (B)I (B)K\n (B)C (B)E\n (R)B\n (R)A\n\nInsert A (B)H\n (B)F (B)J\n (R)D (B)G (B)I (B)K\n (B)B (B)E\n (R)A (R)C\n\nInsert A (B)H\n (B)F (B)J\n (R)D (B)G (B)I (B)K\n (R)B (B)E\n (B)A (B)C\n\nInsert A (B)H\n (B)D (B)J\n (R)B (R)F (B)I (B)K\n (B)A (B)C (B)E (B)G\n\nInsert A (B)H\n (R)D (B)J\n (B)B (B)F (B)I (B)K\n (B)A (B)C (B)E (B)G (Tree height decreased from 4 to 3)\n\nThe insert operation may require no other operations, coloring, right rotation (zero, one or two) or a combination of coloring and right rotation. \nThe more nodes in the tree, the more nodes involved in these operations.\nThe tree height is not monotonically increasing when inserting keys in decreasing order.\n", "support_files": [], "metadata": {"number": "3.3.15", "chapter": 3, "chapter_title": "Searching", "section": 3.3, "section_title": "Balanced Search Trees", "type": "Exercise", "code_execution": false}} {"question": "Draw all the structurally different red-black BSTs with N keys, for N from 2 up to 10 (see Exercise 3.3.5).", "answer": "3.3.18\n\nN = 2\n\n (B)N\n(R)N\n\nN = 3\n\n (B)N\n(B)N (B)N\n\nN = 4\n\n (B)N\n(B)N (B)N\n (R)N\n\nN = 5\n\n (B)N\n (B)N (B)N\n(R)N (R)N\n\n (B)N\n (R)N (B)N\n(B)N (B)N \n\nN = 6\n\n (B)N\n (R)N (B)N\n(B)N (B)N (R)N\n\n (B)N\n (R)N (B)N\n (B)N (B)N\n(R)N\n\nN = 7\n\n (B)N\n (R)N (B)N\n(B)N (B)N (R)N\n (R)N\n\n (B)N\n (B)N (B)N\n(B)N (B)N (B)N (B)N\n\n (B)N\n (R)N (B)N\n (B)N (B)N\n(R)N (R)N\n\nN = 8\n\n (B)N\n (R)N (B)N\n (B)N (B)N (R)N\n(R)N (R)N\n\n (B)N\n (B)N (B)N\n(B)N (B)N (B)N (B)N\n (R)N\n\nN = 9\n\n (B)N\n (B)N (B)N\n (B)N (B)N (B)N (B)N\n(R)N (R)N\n\n (B)N\n (B)N (B)N\n(B)N (B)N (R)N (B)N \n (B)N (B)N\n\nN = 10\n\n (B)N\n (B)N (B)N\n (B)N (B)N (B)N (B)N\n(R)N (R)N (R)N\n\n (B)N\n (B)N (B)N\n (R)N (B)N (B)N (B)N\n (B)N (B)N\n(R)N\n\n (B)N\n (B)N (B)N\n (R)N (B)N (B)N (B)N\nB(N) B(N) (R)N\n\nThanks to QiotoF (https://github.com/QiotoF) for mentioning a missing structure for N = 6.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/103\n", "support_files": [], "metadata": {"number": "3.3.18", "chapter": 3, "chapter_title": "Searching", "section": 3.3, "section_title": "Balanced Search Trees", "type": "Exercise", "code_execution": false}} {"question": "Compute the internal path length in a perfectly balanced BST of N nodes, when N is a power of 2 minus 1.", "answer": "3.3.20\n\nFor a perfectly balanced BST of N nodes, when N is a power of 2 minus 1, the internal path lengths are:\n\nP = 1 -> 2^1 - 1 = 1 node -> Internal path length: 0 -> Which is 2^0 * 0\nP = 2 -> 2^2 - 1 = 3 nodes -> Internal path length: 2 -> Which is 2^0 * 0 + 2^1 * 1\nP = 3 -> 2^3 - 1 = 7 nodes -> Internal path length: 10 -> Which is 2^0 * 0 + 2^1 * 1 + 2^2 * 2\nP = 4 -> 2^4 - 1 = 15 nodes -> Internal path length: 34 -> Which is 2^0 * 0 + 2^1 * 1 + 2^2 * 2 + 2^3 * 3\n\n h\nInternal path length = SUM 2^i * i\n i=0\n\nWhere h is the height of the tree.\n\nThe terms 2^i * i are an arithmetico-geometric sequence, and using the technique of telescoping series, their sum has\na closed-form expression.\nReference: https://en.wikipedia.org/wiki/Arithmetico%E2%80%93geometric_sequence\n\nFollowing the description from the above reference, for the sum of the terms we have:\na = 1\nb = 2\nd = 1\nr = 2\n\nA1 = 1\nG1 = 2\nA(n + 1) = h + 1\nG(n + 1) = 2^(h + 1)\n\nClosed-form expression:\nSn = (A1 * G1 - (A(n + 1) * G(n+ 1))) / (1 - r) + (d * r) / (1 - r)^2 * (G1 - G(n + 1))\n\nReplacing the values:\nSn = (1 * 2 - ((h + 1) * 2^(h + 1))) / (1 - 2) + (1 * 2) / (1 - 2)^2 * (2 - 2^(h + 1))\nSn = (2 - ((h + 1) * 2^(h + 1))) / (-1) + 2 * (2 - 2^(h + 1))\nSn = (2 - (h * 2^(h + 1) + 2^(h + 1))) / (-1) + 4 - 2 * 2^(h + 1)\nSn = -2 + h * 2^(h + 1) + 2^(h + 1) + 4 - 2 * 2^(h + 1)\nSn = 2 + h * 2^(h + 1) + (-1) * 2^(h + 1)\nSn = 2 + (h - 1) * 2^(h + 1)\n\nReplacing h with N we have:\nN = 2^(h + 1) - 1\nh = lg(N + 1) - 1\n\nSn = 2 + ((lg(N + 1) - 1) - 1) * 2^((lg(N + 1) - 1) + 1)\nSn = 2 + (lg(N + 1) - 2) * 2^(lg(N + 1))\nSn = 2 + (lg(N + 1) - 2) * (N + 1)\nSn = 2 + lg(N + 1) * (N + 1) - 2 * (N + 1)\nSn = 2 + lg(N + 1) * (N + 1) - 2 * N - 2\nSn = lg(N + 1) * (N + 1) - 2 * N\n\nInternal path length = lg(N + 1) * (N + 1) - 2 * N\n\nWhere N is the number of nodes in the tree.\n\nThanks to luowyang (https://github.com/luowyang) for mentioning about the closed-form expression and precise solution\nto this exercise:\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/94\n", "support_files": [], "metadata": {"number": "3.3.20", "chapter": 3, "chapter_title": "Searching", "section": 3.3, "section_title": "Balanced Search Trees", "type": "Exercise", "code_execution": false}} {"question": "Create a test client TestRB.java, based on your solution to Exercise 3.2.10.", "answer": "package chapter3.section3;\n\nimport edu.princeton.cs.algs4.StdIn;\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 19/06/17.\n */\npublic class Exercise21 {\n\n public static void main(String[] args) {\n\n /** Test type\n * 0- Keys()\n * 1- Min()\n * 2- Max()\n * 3- Floor()\n * 4- Ceiling()\n * 5- Select()\n * 6- Rank()\n * 7- Delete()\n * 8- DeleteMin()\n * 9- DeleteMax()\n * 10- Keys() with range\n *\n * Or no value, for all tests\n */\n\n int testType = -1;\n if (args.length == 1) {\n testType = Integer.parseInt(args[0]);\n }\n\n //Test values:\n //5 1 9 2 0 99\n\n //Expected tree\n // (B)5\n // (R)1 (B)99\n //(B)0 (B)2 (R)9\n\n RedBlackBST redBlackBST = new RedBlackBST<>();\n\n while (!StdIn.isEmpty()) {\n Integer key = StdIn.readInt();\n redBlackBST.put(key, \"Value \" + key);\n }\n\n if (testType == -1 || testType == 0) {\n StdOut.println(\"Keys() test\");\n\n for (Integer key : redBlackBST.keys()) {\n StdOut.println(\"Key \" + key + \": \" + redBlackBST.get(key));\n }\n\n StdOut.println(\"Expected: 0 1 2 5 9 99\\n\");\n }\n\n if (testType == -1 || testType == 1) {\n // Test min()\n StdOut.println(\"Min key: \" + redBlackBST.min() + \" Expected: 0\");\n }\n\n if (testType == -1 || testType == 2) {\n // Test max()\n StdOut.println(\"Max key: \" + redBlackBST.max() + \" Expected: 99\");\n }\n\n if (testType == -1 || testType == 3) {\n // Test floor()\n StdOut.println(\"Floor of 5: \" + redBlackBST.floor(5) + \" Expected: 5\");\n StdOut.println(\"Floor of 15: \" + redBlackBST.floor(15) + \" Expected: 9\");\n }\n\n if (testType == -1 || testType == 4) {\n // Test ceiling()\n StdOut.println(\"Ceiling of 5: \" + redBlackBST.ceiling(5) + \" Expected: 5\");\n StdOut.println(\"Ceiling of 15: \" + redBlackBST.ceiling(15) + \" Expected: 99\");\n }\n\n if (testType == -1 || testType == 5) {\n // Test select()\n StdOut.println(\"Select key of rank 4: \" + redBlackBST.select(4) + \" Expected: 9\");\n }\n\n if (testType == -1 || testType == 6) {\n // Test rank()\n StdOut.println(\"Rank of key 9: \" + redBlackBST.rank(9) + \" Expected: 4\");\n StdOut.println(\"Rank of key 10: \" + redBlackBST.rank(10) + \" Expected: 5\");\n }\n\n if (testType == -1 || testType == 7) {\n // Test delete()\n StdOut.println(\"\\nDelete key 2\");\n redBlackBST.delete(2);\n\n for (Integer key : redBlackBST.keys()) {\n StdOut.println(\"Key \" + key + \": \" + redBlackBST.get(key));\n }\n }\n\n if (testType == -1 || testType == 8) {\n // Test deleteMin()\n StdOut.println(\"\\nDelete min (key 0)\");\n redBlackBST.deleteMin();\n\n for (Integer key : redBlackBST.keys()) {\n StdOut.println(\"Key \" + key + \": \" + redBlackBST.get(key));\n }\n }\n\n if (testType == -1 || testType == 9) {\n // Test deleteMax()\n StdOut.println(\"\\nDelete max (key 99)\");\n redBlackBST.deleteMax();\n\n for (Integer key : redBlackBST.keys()) {\n StdOut.println(\"Key \" + key + \": \" + redBlackBST.get(key));\n }\n }\n\n if (testType == -1 || testType == 10) {\n // Test keys() with range\n StdOut.println(\"\\nKeys in range [2, 10]\");\n for (Integer key : redBlackBST.keys(2, 10)) {\n StdOut.println(\"Key \" + key + \": \" + redBlackBST.get(key));\n }\n }\n }\n}\n", "support_files": [], "metadata": {"number": "3.3.21", "chapter": 3, "chapter_title": "Searching", "section": 3.3, "section_title": "Balanced Search Trees", "type": "Exercise", "code_execution": false}} {"question": "2-3 trees without balance restriction. Develop an implementation of the basic symbol-table API that uses 2-3 trees that are not necessarily balanced as the underlying data structure. Allow 3-nodes to lean either way. Hook the new node onto the bottom with a black link when inserting into a 3-node at the bottom. Run experiments to develop a hypothesis estimating the average path length in a tree built from N random insertions.", "answer": "// Exercise23_23TreesWithoutBalance.java\npackage chapter3.section3;\n\nimport edu.princeton.cs.algs4.Queue;\nimport edu.princeton.cs.algs4.StdOut;\nimport edu.princeton.cs.algs4.StdRandom;\n\nimport java.util.NoSuchElementException;\n\n/**\n * Created by Rene Argento on 24/06/17.\n */\npublic class Exercise23_23TreesWithoutBalance {\n\n private class TwoThreeTreeNonBalanced, Value> {\n\n private static final boolean RED = true;\n private static final boolean BLACK = false;\n\n private class Node {\n Key key;\n Value value;\n Node left, right;\n\n boolean color;\n int size;\n\n private int depth; //used only to compute the internal path length\n\n Node(Key key, Value value, int size, boolean color) {\n this.key = key;\n this.value = value;\n\n this.size = size;\n this.color = color;\n }\n }\n\n private Node root;\n\n public int size() {\n return size(root);\n }\n\n private int size(Node node) {\n if (node == null) {\n return 0;\n }\n\n return node.size;\n }\n\n public boolean isEmpty() {\n return size(root) == 0;\n }\n\n private boolean isRed(Node node) {\n if (node == null) {\n return false;\n }\n\n return node.color == RED;\n }\n\n private Node rotateLeft(Node node) {\n if (node == null || node.right == null) {\n return node;\n }\n\n Node newRoot = node.right;\n\n node.right = newRoot.left;\n newRoot.left = node;\n\n newRoot.color = node.color;\n node.color = RED;\n\n newRoot.size = node.size;\n node.size = size(node.left) + 1 + size(node.right);\n\n return newRoot;\n }\n\n private Node rotateRight(Node node) {\n if (node == null || node.left == null) {\n return node;\n }\n\n Node newRoot = node.left;\n\n node.left = newRoot.right;\n newRoot.right = node;\n\n newRoot.color = node.color;\n node.color = RED;\n\n newRoot.size = node.size;\n node.size = size(node.left) + 1 + size(node.right);\n\n return newRoot;\n }\n\n private void flipColors(Node node) {\n if (node == null || node.left == null || node.right == null) {\n return;\n }\n\n //The root must have opposite color of its two children\n if ((isRed(node) && !isRed(node.left) && !isRed(node.right))\n || (!isRed(node) && isRed(node.left) && isRed(node.right))) {\n node.color = !node.color;\n node.left.color = !node.left.color;\n node.right.color = !node.right.color;\n }\n }\n\n public void put(Key key, Value value) {\n if (key == null) {\n return;\n }\n\n if (value == null) {\n delete(key);\n return;\n }\n\n root = put(root, key, value, root);\n root.color = BLACK;\n }\n\n private Node put(Node node, Key key, Value value, Node parent) {\n if (node == null) {\n boolean isTwoThreeNode = true;\n\n //If the parent is red, it is a 3-node\n //Otherwise, check the node sibling's color\n if (parent != null && !isRed(parent)) {\n boolean isLeftChild = key.compareTo(parent.key) < 0;\n\n if (isLeftChild) {\n if (!isRed(parent.right)) {\n isTwoThreeNode = false;\n }\n } else {\n if (!isRed(parent.left)) {\n isTwoThreeNode = false;\n }\n }\n }\n\n return new Node(key, value, 1, !isTwoThreeNode);\n }\n\n int compare = key.compareTo(node.key);\n\n if (compare < 0) {\n node.left = put(node.left, key, value, node);\n } else if (compare > 0) {\n node.right = put(node.right, key, value, node);\n } else {\n node.value = value;\n }\n\n node.size = size(node.left) + 1 + size(node.right);\n return node;\n }\n\n public Value get(Key key) {\n if (key == null) {\n return null;\n }\n\n return get(root, key);\n }\n\n private Value get(Node node, Key key) {\n if (node == null) {\n return null;\n }\n\n int compare = key.compareTo(node.key);\n if (compare < 0) {\n return get(node.left, key);\n } else if (compare > 0) {\n return get(node.right, key);\n } else {\n return node.value;\n }\n }\n\n public boolean contains(Key key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Argument to contains() cannot be null\");\n }\n return get(key) != null;\n }\n\n public Key min() {\n if (root == null) {\n throw new NoSuchElementException(\"Empty binary search tree\");\n }\n\n return min(root).key;\n }\n\n protected Node min(Node node) {\n if (node.left == null) {\n return node;\n }\n\n return min(node.left);\n }\n\n public Key max() {\n if (root == null) {\n throw new NoSuchElementException(\"Empty binary search tree\");\n }\n\n return max(root).key;\n }\n\n private Node max(Node node) {\n if (node.right == null) {\n return node;\n }\n\n return max(node.right);\n }\n\n //Returns the highest key in the symbol table smaller than or equal to key.\n public Key floor(Key key) {\n Node node = floor(root, key);\n if (node == null) {\n return null;\n }\n\n return node.key;\n }\n\n private Node floor(Node node, Key key) {\n if (node == null) {\n return null;\n }\n\n int compare = key.compareTo(node.key);\n\n if (compare == 0) {\n return node;\n } else if (compare < 0) {\n return floor(node.left, key);\n } else {\n Node rightNode = floor(node.right, key);\n if (rightNode != null) {\n return rightNode;\n } else {\n return node;\n }\n }\n }\n\n //Returns the smallest key in the symbol table greater than or equal to key.\n public Key ceiling(Key key) {\n Node node = ceiling(root, key);\n if (node == null) {\n return null;\n }\n\n return node.key;\n }\n\n private Node ceiling(Node node, Key key) {\n if (node == null) {\n return null;\n }\n\n int compare = key.compareTo(node.key);\n\n if (compare == 0) {\n return node;\n } else if (compare > 0) {\n return ceiling(node.right, key);\n } else {\n Node leftNode = ceiling(node.left, key);\n if (leftNode != null) {\n return leftNode;\n } else {\n return node;\n }\n }\n }\n\n public Key select(int index) {\n if (index >= size()) {\n throw new IllegalArgumentException(\"Index is higher than tree size\");\n }\n\n return select(root, index).key;\n }\n\n private Node select(Node node, int index) {\n int leftSubtreeSize = size(node.left);\n\n if (leftSubtreeSize == index) {\n return node;\n } else if (leftSubtreeSize > index) {\n return select(node.left, index);\n } else {\n return select(node.right, index - leftSubtreeSize - 1);\n }\n }\n\n public int rank(Key key) {\n return rank(root, key);\n }\n\n private int rank(Node node, Key key) {\n if (node == null) {\n return 0;\n }\n\n //Returns the number of keys less than node.key in the subtree rooted at node\n int compare = key.compareTo(node.key);\n if (compare < 0) {\n return rank(node.left, key);\n } else if (compare > 0) {\n return size(node.left) + 1 + rank(node.right, key);\n } else {\n return size(node.left);\n }\n }\n\n public void deleteMin() {\n if (isEmpty()) {\n return;\n }\n\n if (!isRed(root.left) && !isRed(root.right)) {\n root.color = RED;\n }\n\n root = deleteMin(root);\n\n if (!isEmpty()) {\n root.color = BLACK;\n }\n }\n\n private Node deleteMin(Node node) {\n if (node.left == null) {\n return node.right;\n }\n\n if (!isRed(node.left) && !isRed(node.left.left)) {\n node = moveRedLeft(node);\n }\n\n node.left = deleteMin(node.left);\n return balance(node);\n }\n\n public void deleteMax() {\n if (isEmpty()) {\n return;\n }\n\n if (!isRed(root.left) && !isRed(root.right)) {\n root.color = RED;\n }\n\n root = deleteMax(root);\n\n if (!isEmpty()) {\n root.color = BLACK;\n }\n }\n\n private Node deleteMax(Node node) {\n if (isRed(node.left)) {\n node = rotateRight(node);\n }\n\n if (node.right == null) {\n return node.left;\n }\n\n if (!isRed(node.right) && !isRed(node.right.left)) {\n node = moveRedRight(node);\n }\n\n node.right = deleteMax(node.right);\n return balance(node);\n }\n\n public void delete(Key key) {\n if (isEmpty()) {\n return;\n }\n\n if (!contains(key)) {\n return;\n }\n\n if (!isRed(root.left) && !isRed(root.right)) {\n root.color = RED;\n }\n\n root = delete(root, key);\n\n if (!isEmpty()) {\n root.color = BLACK;\n }\n }\n\n private Node delete(Node node, Key key) {\n if (node == null) {\n return null;\n }\n\n if (key.compareTo(node.key) < 0) {\n if (!isRed(node.left) && node.left != null && !isRed(node.left.left)) {\n node = moveRedLeft(node);\n }\n\n node.left = delete(node.left, key);\n } else {\n if (isRed(node.left)) {\n node = rotateRight(node);\n }\n\n if (key.compareTo(node.key) == 0 && node.right == null) {\n return node.left;\n }\n\n if (!isRed(node.right) && node.right != null && !isRed(node.right.left)) {\n node = moveRedRight(node);\n }\n\n if (key.compareTo(node.key) == 0) {\n Node aux = min(node.right);\n node.key = aux.key;\n node.value = aux.value;\n node.right = deleteMin(node.right);\n } else {\n node.right = delete(node.right, key);\n }\n }\n\n return balance(node);\n }\n\n private Node moveRedLeft(Node node) {\n //Assuming that node is red and both node.left and node.left.left are black,\n // make node.left or one of its children red\n flipColors(node);\n\n if (node.right != null && isRed(node.right.left)) {\n node.right = rotateRight(node.right);\n node = rotateLeft(node);\n flipColors(node);\n }\n\n return node;\n }\n\n private Node moveRedRight(Node node) {\n //Assuming that node is red and both node.right and node.right.left are black,\n // make node.right or one of its children red\n flipColors(node);\n\n if (node.left != null && isRed(node.left.left)) {\n node = rotateRight(node);\n flipColors(node);\n }\n\n return node;\n }\n\n private Node balance(Node node) {\n if (node == null) {\n return null;\n }\n\n if (isRed(node.right) && isRed(node.right.right)) {\n node = rotateLeft(node);\n }\n\n if (isRed(node.left) && isRed(node.left.left)) {\n node = rotateRight(node);\n }\n\n if (isRed(node.left) && isRed(node.right)) {\n flipColors(node);\n }\n\n node.size = size(node.left) + 1 + size(node.right);\n\n return node;\n }\n\n public Iterable keys() {\n return keys(min(), max());\n }\n\n public Iterable keys(Key low, Key high) {\n if (low == null) {\n throw new IllegalArgumentException(\"First argument to keys() cannot be null\");\n }\n if (high == null) {\n throw new IllegalArgumentException(\"Second argument to keys() cannot be null\");\n }\n\n Queue queue = new Queue<>();\n keys(root, queue, low, high);\n return queue;\n }\n\n private void keys(Node node, Queue queue, Key low, Key high) {\n if (node == null) {\n return;\n }\n\n int compareLow = low.compareTo(node.key);\n int compareHigh = high.compareTo(node.key);\n\n if (compareLow < 0) {\n keys(node.left, queue, low, high);\n }\n\n if (compareLow <= 0 && compareHigh >= 0) {\n queue.enqueue(node.key);\n }\n\n if (compareHigh > 0) {\n keys(node.right, queue, low, high);\n }\n }\n\n public int size(Key low, Key high) {\n if (low == null) {\n throw new IllegalArgumentException(\"First argument to size() cannot be null\");\n }\n if (high == null) {\n throw new IllegalArgumentException(\"Second argument to size() cannot be null\");\n }\n\n if (low.compareTo(high) > 0) {\n return 0;\n }\n\n if (contains(high)) {\n return rank(high) - rank(low) + 1;\n } else {\n return rank(high) - rank(low);\n }\n }\n\n private int internalPathLength() {\n if (root == null) {\n return 0;\n }\n\n int internalPathLength = 0;\n\n Queue queue = new Queue<>();\n root.depth = 0;\n queue.enqueue(root);\n\n while (!queue.isEmpty()) {\n Node current = queue.dequeue();\n internalPathLength += current.depth;\n\n if (current.left != null) {\n current.left.depth = current.depth + 1;\n queue.enqueue(current.left);\n }\n if (current.right != null) {\n current.right.depth = current.depth + 1;\n queue.enqueue(current.right);\n }\n }\n\n return internalPathLength;\n }\n\n public int averagePathLength() {\n if (size() == 0) {\n return 0;\n }\n\n return (internalPathLength() / size()) + 1;\n }\n\n private boolean isTwoThreeTree() {\n return isTwoThreeTree(root);\n }\n\n private boolean isTwoThreeTree(Node node) {\n if (node == null) {\n return true;\n }\n\n if (isRed(node.left) && (isRed(node.left.left) || isRed(node.left.right))) {\n return false;\n }\n\n if (isRed(node.right) && (isRed(node.right.left) || isRed(node.right.right))) {\n return false;\n }\n\n return isTwoThreeTree(node.left) && isTwoThreeTree(node.right);\n }\n\n }\n\n public static void main(String[] args) {\n Exercise23_23TreesWithoutBalance treesWithoutBalance = new Exercise23_23TreesWithoutBalance();\n treesWithoutBalance.testAPI();\n treesWithoutBalance.doExperiment();\n }\n\n private void testAPI() {\n // Expected tree\n // (B)5\n // (R)1 (B)9\n // (B)0 (B)2 (R)99\n // (R)-1\n //(B)-2\n\n TwoThreeTreeNonBalanced twoThreeTreeNonBalanced = new TwoThreeTreeNonBalanced<>();\n twoThreeTreeNonBalanced.put(5, 5);\n twoThreeTreeNonBalanced.put(1, 1);\n twoThreeTreeNonBalanced.put(9, 9);\n twoThreeTreeNonBalanced.put(2, 2);\n twoThreeTreeNonBalanced.put(0, 0);\n twoThreeTreeNonBalanced.put(99, 99);\n twoThreeTreeNonBalanced.put(-1, -1);\n twoThreeTreeNonBalanced.put(-2, -2);\n\n StdOut.println(\"Keys() test\");\n\n for (Integer key : twoThreeTreeNonBalanced.keys()) {\n StdOut.println(\"Key \" + key + \": \" + twoThreeTreeNonBalanced.get(key));\n }\n StdOut.println(\"Expected: -2 -1 0 1 2 5 9 99\\n\");\n\n // Test min()\n StdOut.println(\"Min key: \" + twoThreeTreeNonBalanced.min() + \" Expected: -2\");\n\n // Test max()\n StdOut.println(\"Max key: \" + twoThreeTreeNonBalanced.max() + \" Expected: 99\");\n\n // Test floor()\n StdOut.println(\"Floor of 5: \" + twoThreeTreeNonBalanced.floor(5) + \" Expected: 5\");\n StdOut.println(\"Floor of 15: \" + twoThreeTreeNonBalanced.floor(15) + \" Expected: 9\");\n\n // Test ceiling()\n StdOut.println(\"Ceiling of 5: \" + twoThreeTreeNonBalanced.ceiling(5) + \" Expected: 5\");\n StdOut.println(\"Ceiling of 15: \" + twoThreeTreeNonBalanced.ceiling(15) + \" Expected: 99\");\n\n // Test select()\n StdOut.println(\"Select key of rank 4: \" + twoThreeTreeNonBalanced.select(4) + \" Expected: 2\");\n\n // Test rank()\n StdOut.println(\"Rank of key 9: \" + twoThreeTreeNonBalanced.rank(9) + \" Expected: 6\");\n StdOut.println(\"Rank of key 10: \" + twoThreeTreeNonBalanced.rank(10) + \" Expected: 7\");\n\n // Test delete()\n StdOut.println(\"\\nDelete key 2\");\n twoThreeTreeNonBalanced.delete(2);\n\n for (Integer key : twoThreeTreeNonBalanced.keys()) {\n StdOut.println(\"Key \" + key + \": \" + twoThreeTreeNonBalanced.get(key));\n }\n StdOut.println(\"Is 2-3 three: \" + twoThreeTreeNonBalanced.isTwoThreeTree() + \" Expected: true\");\n\n // Test deleteMin()\n StdOut.println(\"\\nDelete min (key -2)\");\n twoThreeTreeNonBalanced.deleteMin();\n\n for (Integer key : twoThreeTreeNonBalanced.keys()) {\n StdOut.println(\"Key \" + key + \": \" + twoThreeTreeNonBalanced.get(key));\n }\n StdOut.println(\"Is 2-3 three: \" + twoThreeTreeNonBalanced.isTwoThreeTree() + \" Expected: true\");\n\n // Test deleteMax()\n StdOut.println(\"\\nDelete max (key 99)\");\n twoThreeTreeNonBalanced.deleteMax();\n\n for (Integer key : twoThreeTreeNonBalanced.keys()) {\n StdOut.println(\"Key \" + key + \": \" + twoThreeTreeNonBalanced.get(key));\n }\n StdOut.println(\"Is 2-3 three: \" + twoThreeTreeNonBalanced.isTwoThreeTree() + \" Expected: true\");\n\n // Test keys() with range\n StdOut.println(\"\\nKeys in range [2, 10]\");\n for (Integer key : twoThreeTreeNonBalanced.keys(2, 10)) {\n StdOut.println(\"Key \" + key + \": \" + twoThreeTreeNonBalanced.get(key));\n }\n\n // Delete all\n StdOut.println(\"\\nDelete all\");\n while (twoThreeTreeNonBalanced.size() > 0) {\n for (Integer key : twoThreeTreeNonBalanced.keys()) {\n StdOut.println(\"Key \" + key + \": \" + twoThreeTreeNonBalanced.get(key));\n }\n StdOut.println(\"Is 2-3 three: \" + twoThreeTreeNonBalanced.isTwoThreeTree() + \" Expected: true\");\n\n twoThreeTreeNonBalanced.delete(twoThreeTreeNonBalanced.select(twoThreeTreeNonBalanced.size() - 1));\n StdOut.println();\n }\n }\n\n private void doExperiment() {\n int redBlackTreeSize = 100;\n\n for (int experiment = 0; experiment < 6; experiment++) {\n TwoThreeTreeNonBalanced twoThreeTreeNonBalanced = new TwoThreeTreeNonBalanced<>();\n\n for (int i = 0; i < redBlackTreeSize; i++) {\n int randomKey = StdRandom.uniform(Integer.MAX_VALUE);\n twoThreeTreeNonBalanced.put(randomKey, randomKey);\n }\n\n StdOut.println(\"Average path length for \" + redBlackTreeSize + \" random insertions: \"\n + twoThreeTreeNonBalanced.averagePathLength());\n redBlackTreeSize *= 10;\n }\n }\n}\n\nAdditional notes/results:\n3.3.23 - 2-3 trees without balance restriction\n\nAverage path length for 100 random insertions: 7\nAverage path length for 1000 random insertions: 12\nAverage path length for 10000 random insertions: 17\nAverage path length for 100000 random insertions: 20\nAverage path length for 1000000 random insertions: 26\nAverage path length for 10000000 random insertions: 30\n\nHypothesis: In a non-balanced 2-3 tree the average path length becomes the same as the average path length for a standard binary search tree: ~1.44 lg N after N random insertions.", "support_files": [], "metadata": {"number": "3.3.23", "chapter": 3, "chapter_title": "Searching", "section": 3.3, "section_title": "Balanced Search Trees", "type": "Creative Problem", "code_execution": false}} {"question": "Allow right-leaning red links. Develop a modified version of your solution to Exercise 3.3.25 that allows right-leaning red links in the tree.", "answer": "package chapter3.section3;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 28/06/17.\n */\npublic class Exercise27_AllowRightLeaningRedLinks {\n\n private class RedBlackTopDown234RightLeaningBST, Value> extends Exercise25_TopDown234Trees.RedBlackTopDown234BST {\n public void put(Key key, Value value) {\n if (key == null) {\n return;\n }\n\n if (value == null) {\n delete(key);\n return;\n }\n\n root = put(root, key, value);\n root.color = BLACK;\n }\n\n private Node put(Node node, Key key, Value value) {\n if (node == null) {\n return new Node(key, value, 1, RED);\n }\n\n if (isRed(node.left) && isRed(node.right)) {\n flipColors(node);\n }\n\n int compare = key.compareTo(node.key);\n\n if (compare < 0) {\n node.left = put(node.left, key, value);\n } else if (compare > 0) {\n node.right = put(node.right, key, value);\n } else {\n node.value = value;\n }\n\n if (isRed(node.right) && isRed(node.right.left)) {\n node.right = rotateRight(node.right);\n }\n if (isRed(node.right) && isRed(node.right.right)) {\n node = rotateLeft(node);\n }\n if (isRed(node.left) && isRed(node.left.right)) {\n node.left = rotateLeft(node.left);\n }\n if (isRed(node.left) && isRed(node.left.left)) {\n node = rotateRight(node);\n }\n\n node.size = size(node.left) + 1 + size(node.right);\n return node;\n }\n\n public void deleteMax() {\n if (isEmpty()) {\n return;\n }\n\n if (!isRed(root.left) && !isRed(root.right)) {\n root.color = RED;\n }\n\n root = deleteMax(root);\n\n if (!isEmpty()) {\n root.color = BLACK;\n }\n }\n\n private Node deleteMax(Node node) {\n if (isRed(node.left) && !isRed(node.right)) {\n node = rotateRight(node);\n }\n\n if (node.right == null) {\n return null;\n }\n\n if (!isRed(node.right) && node.right != null && !isRed(node.right.left) && !isRed(node.right.right)) {\n node = moveRedRight(node);\n }\n\n node.right = deleteMax(node.right);\n return balance(node);\n }\n\n public void delete(Key key) {\n if (isEmpty()) {\n return;\n }\n\n if (!contains(key)) {\n return;\n }\n\n if (!isRed(root.left) && !isRed(root.right)) {\n root.color = RED;\n }\n\n root = delete(root, key);\n\n if (!isEmpty()) {\n root.color = BLACK;\n }\n }\n\n private Node delete(Node node, Key key) {\n if (node == null) {\n return null;\n }\n\n if (key.compareTo(node.key) < 0) {\n if (!isRed(node.left) && node.left != null && !isRed(node.left.left)) {\n node = moveRedLeft(node);\n }\n\n node.left = delete(node.left, key);\n } else {\n if (isRed(node.left) && !isRed(node.right)) {\n node = rotateRight(node);\n }\n\n if (key.compareTo(node.key) == 0 && node.right == null) {\n return null;\n }\n\n if (!isRed(node.right) && node.right != null && !isRed(node.right.left) && !isRed(node.right.right)) {\n node = moveRedRight(node);\n }\n\n if (key.compareTo(node.key) == 0) {\n Node aux = min(node.right);\n node.key = aux.key;\n node.value = aux.value;\n node.right = deleteMin(node.right);\n } else {\n node.right = delete(node.right, key);\n }\n }\n\n return balance(node);\n }\n\n private Node moveRedLeft(Node node) {\n //Assuming that node is red and node.left and node.left.left and node.left.right are black,\n // make node.left or one of its children red\n flipColors(node);\n\n if (node.right != null && isRed(node.right.left)) {\n node.right = rotateRight(node.right);\n node = rotateLeft(node);\n flipColors(node);\n } else if (node.right != null && isRed(node.right.right)) {\n node.right = rotateLeft(node.right);\n node = rotateLeft(node);\n flipColors(node);\n }\n\n return node;\n }\n\n private Node moveRedRight(Node node) {\n // Assuming that node is red and node.right and node.right.left and node.right.right are black,\n // make node.right or one of its children red\n flipColors(node);\n\n if (node.left != null && isRed(node.left.left)) {\n node = rotateRight(node);\n flipColors(node);\n } else if (node.left != null && isRed(node.left.right)) {\n node.left = rotateLeft(node.left);\n node = rotateRight(node);\n flipColors(node);\n }\n\n return node;\n }\n\n private Node balance(Node node) {\n if (node == null) {\n return null;\n }\n\n if (isRed(node.right) && isRed(node.right.left)) {\n node.right = rotateRight(node.right);\n }\n if (isRed(node.right) && isRed(node.right.right)) {\n node = rotateLeft(node);\n }\n if (isRed(node.left) && isRed(node.left.right)) {\n node.left = rotateLeft(node.left);\n }\n if (isRed(node.left) && isRed(node.left.left)) {\n node = rotateRight(node);\n }\n\n if (isRed(node.left) && isRed(node.right)) {\n flipColors(node);\n }\n\n node.size = size(node.left) + 1 + size(node.right);\n\n return node;\n }\n\n public boolean isValid234RightLeaningTree() {\n return isValid234RightLeaningTree(root);\n }\n\n private boolean isValid234RightLeaningTree(Node node) {\n if (node == null) {\n return true;\n }\n\n if (isRed(node.left) && isRed(node.left.left)) {\n return false;\n }\n if (isRed(node.left) && isRed(node.left.right)) {\n return false;\n }\n if (isRed(node.right) && isRed(node.right.right)) {\n return false;\n }\n if (isRed(node.right) && isRed(node.right.left)) {\n return false;\n }\n\n return isValid234RightLeaningTree(node.left) && isValid234RightLeaningTree(node.right);\n }\n }\n\n public static void main(String[] args) {\n // Expected 2-3-4 tree\n //\n // (B)1\n // (R)-1 (R)5\n // (B)-2 (B)0 (B)2 (B)9\n // (R)-5 (R)3 (R)99\n //\n\n Exercise27_AllowRightLeaningRedLinks allowRightLeaningRedLinks = new Exercise27_AllowRightLeaningRedLinks();\n RedBlackTopDown234RightLeaningBST redBlackTopDown234RightLeaningBST =\n allowRightLeaningRedLinks.new RedBlackTopDown234RightLeaningBST<>();\n redBlackTopDown234RightLeaningBST.put(5, 5);\n StdOut.println(\"Is valid 2-3-4 tree: \" + redBlackTopDown234RightLeaningBST.isValid234RightLeaningTree() + \" Expected: true\");\n StdOut.println(\"Is BST: \" + redBlackTopDown234RightLeaningBST.isBST() + \" Expected: true\");\n redBlackTopDown234RightLeaningBST.put(1, 1);\n StdOut.println(\"Is valid 2-3-4 tree: \" + redBlackTopDown234RightLeaningBST.isValid234RightLeaningTree() + \" Expected: true\");\n StdOut.println(\"Is BST: \" + redBlackTopDown234RightLeaningBST.isBST() + \" Expected: true\");\n redBlackTopDown234RightLeaningBST.put(9, 9);\n StdOut.println(\"Is valid 2-3-4 tree: \" + redBlackTopDown234RightLeaningBST.isValid234RightLeaningTree() + \" Expected: true\");\n StdOut.println(\"Is BST: \" + redBlackTopDown234RightLeaningBST.isBST() + \" Expected: true\");\n redBlackTopDown234RightLeaningBST.put(2, 2);\n StdOut.println(\"Is valid 2-3-4 tree: \" + redBlackTopDown234RightLeaningBST.isValid234RightLeaningTree() + \" Expected: true\");\n StdOut.println(\"Is BST: \" + redBlackTopDown234RightLeaningBST.isBST() + \" Expected: true\");\n redBlackTopDown234RightLeaningBST.put(0, 0);\n StdOut.println(\"Is valid 2-3-4 tree: \" + redBlackTopDown234RightLeaningBST.isValid234RightLeaningTree() + \" Expected: true\");\n StdOut.println(\"Is BST: \" + redBlackTopDown234RightLeaningBST.isBST() + \" Expected: true\");\n redBlackTopDown234RightLeaningBST.put(99, 99);\n StdOut.println(\"Is valid 2-3-4 tree: \" + redBlackTopDown234RightLeaningBST.isValid234RightLeaningTree() + \" Expected: true\");\n StdOut.println(\"Is BST: \" + redBlackTopDown234RightLeaningBST.isBST() + \" Expected: true\");\n redBlackTopDown234RightLeaningBST.put(-1, -1);\n StdOut.println(\"Is valid 2-3-4 tree: \" + redBlackTopDown234RightLeaningBST.isValid234RightLeaningTree() + \" Expected: true\");\n StdOut.println(\"Is BST: \" + redBlackTopDown234RightLeaningBST.isBST() + \" Expected: true\");\n redBlackTopDown234RightLeaningBST.put(-2, -2);\n StdOut.println(\"Is valid 2-3-4 tree: \" + redBlackTopDown234RightLeaningBST.isValid234RightLeaningTree() + \" Expected: true\");\n StdOut.println(\"Is BST: \" + redBlackTopDown234RightLeaningBST.isBST() + \" Expected: true\");\n redBlackTopDown234RightLeaningBST.put(3, 3);\n StdOut.println(\"Is valid 2-3-4 tree: \" + redBlackTopDown234RightLeaningBST.isValid234RightLeaningTree() + \" Expected: true\");\n StdOut.println(\"Is BST: \" + redBlackTopDown234RightLeaningBST.isBST() + \" Expected: true\");\n redBlackTopDown234RightLeaningBST.put(-5, -5);\n StdOut.println(\"Is valid 2-3-4 tree: \" + redBlackTopDown234RightLeaningBST.isValid234RightLeaningTree() + \" Expected: true\");\n StdOut.println(\"Is BST: \" + redBlackTopDown234RightLeaningBST.isBST() + \" Expected: true\\n\");\n\n StdOut.println(\"Size consistent: \" + redBlackTopDown234RightLeaningBST.isSubtreeCountConsistent() + \" Expected: true\\n\");\n\n StdOut.println(\"Keys() test\");\n\n for (Integer key : redBlackTopDown234RightLeaningBST.keys()) {\n StdOut.println(\"Key \" + key + \": \" + redBlackTopDown234RightLeaningBST.get(key));\n }\n StdOut.println(\"Expected: -5 -2 -1 0 1 2 3 5 9 99\\n\");\n\n // Test min()\n StdOut.println(\"Min key: \" + redBlackTopDown234RightLeaningBST.min() + \" Expected: -5\");\n\n // Test max()\n StdOut.println(\"Max key: \" + redBlackTopDown234RightLeaningBST.max() + \" Expected: 99\");\n\n // Test floor()\n StdOut.println(\"Floor of 5: \" + redBlackTopDown234RightLeaningBST.floor(5) + \" Expected: 5\");\n StdOut.println(\"Floor of 15: \" + redBlackTopDown234RightLeaningBST.floor(15) + \" Expected: 9\");\n\n // Test ceiling()\n StdOut.println(\"Ceiling of 5: \" + redBlackTopDown234RightLeaningBST.ceiling(5) + \" Expected: 5\");\n StdOut.println(\"Ceiling of 15: \" + redBlackTopDown234RightLeaningBST.ceiling(15) + \" Expected: 99\");\n\n // Test select()\n StdOut.println(\"Select key of rank 4: \" + redBlackTopDown234RightLeaningBST.select(4) + \" Expected: 1\");\n\n // Test rank()\n StdOut.println(\"Rank of key 9: \" + redBlackTopDown234RightLeaningBST.rank(9) + \" Expected: 8\");\n StdOut.println(\"Rank of key 10: \" + redBlackTopDown234RightLeaningBST.rank(10) + \" Expected: 9\");\n\n // Test delete()\n StdOut.println(\"\\nDelete key 2\");\n redBlackTopDown234RightLeaningBST.delete(2);\n\n for (Integer key : redBlackTopDown234RightLeaningBST.keys()) {\n StdOut.println(\"Key \" + key + \": \" + redBlackTopDown234RightLeaningBST.get(key));\n }\n StdOut.println(\"Is valid 2-3-4 tree: \" + redBlackTopDown234RightLeaningBST.isValid234RightLeaningTree() + \" Expected: true\");\n StdOut.println(\"Is BST: \" + redBlackTopDown234RightLeaningBST.isBST() + \" Expected: true\");\n StdOut.println(\"Size consistent: \" + redBlackTopDown234RightLeaningBST.isSubtreeCountConsistent() + \" Expected: true\");\n\n // Test deleteMin()\n StdOut.println(\"\\nDelete min (key -5)\");\n redBlackTopDown234RightLeaningBST.deleteMin();\n\n for (Integer key : redBlackTopDown234RightLeaningBST.keys()) {\n StdOut.println(\"Key \" + key + \": \" + redBlackTopDown234RightLeaningBST.get(key));\n }\n StdOut.println(\"Is valid 2-3-4 tree: \" + redBlackTopDown234RightLeaningBST.isValid234RightLeaningTree() + \" Expected: true\");\n StdOut.println(\"Is BST: \" + redBlackTopDown234RightLeaningBST.isBST() + \" Expected: true\");\n StdOut.println(\"Size consistent: \" + redBlackTopDown234RightLeaningBST.isSubtreeCountConsistent() + \" Expected: true\");\n\n // Test deleteMax()\n StdOut.println(\"\\nDelete max (key 99)\");\n redBlackTopDown234RightLeaningBST.deleteMax();\n\n for (Integer key : redBlackTopDown234RightLeaningBST.keys()) {\n StdOut.println(\"Key \" + key + \": \" + redBlackTopDown234RightLeaningBST.get(key));\n }\n StdOut.println(\"Is valid 2-3-4 tree: \" + redBlackTopDown234RightLeaningBST.isValid234RightLeaningTree() + \" Expected: true\");\n StdOut.println(\"Is BST: \" + redBlackTopDown234RightLeaningBST.isBST() + \" Expected: true\");\n StdOut.println(\"Size consistent: \" + redBlackTopDown234RightLeaningBST.isSubtreeCountConsistent() + \" Expected: true\");\n\n // Test keys() with range\n StdOut.println(\"\\nKeys in range [2, 10]\");\n for (Integer key : redBlackTopDown234RightLeaningBST.keys(2, 10)) {\n StdOut.println(\"Key \" + key + \": \" + redBlackTopDown234RightLeaningBST.get(key));\n }\n\n StdOut.println(\"\\nKeys in range [-4, -1]\");\n for (Integer key : redBlackTopDown234RightLeaningBST.keys(-4, -1)) {\n StdOut.println(\"Key \" + key + \": \" + redBlackTopDown234RightLeaningBST.get(key));\n }\n\n // Delete all\n StdOut.println(\"\\nDelete all\");\n while (redBlackTopDown234RightLeaningBST.size() > 0) {\n for (Integer key : redBlackTopDown234RightLeaningBST.keys()) {\n StdOut.println(\"Key \" + key + \": \" + redBlackTopDown234RightLeaningBST.get(key));\n }\n\n // redBlackIterative234BST.delete(redBlackIterative234BST.select(0));\n redBlackTopDown234RightLeaningBST.delete(redBlackTopDown234RightLeaningBST.select(redBlackTopDown234RightLeaningBST.size() - 1));\n StdOut.println(\"Is valid 2-3-4 tree: \" + redBlackTopDown234RightLeaningBST.isValid234RightLeaningTree() + \" Expected: true\");\n StdOut.println(\"Is BST: \" + redBlackTopDown234RightLeaningBST.isBST() + \" Expected: true\");\n StdOut.println(\"Size consistent: \" + redBlackTopDown234RightLeaningBST.isSubtreeCountConsistent() + \" Expected: true\");\n\n StdOut.println();\n }\n }\n\n}\n", "support_files": [], "metadata": {"number": "3.3.27", "chapter": 3, "chapter_title": "Searching", "section": 3.3, "section_title": "Balanced Search Trees", "type": "Creative Problem", "code_execution": false}} {"question": "Tree drawing. Add a method draw() to RedBlackBST that draws red-black BST figures in the style of the text (see Exercise 3.2.38).", "answer": "package chapter3.section3;\n\nimport edu.princeton.cs.algs4.StdDraw;\n\n/**\n * Created by Rene Argento on 18/06/17.\n */\npublic class Exercise31_TreeDrawing {\n\n public class RedBlackBSTDrawable, Value> extends RedBlackBST {\n\n private class Node {\n Key key;\n Value value;\n Node left, right;\n\n boolean color;\n int size;\n\n private double xCoordinate, yCoordinate;\n\n Node(Key key, Value value, int size, boolean color) {\n this.key = key;\n this.value = value;\n\n this.size = size;\n this.color = color;\n }\n }\n\n private Node root;\n private int treeLevel;\n\n public int size() {\n return size(root);\n }\n\n protected int size(Node node) {\n if (node == null) {\n return 0;\n }\n\n return node.size;\n }\n\n private boolean isRed(Node node) {\n if (node == null) {\n return false;\n }\n\n return node.color == RED;\n }\n\n private Node rotateLeft(Node node) {\n if (node == null || node.right == null) {\n return node;\n }\n\n Node newRoot = node.right;\n\n node.right = newRoot.left;\n newRoot.left = node;\n\n newRoot.color = node.color;\n node.color = RED;\n\n newRoot.size = node.size;\n node.size = size(node.left) + 1 + size(node.right);\n\n return newRoot;\n }\n\n private Node rotateRight(Node node) {\n if (node == null || node.left == null) {\n return node;\n }\n\n Node newRoot = node.left;\n\n node.left = newRoot.right;\n newRoot.right = node;\n\n newRoot.color = node.color;\n node.color = RED;\n\n newRoot.size = node.size;\n node.size = size(node.left) + 1 + size(node.right);\n\n return newRoot;\n }\n\n private void flipColors(Node node) {\n if (node == null || node.left == null || node.right == null) {\n return;\n }\n\n node.color = RED;\n node.left.color = BLACK;\n node.right.color = BLACK;\n }\n\n public void put(Key key, Value value) {\n if (key == null) {\n return;\n }\n\n root = put(root, key, value);\n root.color = BLACK;\n }\n\n private Node put(Node node, Key key, Value value) {\n if (node == null) {\n return new Node(key, value, 1, RED);\n }\n\n int compare = key.compareTo(node.key);\n\n if (compare < 0) {\n node.left = put(node.left, key, value);\n } else if (compare > 0) {\n node.right = put(node.right, key, value);\n } else {\n node.value = value;\n }\n\n if (isRed(node.right) && !isRed(node.left)) {\n node = rotateLeft(node);\n }\n if (isRed(node.left) && isRed(node.left.left)) {\n node = rotateRight(node);\n }\n if (isRed(node.left) && isRed(node.right)) {\n flipColors(node);\n }\n\n node.size = size(node.left) + 1 + size(node.right);\n return node;\n }\n\n public void draw() {\n treeLevel = 0;\n setCoordinates(root, 0.9);\n\n StdDraw.setPenColor(StdDraw.BLACK);\n drawLines(root);\n drawNodes(root);\n }\n\n private void setCoordinates(Node node, double distance) {\n if (node == null) {\n return;\n }\n\n setCoordinates(node.left, distance - 0.05);\n node.xCoordinate = (0.5 + treeLevel++) / size();\n node.yCoordinate = distance - 0.05;\n setCoordinates(node.right, distance - 0.05);\n }\n\n private void drawLines(Node node) {\n if (node == null) {\n return;\n }\n\n drawLines(node.left);\n\n if (node.left != null) {\n if (node.left.color == RED) {\n setPenToWriteRedLine();\n }\n\n StdDraw.line(node.xCoordinate, node.yCoordinate, node.left.xCoordinate, node.left.yCoordinate);\n resetPen();\n }\n if (node.right != null) {\n if (node.right.color == RED) {\n setPenToWriteRedLine();\n }\n\n StdDraw.line(node.xCoordinate, node.yCoordinate, node.right.xCoordinate, node.right.yCoordinate);\n resetPen();\n }\n\n drawLines(node.right);\n }\n\n private void setPenToWriteRedLine() {\n StdDraw.setPenColor(StdDraw.RED);\n StdDraw.setPenRadius(0.007);\n }\n\n private void resetPen() {\n StdDraw.setPenColor(StdDraw.BLACK);\n StdDraw.setPenRadius(0.0025);\n }\n\n private void drawNodes(Node node) {\n if (node == null) {\n return;\n }\n\n double nodeRadius = 0.032;\n\n drawNodes(node.left);\n\n StdDraw.setPenColor(StdDraw.WHITE);\n //Clear the node circle area\n StdDraw.filledCircle(node.xCoordinate, node.yCoordinate, nodeRadius);\n\n StdDraw.setPenColor(StdDraw.BLACK);\n StdDraw.circle(node.xCoordinate, node.yCoordinate, nodeRadius);\n StdDraw.text(node.xCoordinate, node.yCoordinate, String.valueOf(node.key));\n\n drawNodes(node.right);\n }\n }\n\n public static void main(String[] args) {\n StdDraw.setPenRadius(0.0025);\n Exercise31_TreeDrawing treeDrawing = new Exercise31_TreeDrawing();\n\n RedBlackBSTDrawable redBlackBSTDrawable = treeDrawing.new RedBlackBSTDrawable();\n\n /**\n * (B)6\n * (B)2 (B)20\n * (B)1 (B)4 (R)12 (B)25\n * (B)10 (B)15\n */\n\n redBlackBSTDrawable.put(10, \"Value 10\");\n redBlackBSTDrawable.put(4, \"Value 4\");\n redBlackBSTDrawable.put(6, \"Value 6\");\n redBlackBSTDrawable.put(1, \"Value 1\");\n redBlackBSTDrawable.put(2, \"Value 2\");\n redBlackBSTDrawable.put(15, \"Value 15\");\n redBlackBSTDrawable.put(12, \"Value 12\");\n redBlackBSTDrawable.put(20, \"Value 20\");\n redBlackBSTDrawable.put(25, \"Value 25\");\n\n StdDraw.clear(StdDraw.WHITE);\n redBlackBSTDrawable.draw();\n }\n\n}\n", "support_files": [], "metadata": {"number": "3.3.31", "chapter": 3, "chapter_title": "Searching", "section": 3.3, "section_title": "Balanced Search Trees", "type": "Creative Problem", "code_execution": false}} {"question": "AVL trees. An AVL tree is a BST where the height of every node and that of its sibling differ by at most 1. (The oldest balanced tree algorithms are based on using rotations to maintain height balance in AVL trees.) Show that coloring red links that go from nodes of even height to nodes of odd height in an AVL tree gives a (perfectly balanced) 2-3-4 tree, where red links are not necessarily left-leaning. Extra credit: Develop an implementation of the symbol-table API that uses this as the underlying data structure. One approach is to keep a height field in each node, using rotations after the recursive calls to adjust the height as necessary; another is to use the red-black representation and use methods like moveRedLeft() and moveRedRight() in Exercise 3.3.39 and Exercise 3.3.40.", "answer": "// Exercise32_AVLTrees.java\npackage chapter3.section3;\n\nimport edu.princeton.cs.algs4.Queue;\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.NoSuchElementException;\n\n/**\n * Created by Rene Argento on 29/06/17.\n */\n// Based on http://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/AVLTreeST.java.html\n// Thanks to williamcheng-web (https://github.com/williamcheng-web) for finding a bug on the height update after a rotation:\n// https://github.com/reneargento/algorithms-sedgewick-wayne/issues/162\npublic class Exercise32_AVLTrees {\n\n private class AVLTree, Value> {\n\n private class Node {\n Key key;\n Value value;\n Node left, right;\n\n int height;\n int size;\n\n Node(Key key, Value value, int size, int height) {\n this.key = key;\n this.value = value;\n\n this.size = size;\n this.height = height;\n }\n }\n\n private Node root;\n\n public int size() {\n return size(root);\n }\n\n private int size(Node node) {\n if (node == null) {\n return 0;\n }\n\n return node.size;\n }\n\n public int height() {\n return height(root);\n }\n\n private int height(Node node) {\n if (node == null) {\n return -1;\n }\n\n return node.height;\n }\n\n public boolean isEmpty() {\n return size(root) == 0;\n }\n\n private Node rotateLeft(Node node) {\n if (node == null || node.right == null) {\n return node;\n }\n\n Node newRoot = node.right;\n\n node.right = newRoot.left;\n newRoot.left = node;\n\n node.height = 1 + Math.max(height(node.left), height(node.right));\n newRoot.height = 1 + Math.max(height(newRoot.left), height(newRoot.right));\n\n newRoot.size = node.size;\n node.size = size(node.left) + 1 + size(node.right);\n\n return newRoot;\n }\n\n private Node rotateRight(Node node) {\n if (node == null || node.left == null) {\n return node;\n }\n\n Node newRoot = node.left;\n\n node.left = newRoot.right;\n newRoot.right = node;\n\n node.height = 1 + Math.max(height(node.left), height(node.right));\n newRoot.height = 1 + Math.max(height(newRoot.left), height(newRoot.right));\n\n newRoot.size = node.size;\n node.size = size(node.left) + 1 + size(node.right);\n\n return newRoot;\n }\n\n public void put(Key key, Value value) {\n if (key == null) {\n return;\n }\n\n if (value == null) {\n delete(key);\n return;\n }\n\n root = put(root, key, value);\n }\n\n private Node put(Node node, Key key, Value value) {\n if (node == null) {\n return new Node(key, value, 1, 0);\n }\n\n int compare = key.compareTo(node.key);\n\n if (compare < 0) {\n node.left = put(node.left, key, value);\n } else if (compare > 0) {\n node.right = put(node.right, key, value);\n } else {\n node.value = value;\n }\n\n node.height = 1 + Math.max(height(node.left), height(node.right));\n node.size = size(node.left) + 1 + size(node.right);\n\n return balance(node);\n }\n\n private Node balance(Node node) {\n\n if (balanceFactor(node) < -1) {\n //right-left case\n if (balanceFactor(node.right) > 0) {\n node.right = rotateRight(node.right);\n }\n node = rotateLeft(node);\n }\n\n if (balanceFactor(node) > 1) {\n //left-right case\n if (balanceFactor(node.left) < 0) {\n node.left = rotateLeft(node.left);\n }\n node = rotateRight(node);\n }\n\n return node;\n }\n\n /**\n * Returns the balance factor of the subtree. The balance factor is defined\n * as the difference in height of the left subtree and right subtree, in\n * this order. Therefore, a subtree with a balance factor of -1, 0 or 1 has\n * the AVL property since the heights of the two child subtrees differ by at\n * most one.\n */\n private int balanceFactor(Node node) {\n if (node == null) {\n return 0;\n }\n return height(node.left) - height(node.right);\n }\n\n public Value get(Key key) {\n if (key == null) {\n return null;\n }\n\n return get(root, key);\n }\n\n private Value get(Node node, Key key) {\n if (node == null) {\n return null;\n }\n\n int compare = key.compareTo(node.key);\n if (compare < 0) {\n return get(node.left, key);\n } else if (compare > 0) {\n return get(node.right, key);\n } else {\n return node.value;\n }\n }\n\n public boolean contains(Key key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Argument to contains() cannot be null\");\n }\n return get(key) != null;\n }\n\n public Key min() {\n if (root == null) {\n throw new NoSuchElementException(\"Empty binary search tree\");\n }\n\n return min(root).key;\n }\n\n private Node min(Node node) {\n if (node.left == null) {\n return node;\n }\n\n return min(node.left);\n }\n\n public Key max() {\n if (root == null) {\n throw new NoSuchElementException(\"Empty binary search tree\");\n }\n\n return max(root).key;\n }\n\n private Node max(Node node) {\n if (node.right == null) {\n return node;\n }\n\n return max(node.right);\n }\n\n //Returns the highest key in the symbol table smaller than or equal to key.\n public Key floor(Key key) {\n Node node = floor(root, key);\n if (node == null) {\n return null;\n }\n\n return node.key;\n }\n\n private Node floor(Node node, Key key) {\n if (node == null) {\n return null;\n }\n\n int compare = key.compareTo(node.key);\n\n if (compare == 0) {\n return node;\n } else if (compare < 0) {\n return floor(node.left, key);\n } else {\n Node rightNode = floor(node.right, key);\n if (rightNode != null) {\n return rightNode;\n } else {\n return node;\n }\n }\n }\n\n //Returns the smallest key in the symbol table greater than or equal to key.\n public Key ceiling(Key key) {\n Node node = ceiling(root, key);\n if (node == null) {\n return null;\n }\n\n return node.key;\n }\n\n private Node ceiling(Node node, Key key) {\n if (node == null) {\n return null;\n }\n\n int compare = key.compareTo(node.key);\n\n if (compare == 0) {\n return node;\n } else if (compare > 0) {\n return ceiling(node.right, key);\n } else {\n Node leftNode = ceiling(node.left, key);\n if (leftNode != null) {\n return leftNode;\n } else {\n return node;\n }\n }\n }\n\n public Key select(int index) {\n if (index >= size()) {\n throw new IllegalArgumentException(\"Index is higher than tree size\");\n }\n\n return select(root, index).key;\n }\n\n private Node select(Node node, int index) {\n int leftSubtreeSize = size(node.left);\n\n if (leftSubtreeSize == index) {\n return node;\n } else if (leftSubtreeSize > index) {\n return select(node.left, index);\n } else {\n return select(node.right, index - leftSubtreeSize - 1);\n }\n }\n\n public int rank(Key key) {\n return rank(root, key);\n }\n\n private int rank(Node node, Key key) {\n if (node == null) {\n return 0;\n }\n\n //Returns the number of keys less than node.key in the subtree rooted at node\n int compare = key.compareTo(node.key);\n if (compare < 0) {\n return rank(node.left, key);\n } else if (compare > 0) {\n return size(node.left) + 1 + rank(node.right, key);\n } else {\n return size(node.left);\n }\n }\n\n public void deleteMin() {\n if (isEmpty()) {\n return;\n }\n\n root = deleteMin(root);\n }\n\n private Node deleteMin(Node node) {\n if (node.left == null) {\n return node.right;\n }\n\n node.left = deleteMin(node.left);\n\n node.size = size(node.left) + 1 + size(node.right);\n node.height = 1 + Math.max(height(node.left), height(node.right));\n return balance(node);\n }\n\n public void deleteMax() {\n if (isEmpty()) {\n return;\n }\n\n root = deleteMax(root);\n }\n\n private Node deleteMax(Node node) {\n if (node.right == null) {\n return node.left;\n }\n\n node.right = deleteMax(node.right);\n\n node.size = size(node.left) + 1 + size(node.right);\n node.height = 1 + Math.max(height(node.left), height(node.right));\n return balance(node);\n }\n\n public void delete(Key key) {\n if (isEmpty()) {\n return;\n }\n\n if (!contains(key)) {\n return;\n }\n\n root = delete(root, key);\n }\n\n private Node delete(Node node, Key key) {\n if (node == null) {\n return null;\n }\n\n int compare = key.compareTo(node.key);\n\n if (compare < 0) {\n node.left = delete(node.left, key);\n } else if (compare > 0) {\n node.right = delete(node.right, key);\n } else {\n if (node.left == null) {\n return node.right;\n } else if (node.right == null) {\n return node.left;\n } else {\n Node aux = min(node.right);\n node.key = aux.key;\n node.value = aux.value;\n node.right = deleteMin(node.right);\n }\n }\n\n node.size = size(node.left) + 1 + size(node.right);\n node.height = 1 + Math.max(height(node.left), height(node.right));\n return balance(node);\n }\n\n public Iterable keys() {\n return keys(min(), max());\n }\n\n public Iterable keys(Key low, Key high) {\n if (low == null) {\n throw new IllegalArgumentException(\"First argument to keys() cannot be null\");\n }\n if (high == null) {\n throw new IllegalArgumentException(\"Second argument to keys() cannot be null\");\n }\n\n Queue queue = new Queue<>();\n keys(root, queue, low, high);\n return queue;\n }\n\n private void keys(Node node, Queue queue, Key low, Key high) {\n if (node == null) {\n return;\n }\n\n int compareLow = low.compareTo(node.key);\n int compareHigh = high.compareTo(node.key);\n\n if (compareLow < 0) {\n keys(node.left, queue, low, high);\n }\n\n if (compareLow <= 0 && compareHigh >= 0) {\n queue.enqueue(node.key);\n }\n\n if (compareHigh > 0) {\n keys(node.right, queue, low, high);\n }\n }\n\n public int size(Key low, Key high) {\n if (low == null) {\n throw new IllegalArgumentException(\"First argument to size() cannot be null\");\n }\n if (high == null) {\n throw new IllegalArgumentException(\"Second argument to size() cannot be null\");\n }\n\n if (low.compareTo(high) > 0) {\n return 0;\n }\n\n if (contains(high)) {\n return rank(high) - rank(low) + 1;\n } else {\n return rank(high) - rank(low);\n }\n }\n\n private boolean isAVL() {\n return isAVL(root);\n }\n\n private boolean isAVL(Node node) {\n if (node == null) {\n return true;\n }\n\n int balanceFactor = balanceFactor(node);\n if (balanceFactor < -1 || balanceFactor > 1) {\n return false;\n }\n\n return isAVL(node.left) && isAVL(node.right);\n }\n\n private boolean isSubtreeCountConsistent() {\n return isSubtreeCountConsistent(root);\n }\n\n private boolean isSubtreeCountConsistent(Node node) {\n if (node == null) {\n return true;\n }\n\n int totalSubtreeCount = 0;\n if (node.left != null) {\n totalSubtreeCount += node.left.size;\n }\n if (node.right != null) {\n totalSubtreeCount += node.right.size;\n }\n\n if (node.size != totalSubtreeCount + 1) {\n return false;\n }\n\n return isSubtreeCountConsistent(node.left) && isSubtreeCountConsistent(node.right);\n }\n }\n\n public static void main(String[] args) {\n Exercise32_AVLTrees avlTrees = new Exercise32_AVLTrees();\n AVLTree avlTree = avlTrees.new AVLTree<>();\n\n avlTree.put(5, 5);\n StdOut.println(\"Is AVL: \" + avlTree.isAVL() + \" Expected: true\");\n avlTree.put(1, 1);\n StdOut.println(\"Is AVL: \" + avlTree.isAVL() + \" Expected: true\");\n avlTree.put(9, 9);\n StdOut.println(\"Is AVL: \" + avlTree.isAVL() + \" Expected: true\");\n avlTree.put(2, 2);\n StdOut.println(\"Is AVL: \" + avlTree.isAVL() + \" Expected: true\");\n avlTree.put(0, 0);\n StdOut.println(\"Is AVL: \" + avlTree.isAVL() + \" Expected: true\");\n avlTree.put(99, 99);\n StdOut.println(\"Is AVL: \" + avlTree.isAVL() + \" Expected: true\");\n avlTree.put(-1, -1);\n StdOut.println(\"Is AVL: \" + avlTree.isAVL() + \" Expected: true\");\n avlTree.put(-2, -2);\n StdOut.println(\"Is AVL: \" + avlTree.isAVL() + \" Expected: true\");\n avlTree.put(3, 3);\n StdOut.println(\"Is AVL: \" + avlTree.isAVL() + \" Expected: true\");\n avlTree.put(-5, -5);\n StdOut.println(\"Is AVL: \" + avlTree.isAVL() + \" Expected: true\");\n\n StdOut.println(\"Size consistent: \" + avlTree.isSubtreeCountConsistent() + \" Expected: true\\n\");\n\n StdOut.println(\"Keys() test\");\n\n for (Integer key : avlTree.keys()) {\n StdOut.println(\"Key \" + key + \": \" + avlTree.get(key));\n }\n StdOut.println(\"Expected: -5 -2 -1 0 1 2 3 5 9 99\\n\");\n\n // Test min()\n StdOut.println(\"Min key: \" + avlTree.min() + \" Expected: -5\");\n\n // Test max()\n StdOut.println(\"Max key: \" + avlTree.max() + \" Expected: 99\");\n\n // Test floor()\n StdOut.println(\"Floor of 5: \" + avlTree.floor(5) + \" Expected: 5\");\n StdOut.println(\"Floor of 15: \" + avlTree.floor(15) + \" Expected: 9\");\n\n // Test ceiling()\n StdOut.println(\"Ceiling of 5: \" + avlTree.ceiling(5) + \" Expected: 5\");\n StdOut.println(\"Ceiling of 15: \" + avlTree.ceiling(15) + \" Expected: 99\");\n\n // Test select()\n StdOut.println(\"Select key of rank 4: \" + avlTree.select(4) + \" Expected: 1\");\n\n // Test rank()\n StdOut.println(\"Rank of key 9: \" + avlTree.rank(9) + \" Expected: 8\");\n StdOut.println(\"Rank of key 10: \" + avlTree.rank(10) + \" Expected: 9\");\n\n // Test delete()\n StdOut.println(\"\\nDelete key 2\");\n avlTree.delete(2);\n\n for (Integer key : avlTree.keys()) {\n StdOut.println(\"Key \" + key + \": \" + avlTree.get(key));\n }\n StdOut.println(\"Is AVL: \" + avlTree.isAVL() + \" Expected: true\");\n StdOut.println(\"Size consistent: \" + avlTree.isSubtreeCountConsistent() + \" Expected: true\");\n\n // Test deleteMin()\n StdOut.println(\"\\nDelete min (key -5)\");\n avlTree.deleteMin();\n\n for (Integer key : avlTree.keys()) {\n StdOut.println(\"Key \" + key + \": \" + avlTree.get(key));\n }\n StdOut.println(\"Is AVL: \" + avlTree.isAVL() + \" Expected: true\");\n StdOut.println(\"Size consistent: \" + avlTree.isSubtreeCountConsistent() + \" Expected: true\");\n\n // Test deleteMax()\n StdOut.println(\"\\nDelete max (key 99)\");\n avlTree.deleteMax();\n\n for (Integer key : avlTree.keys()) {\n StdOut.println(\"Key \" + key + \": \" + avlTree.get(key));\n }\n StdOut.println(\"Is AVL: \" + avlTree.isAVL() + \" Expected: true\");\n StdOut.println(\"Size consistent: \" + avlTree.isSubtreeCountConsistent() + \" Expected: true\");\n\n // Test keys() with range\n StdOut.println(\"\\nKeys in range [2, 10]\");\n for (Integer key : avlTree.keys(2, 10)) {\n StdOut.println(\"Key \" + key + \": \" + avlTree.get(key));\n }\n\n StdOut.println(\"\\nKeys in range [-4, -1]\");\n for (Integer key : avlTree.keys(-4, -1)) {\n StdOut.println(\"Key \" + key + \": \" + avlTree.get(key));\n }\n\n // Delete all\n StdOut.println(\"\\nDelete all\");\n while (avlTree.size() > 0) {\n for (Integer key : avlTree.keys()) {\n StdOut.println(\"Key \" + key + \": \" + avlTree.get(key));\n }\n\n // avlTree.delete(avlTree.select(0));\n avlTree.delete(avlTree.select(avlTree.size() - 1));\n StdOut.println(\"Is AVL: \" + avlTree.isAVL() + \" Expected: true\");\n StdOut.println(\"Size consistent: \" + avlTree.isSubtreeCountConsistent() + \" Expected: true\");\n\n StdOut.println();\n }\n }\n}\n\nAdditional explanation:\n3.3.32 - AVL trees\n\nColoring red links that go from nodes of even height to nodes of odd height in an AVL tree gives a perfectly balanced 2-3-4 tree.\nThis happens because every two levels of the tree will merge its nodes into 4-nodes (or 3-nodes if the node has only one child or 2-nodes if the node has no children). This generates a perfectly balanced 2-3-4 tree.\n\nFor an AVL tree of size 6:\n\n (B)H\n (B)B (B)V\n(B)A (B)C (B)R\n\n2-3 representation\n H\n B V\n A C R\n\nAfter coloring red links:\n\n (B)H\n (R)B (R)V\n(B)A (B)C (B)R\n\n2-3 representation\n BHV\n A C R\n\nFor an AVL tree of size 19:\n (B)P\n (B)L (B)T\n (B)H (B)N (B)R (B)V\n (B)F (B)J (B)M (B)O (B)Q (B)S (B)U (B)X\n(B)E (B)G (B)I (B)K\n\n2-3 representation\n P\n L T\n H N R V\n F J M O Q S U X\nE G I K\n\nAfter coloring red links:\n (B)P\n (R)L (R)T\n (B)H (B)N (B)R (B)V\n (R)F (R)J (R)M (R)O (R)Q (R)S (R)U (R)X\n(B)E (B)G (B)I (B)K\n\n2-3 representation\n LPT\n FHJ MNO QRS UVX\n E G I K\n", "support_files": [], "metadata": {"number": "3.3.32", "chapter": 3, "chapter_title": "Searching", "section": 3.3, "section_title": "Balanced Search Trees", "type": "Creative Problem", "code_execution": false}} {"question": "Certification. Add to RedBlackBST a method is23() to check that no node is connected to two red links and that there are no right-leaning red links and a method isBalanced() to check that all paths from the root to a null link have the same number of black links. Combine these methods with code from isBST() in Exercise 3.2.32 to create a method isRedBlackBST() that checks that the tree is a red-black BST.", "answer": "package chapter3.section3;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 29/06/17.\n */\n@SuppressWarnings(\"unchecked\")\npublic class Exercise33_Certification {\n\n private class RedBlackBSTCertification, Value> extends RedBlackBST {\n public boolean is23() {\n return is23(root);\n }\n\n private boolean is23(Node node) {\n if (node == null) {\n return true;\n }\n\n if (isRed(node.right)) {\n return false;\n }\n if (isRed(node) && isRed(node.left)) {\n return false;\n }\n\n return is23(node.left) && is23(node.right);\n }\n\n public boolean isBalanced() {\n int blackNodes = 0; // number of black links on path from root to min\n\n Node currentNode = root;\n while (currentNode != null) {\n if (!isRed(currentNode)) {\n blackNodes++;\n }\n\n currentNode = currentNode.left;\n }\n\n return isBalanced(root, blackNodes);\n }\n\n private boolean isBalanced(Node node, int blackNodes) {\n if (node == null) {\n return blackNodes == 0;\n }\n\n if (!isRed(node)) {\n blackNodes--;\n }\n\n return isBalanced(node.left, blackNodes) && isBalanced(node.right, blackNodes);\n }\n\n public boolean isBST() {\n return isBST(root, null, null);\n }\n\n private boolean isBST(Node node, Comparable low, Comparable high) {\n if (node == null) {\n return true;\n }\n\n if (low != null && low.compareTo(node.key) >= 0) {\n return false;\n }\n if (high != null && high.compareTo(node.key) <= 0) {\n return false;\n }\n\n return isBST(node.left, low, node.key) && isBST(node.right, node.key, high);\n }\n\n public boolean isSizeConsistent() {\n return isSizeConsistent(root);\n }\n\n private boolean isSizeConsistent(Node node) {\n if (node == null) {\n return true;\n }\n int leftSize = node.left == null ? 0 : node.left.size;\n int rightSize = node.right == null ? 0 : node.right.size;\n return node.size == leftSize + rightSize + 1\n && isSizeConsistent(node.left)\n && isSizeConsistent(node.right);\n }\n\n public boolean isRedBlackBST() {\n return isBST() && isSizeConsistent() && is23() && isBalanced();\n }\n\n }\n\n public static void main(String[] args) {\n Exercise33_Certification certification = new Exercise33_Certification();\n RedBlackBSTCertification redBlackBSTCertification = certification.new RedBlackBSTCertification<>();\n\n RedBlackBST.Node root = new RedBlackBST().new Node(10, \"Value 10\", 7, false);\n root.left = new RedBlackBST().new Node(5, \"Value 5\", 4, true);\n root.left.left = new RedBlackBST().new Node(2, \"Value 2\", 1, false);\n root.left.right = new RedBlackBST().new Node(9, \"Value 9\", 2, false);\n root.left.right.left = new RedBlackBST().new Node(7, \"Value 7\", 1, true);\n\n root.right = new RedBlackBST().new Node(14, \"Value 14\", 2, false);\n root.right.left = new RedBlackBST().new Node(11, \"Value 11\", 1, true);\n\n StdOut.println(\"Test 1\");\n StdOut.println(redBlackBSTCertification.is23(root) + \" Expected: true\");\n StdOut.println(redBlackBSTCertification.isBalanced(root, 2) + \" Expected: true\");\n StdOut.println(redBlackBSTCertification.isBST(root, null, null) + \" Expected: true\\n\");\n\n RedBlackBST.Node root2 = new RedBlackBST().new Node(20, \"Value 20\", 7, false);\n root2.left = new RedBlackBST().new Node(5, \"Value 5\", 4, true);\n root2.left.left = new RedBlackBST().new Node(2, \"Value 2\", 1, false);\n root2.left.right = new RedBlackBST().new Node(9, \"Value 9\", 2, false);\n root2.left.right.left = new RedBlackBST().new Node(1, \"Value 1\", 1, true); //Not a BST\n\n root2.right = new RedBlackBST().new Node(24, \"Value 24\", 2, false);\n root2.right.left = new RedBlackBST().new Node(21, \"Value 21\", 1, true);\n\n StdOut.println(\"Test 2\");\n StdOut.println(redBlackBSTCertification.is23(root2) + \" Expected: true\");\n StdOut.println(redBlackBSTCertification.isBalanced(root2, 2) + \" Expected: true\");\n StdOut.println(redBlackBSTCertification.isBST(root2, null, null) + \" Expected: false\\n\");\n\n RedBlackBST.Node root3 = new RedBlackBST().new Node(10, \"Value 10\", 7, false);\n root3.left = new RedBlackBST().new Node(5, \"Value 5\", 4, true);\n root3.left.left = new RedBlackBST().new Node(2, \"Value 2\", 1, false);\n root3.left.right = new RedBlackBST().new Node(9, \"Value 9\", 2, false);\n root3.left.right.left = new RedBlackBST().new Node(7, \"Value 7\", 1, true);\n\n root3.right = new RedBlackBST().new Node(14, \"Value 14\", 2, true); //Not 2-3 tree, not balanced\n root3.right.left = new RedBlackBST().new Node(11, \"Value 11\", 1, true);\n\n StdOut.println(\"Test 3\");\n StdOut.println(redBlackBSTCertification.is23(root3) + \" Expected: false\");\n StdOut.println(redBlackBSTCertification.isBalanced(root3, 2) + \" Expected: false\");\n StdOut.println(redBlackBSTCertification.isBST(root3, null, null) + \" Expected: true\\n\");\n\n RedBlackBST.Node root4 = new RedBlackBST().new Node(10, \"Value 10\", 7, false);\n root4.left = new RedBlackBST().new Node(5, \"Value 5\", 4, true);\n root4.left.left = new RedBlackBST().new Node(2, \"Value 2\", 1, true); //Not 2-3 tree, not balanced\n root4.left.right = new RedBlackBST().new Node(9, \"Value 9\", 2, false);\n root4.left.right.left = new RedBlackBST().new Node(7, \"Value 7\", 1, true);\n\n root4.right = new RedBlackBST().new Node(14, \"Value 14\", 2, false);\n root4.right.left = new RedBlackBST().new Node(11, \"Value 11\", 1, true);\n\n StdOut.println(\"Test 4\");\n StdOut.println(redBlackBSTCertification.is23(root4) + \" Expected: false\");\n StdOut.println(redBlackBSTCertification.isBalanced(root4, 2) + \" Expected: false\");\n StdOut.println(redBlackBSTCertification.isBST(root4, null, null) + \" Expected: true\");\n }\n\n}\n", "support_files": [], "metadata": {"number": "3.3.33", "chapter": 3, "chapter_title": "Searching", "section": 3.3, "section_title": "Balanced Search Trees", "type": "Creative Problem", "code_execution": false}} {"question": "All 2-3 trees. Write code to generate all structurally different 2-3 trees of height 2, 3, and 4. There are 2, 7, and 112 such trees, respectively. (Hint: Use a symbol table.)", "answer": "package chapter3.section3;\n\nimport edu.princeton.cs.algs4.Queue;\nimport edu.princeton.cs.algs4.StdOut;\nimport edu.princeton.cs.algs4.StdRandom;\n\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\n\n/**\n * Created by Rene Argento on 01/07/17.\n */\n@SuppressWarnings(\"unchecked\")\npublic class Exercise34_All23Trees {\n private static Map differentTreeStructures = new HashMap<>();\n\n private Set> generateTrees(int height, Set> heightMinus1Trees,\n Set keysInTree) {\n Set> generatedTrees = new HashSet<>();\n\n int nodesInLevel = (int) Math.pow(2, height);\n int structuresToGenerate = differentTreeStructures.get(height);\n\n int nodesToAdd;\n // Used to change the insertion order and generate different tree structures\n int insertionsBeforeSwitchToLeftSide = 1; //always 1\n int insertionsBeforeSwitchToRightSide = 1; //starts at 1\n int insertions;\n\n while (structuresToGenerate > 0) {\n for (RedBlackBST previousTree : heightMinus1Trees) {\n\n RedBlackBST currentTree = copyTree(previousTree);\n\n boolean addToLeftSubtree = true;\n nodesToAdd = nodesInLevel;\n insertions = 0;\n\n while (nodesToAdd > 0) {\n addKeyToTree(currentTree, addToLeftSubtree, keysInTree);\n nodesToAdd--;\n insertions++;\n\n if ((addToLeftSubtree && insertions == insertionsBeforeSwitchToRightSide)\n || (!addToLeftSubtree && insertions == insertionsBeforeSwitchToLeftSide)) {\n addToLeftSubtree = !addToLeftSubtree;\n insertions = 0;\n }\n }\n\n generatedTrees.add(currentTree);\n structuresToGenerate--;\n if (structuresToGenerate == 0) {\n break;\n }\n\n insertionsBeforeSwitchToRightSide++;\n }\n }\n return generatedTrees;\n }\n\n private void addKeyToTree(RedBlackBST currentTree, boolean addToLeftSubtree, Set keysInTree) {\n int median = currentTree.select(currentTree.size() / 2);\n int lowerBound;\n int higherBound;\n\n if (addToLeftSubtree) {\n lowerBound = 0;\n higherBound = median;\n } else {\n lowerBound = median;\n higherBound = Integer.MAX_VALUE;\n }\n\n int randomKey = StdRandom.uniform(lowerBound, higherBound);\n\n while (keysInTree.contains(randomKey)) {\n randomKey = StdRandom.uniform(lowerBound, higherBound);\n }\n\n keysInTree.add(randomKey);\n currentTree.put(randomKey, randomKey);\n }\n\n private RedBlackBST copyTree(RedBlackBST tree) {\n RedBlackBST.Node root = tree.root;\n\n if (root == null) {\n return null;\n }\n\n Queue queue = new Queue<>();\n queue.enqueue(tree.root);\n\n RedBlackBST.Node newRoot = new RedBlackBST().new Node(root.key, root.value, root.size, root.color);\n Queue newTreeQueue = new Queue<>();\n newTreeQueue.enqueue(newRoot);\n\n while (!queue.isEmpty()) {\n RedBlackBST.Node current = queue.dequeue();\n RedBlackBST.Node currentNewTree = newTreeQueue.dequeue();\n\n if (current.left != null) {\n currentNewTree.left = new RedBlackBST().new Node(current.left.key, current.left.value,\n current.left.size, current.left.color);\n\n queue.enqueue(current.left);\n newTreeQueue.enqueue(currentNewTree.left);\n }\n if (current.right != null) {\n currentNewTree.right = new RedBlackBST().new Node(current.right.key, current.right.value,\n current.right.size, current.right.color);\n\n queue.enqueue(current.right);\n newTreeQueue.enqueue(currentNewTree.right);\n }\n }\n\n RedBlackBST copyTree = new RedBlackBST<>();\n copyTree.root = newRoot;\n return copyTree;\n }\n\n public static void main(String[] args) {\n Exercise34_All23Trees all23Trees = new Exercise34_All23Trees();\n\n Set> generatedTrees = new HashSet<>();\n Set keysInTree = new HashSet<>();\n\n Set> treesOfHeight1 = new HashSet<>();\n RedBlackBST height1Tree = new RedBlackBST<>();\n for (int i = 0; i < 3; i++) {\n int randomKey = StdRandom.uniform(Integer.MAX_VALUE);\n height1Tree.put(randomKey, randomKey);\n keysInTree.add(randomKey);\n }\n\n treesOfHeight1.add(height1Tree);\n\n differentTreeStructures.put(2, 2);\n differentTreeStructures.put(3, 7);\n // According to http://algs4.cs.princeton.edu/errata/errata-printing8.php\n // there are 112 structurally different 2-3 trees of height 4\n differentTreeStructures.put(4, 112);\n\n // Height = 2\n Set> treesOfHeight2 = all23Trees.generateTrees(2, treesOfHeight1, keysInTree);\n generatedTrees.addAll(treesOfHeight2);\n\n // Height = 3\n Set> treesOfHeight3 = all23Trees.generateTrees(3, treesOfHeight2, keysInTree);\n generatedTrees.addAll(treesOfHeight3);\n\n // Height = 4\n Set> treesOfHeight4 = all23Trees.generateTrees(4, treesOfHeight3, keysInTree);\n generatedTrees.addAll(treesOfHeight4);\n\n StdOut.println(\"Number of trees generated: \" + generatedTrees.size());\n }\n}\n", "support_files": [], "metadata": {"number": "3.3.34", "chapter": 3, "chapter_title": "Searching", "section": 3.3, "section_title": "Balanced Search Trees", "type": "Creative Problem", "code_execution": false}} {"question": "2-3 trees. Write a program TwoThreeST.java that uses two node types to implement 2-3 search trees directly.", "answer": "package chapter3.section3;\n\nimport edu.princeton.cs.algs4.Queue;\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.NoSuchElementException;\n\n/**\n * Created by Rene Argento on 02/07/17.\n */\n@SuppressWarnings(\"unchecked\")\npublic class Exercise35_23Trees {\n\n private static class TwoThreeST, Value> {\n\n private class Node {\n Node left, right;\n int size;\n\n Node(int size) {\n this.size = size;\n }\n }\n\n private class TwoNode extends Node {\n Key key;\n Value value;\n\n TwoNode(Key key, Value value, int size) {\n super(size);\n this.key = key;\n this.value = value;\n }\n }\n\n private class ThreeNode extends Node {\n Node middle;\n\n Key leftKey;\n Value leftValue;\n\n Key rightKey;\n Value rightValue;\n\n ThreeNode(Key leftKey, Value leftValue, Key rightKey, Value rightValue, int size) {\n super(size);\n\n this.leftKey = leftKey;\n this.leftValue = leftValue;\n this.rightKey = rightKey;\n this.rightValue = rightValue;\n }\n }\n\n private class FourNode extends Node {\n Node middle1;\n Node middle2;\n\n Key leftKey;\n Value leftValue;\n\n Key middleKey;\n Value middleValue;\n\n Key rightKey;\n Value rightValue;\n\n FourNode(Key leftKey, Value leftValue, Key middleKey, Value middleValue, Key rightKey, Value rightValue, int size) {\n super(size);\n\n this.leftKey = leftKey;\n this.leftValue = leftValue;\n this.middleKey = middleKey;\n this.middleValue = middleValue;\n this.rightKey = rightKey;\n this.rightValue = rightValue;\n }\n }\n\n private Node root;\n\n private enum NodePosition {\n LEFT, MIDDLE1, MIDDLE2, RIGHT\n }\n\n private int getNodePositionValue(Node parent, NodePosition nodePosition) {\n int value = 0;\n\n if (is2Node(parent)) {\n switch (nodePosition) {\n case LEFT: value = 0; break;\n case RIGHT: value = 1; break;\n }\n } else if (is3Node(parent)) {\n switch (nodePosition) {\n case LEFT: value = 0; break;\n case MIDDLE1: value = 1; break;\n case RIGHT: value = 2; break;\n }\n } else {\n switch (nodePosition) {\n case LEFT: value = 0; break;\n case MIDDLE1: value = 1; break;\n case MIDDLE2: value = 2; break;\n case RIGHT: value = 3; break;\n }\n }\n\n return value;\n }\n\n public int size() {\n return size(root);\n }\n\n private int size(Node node) {\n if (node == null) {\n return 0;\n }\n\n return node.size;\n }\n\n public boolean isEmpty() {\n return size(root) == 0;\n }\n\n private boolean is2Node(Node node) {\n if (node == null) {\n return false;\n }\n\n return node instanceof TwoThreeST.TwoNode;\n }\n\n private boolean is3Node(Node node) {\n if (node == null) {\n return false;\n }\n\n return node instanceof TwoThreeST.ThreeNode;\n }\n\n private boolean is4Node(Node node) {\n if (node == null) {\n return false;\n }\n\n return node instanceof TwoThreeST.FourNode;\n }\n\n private TwoNode split4Node(FourNode fourNode) {\n int leftNodeSize = size(fourNode.left) + 1 + size(fourNode.middle1);\n int rightNodeSize = size(fourNode.middle2) + 1 + size(fourNode.right);\n int middleNodeSize = leftNodeSize + 1 + rightNodeSize;\n\n TwoNode leftNode = new TwoNode(fourNode.leftKey, fourNode.leftValue, leftNodeSize);\n TwoNode middleNode = new TwoNode(fourNode.middleKey, fourNode.middleValue, middleNodeSize);\n TwoNode rightNode = new TwoNode(fourNode.rightKey, fourNode.rightValue, rightNodeSize);\n\n leftNode.left = fourNode.left;\n leftNode.right = fourNode.middle1;\n\n rightNode.left = fourNode.middle2;\n rightNode.right = fourNode.right;\n\n middleNode.left = leftNode;\n middleNode.right = rightNode;\n\n return middleNode;\n }\n\n private TwoNode split3NodeAndMakeRightNodeParent(ThreeNode threeNode) {\n int leftNodeSize = size(threeNode.left) + 1 + size(threeNode.middle);\n int rightNodeSize = leftNodeSize + 1 + size(threeNode.right);\n\n TwoNode leftNode = new TwoNode(threeNode.leftKey, threeNode.leftValue, leftNodeSize);\n TwoNode rightNode = new TwoNode(threeNode.rightKey, threeNode.rightValue, rightNodeSize);\n\n leftNode.left = threeNode.left;\n leftNode.right = threeNode.middle;\n\n rightNode.left = leftNode;\n rightNode.right = threeNode.right;\n\n return rightNode;\n }\n\n private TwoNode split3NodeAndMakeLeftNodeParent(ThreeNode threeNode) {\n int rightNodeSize = size(threeNode.right) + 1 + size(threeNode.middle);\n int leftNodeSize = size(threeNode.left) + 1 + rightNodeSize;\n\n TwoNode leftNode = new TwoNode(threeNode.leftKey, threeNode.leftValue, leftNodeSize);\n TwoNode rightNode = new TwoNode(threeNode.rightKey, threeNode.rightValue, rightNodeSize);\n\n leftNode.left = threeNode.left;\n leftNode.right = rightNode;\n\n rightNode.left = threeNode.middle;\n rightNode.right = threeNode.right;\n\n return leftNode;\n }\n\n private ThreeNode generate3Node(TwoNode parentNode, TwoNode newNode) {\n boolean isLeftNode = parentNode.key.compareTo(newNode.key) > 0;\n\n ThreeNode newThreeNode;\n int newSize = parentNode.size;\n if (isLeftNode) {\n newThreeNode = new ThreeNode(newNode.key, newNode.value, parentNode.key,\n parentNode.value, newSize);\n newThreeNode.left = newNode.left;\n newThreeNode.middle = newNode.right;\n newThreeNode.right = parentNode.right;\n } else {\n newThreeNode = new ThreeNode(parentNode.key, parentNode.value, newNode.key,\n newNode.value, newSize);\n newThreeNode.left = parentNode.left;\n newThreeNode.middle = newNode.left;\n newThreeNode.right = newNode.right;\n }\n\n return newThreeNode;\n }\n\n private FourNode generate4Node(ThreeNode parentNode, TwoNode newNode) {\n boolean isLeftNode = parentNode.leftKey.compareTo(newNode.key) > 0;\n boolean isRightNode = parentNode.rightKey.compareTo(newNode.key) < 0;\n\n //Create temporary 4-node\n FourNode newFourNode;\n int newSize = parentNode.size;\n if (isLeftNode) {\n newFourNode = new FourNode(newNode.key, newNode.value, parentNode.leftKey, parentNode.leftValue,\n parentNode.rightKey, parentNode.rightValue, newSize);\n newFourNode.left = newNode.left;\n newFourNode.middle1 = newNode.right;\n newFourNode.middle2 = parentNode.middle;\n newFourNode.right = parentNode.right;\n } else if (isRightNode) {\n newFourNode = new FourNode(parentNode.leftKey, parentNode.leftValue,\n parentNode.rightKey, parentNode.rightValue, newNode.key, newNode.value, newSize);\n newFourNode.left = parentNode.left;\n newFourNode.middle1 = parentNode.middle;\n newFourNode.middle2 = newNode.left;\n newFourNode.right = newNode.right;\n } else {\n newFourNode = new FourNode(parentNode.leftKey, parentNode.leftValue, newNode.key, newNode.value,\n parentNode.rightKey, parentNode.rightValue, newSize);\n newFourNode.left = parentNode.left;\n newFourNode.middle1 = newNode.left;\n newFourNode.middle2 = newNode.right;\n newFourNode.right = parentNode.right;\n }\n\n return newFourNode;\n }\n\n /**\n * Source node - Child node to move threeNode from\n * Destination node - Child node to move threeNode to\n */\n private Node moveKey(Node parent, NodePosition sourceNodePosition, NodePosition destinationNodePosition) {\n int source = getNodePositionValue(parent, sourceNodePosition);\n int destination = getNodePositionValue(parent, destinationNodePosition);\n boolean isMoveLeft = source > destination;\n\n if (isMoveLeft) {\n while (destination < source) {\n //Default values for 2-node\n Node temporarySource = parent.right;\n Node temporaryDestination = parent.left;\n\n if (is3Node(parent)) {\n ThreeNode threeNodeParent = (ThreeNode) parent;\n\n switch (source) {\n case 2:\n temporarySource = threeNodeParent.right;\n temporaryDestination = threeNodeParent.middle;\n\n sourceNodePosition = NodePosition.RIGHT;\n destinationNodePosition = NodePosition.MIDDLE1;\n break;\n case 1:\n temporarySource = threeNodeParent.middle;\n temporaryDestination = threeNodeParent.left;\n\n sourceNodePosition = NodePosition.MIDDLE1;\n destinationNodePosition = NodePosition.LEFT;\n break;\n }\n } else if (is4Node(parent)) {\n FourNode fourNode = (FourNode) parent;\n\n switch (source) {\n case 3:\n temporarySource = fourNode.right;\n temporaryDestination = fourNode.middle2;\n\n sourceNodePosition = NodePosition.RIGHT;\n destinationNodePosition = NodePosition.MIDDLE2;\n break;\n case 2:\n temporarySource = fourNode.middle2;\n temporaryDestination = fourNode.middle1;\n\n sourceNodePosition = NodePosition.MIDDLE2;\n destinationNodePosition = NodePosition.MIDDLE1;\n break;\n case 1:\n temporarySource = fourNode.middle1;\n temporaryDestination = fourNode.left;\n\n sourceNodePosition = NodePosition.MIDDLE1;\n destinationNodePosition = NodePosition.LEFT;\n break;\n }\n }\n\n //Invert temporaryDestination and temporarySource parameters when going left\n parent = moveKeyBetweenImmediateSiblings(parent, temporaryDestination, temporarySource,\n sourceNodePosition, destinationNodePosition);\n source--;\n }\n } else {\n while (source < destination) {\n //Default values for 2-node\n Node temporarySource = parent.left;\n Node temporaryDestination = parent.right;\n\n if (is3Node(parent)) {\n ThreeNode threeNodeParent = (ThreeNode) parent;\n\n switch (source) {\n case 0:\n temporarySource = threeNodeParent.left;\n temporaryDestination = threeNodeParent.middle;\n\n sourceNodePosition = NodePosition.LEFT;\n destinationNodePosition = NodePosition.MIDDLE1;\n break;\n case 1:\n temporarySource = threeNodeParent.middle;\n temporaryDestination = threeNodeParent.right;\n\n sourceNodePosition = NodePosition.MIDDLE1;\n destinationNodePosition = NodePosition.RIGHT;\n break;\n }\n } else if (is4Node(parent)) {\n FourNode fourNode = (FourNode) parent;\n\n switch (source) {\n case 0:\n temporarySource = fourNode.left;\n temporaryDestination = fourNode.middle1;\n\n sourceNodePosition = NodePosition.LEFT;\n destinationNodePosition = NodePosition.MIDDLE1;\n break;\n case 1:\n temporarySource = fourNode.middle1;\n temporaryDestination = fourNode.middle2;\n\n sourceNodePosition = NodePosition.MIDDLE1;\n destinationNodePosition = NodePosition.MIDDLE2;\n break;\n case 2:\n temporarySource = fourNode.middle2;\n temporaryDestination = fourNode.right;\n\n sourceNodePosition = NodePosition.MIDDLE2;\n destinationNodePosition = NodePosition.RIGHT;\n break;\n }\n }\n\n parent = moveKeyBetweenImmediateSiblings(parent, temporarySource, temporaryDestination,\n sourceNodePosition, destinationNodePosition);\n source++;\n }\n }\n\n return parent;\n }\n\n private Node moveKeyBetweenImmediateSiblings(Node parent, Node leftChild, Node rightChild,\n NodePosition sourceNodePosition, NodePosition destinationNodePosition) {\n int source = getNodePositionValue(parent, sourceNodePosition);\n int destination = getNodePositionValue(parent, destinationNodePosition);\n\n boolean isMoveLeft = source > destination;\n\n if (isMoveLeft) {\n if (is2Node(rightChild)) {\n //No point in moving a 2-node\n return parent;\n } else if (is3Node(rightChild)) {\n ThreeNode rightChildThreeNode = (ThreeNode) rightChild;\n Node newLeftChild;\n\n if (is2Node(parent)) {\n TwoNode twoNodeParent = (TwoNode) parent;\n\n if (leftChild != null) {\n TwoNode twoNodeLeftChild = (TwoNode) leftChild;\n newLeftChild = new ThreeNode(twoNodeLeftChild.key, twoNodeLeftChild.value,\n twoNodeParent.key, twoNodeParent.value, leftChild.size + 1 + size(rightChild.left));\n\n newLeftChild.left = leftChild.left;\n ((ThreeNode) newLeftChild).middle = leftChild.right;\n } else {\n newLeftChild = new TwoNode(twoNodeParent.key, twoNodeParent.value, 1);\n }\n newLeftChild.right = rightChildThreeNode.left;\n\n twoNodeParent.key = rightChildThreeNode.leftKey;\n twoNodeParent.value = rightChildThreeNode.leftValue;\n\n TwoNode newRightChild = new TwoNode(rightChildThreeNode.rightKey, rightChildThreeNode.rightValue,\n rightChildThreeNode.size - 1 - size(rightChild.left));\n newRightChild.left = rightChildThreeNode.middle;\n newRightChild.right = rightChildThreeNode.right;\n\n twoNodeParent.left = newLeftChild;\n twoNodeParent.right = newRightChild;\n } else if (is3Node(parent)) {\n ThreeNode threeNodeParent = (ThreeNode) parent;\n TwoNode newRightChild;\n\n switch (source) {\n case 1:\n if (leftChild != null) {\n TwoNode twoNodeLeftChild = (TwoNode) leftChild;\n newLeftChild = new ThreeNode(twoNodeLeftChild.key, twoNodeLeftChild.value,\n threeNodeParent.leftKey, threeNodeParent.leftValue, leftChild.size + 1\n + size(rightChild.left));\n\n newLeftChild.left = leftChild.left;\n ((ThreeNode) newLeftChild).middle = leftChild.right;\n } else {\n newLeftChild = new TwoNode(threeNodeParent.leftKey, threeNodeParent.leftValue, 1);\n }\n newLeftChild.right = rightChildThreeNode.left;\n\n threeNodeParent.leftKey = rightChildThreeNode.leftKey;\n threeNodeParent.leftValue = rightChildThreeNode.leftValue;\n\n newRightChild = new TwoNode(rightChildThreeNode.rightKey, rightChildThreeNode.rightValue,\n rightChildThreeNode.size - 1 - size(rightChild.left));\n newRightChild.left = rightChildThreeNode.middle;\n newRightChild.right = rightChildThreeNode.right;\n\n threeNodeParent.left = newLeftChild;\n threeNodeParent.middle = newRightChild;\n\n break;\n case 2:\n if (leftChild != null) {\n TwoNode twoNodeLeftChild = (TwoNode) leftChild;\n newLeftChild = new ThreeNode(twoNodeLeftChild.key, twoNodeLeftChild.value,\n threeNodeParent.rightKey, threeNodeParent.rightValue, leftChild.size + 1\n + size(rightChild.left));\n\n newLeftChild.left = leftChild.left;\n ((ThreeNode) newLeftChild).middle = leftChild.right;\n } else {\n newLeftChild = new TwoNode(threeNodeParent.rightKey, threeNodeParent.rightValue, 1);\n }\n newLeftChild.right = rightChildThreeNode.left;\n\n threeNodeParent.rightKey = rightChildThreeNode.leftKey;\n threeNodeParent.rightValue = rightChildThreeNode.leftValue;\n\n newRightChild = new TwoNode(rightChildThreeNode.rightKey, rightChildThreeNode.rightValue,\n rightChildThreeNode.size - 1 - size(rightChild.left));\n newRightChild.left = rightChildThreeNode.middle;\n newRightChild.right = rightChildThreeNode.right;\n\n threeNodeParent.middle = newLeftChild;\n threeNodeParent.right = newRightChild;\n\n break;\n }\n } else if (is4Node(parent)) {\n FourNode fourNodeParent = (FourNode) parent;\n TwoNode newRightChild;\n\n switch (source) {\n case 1:\n if (leftChild != null) {\n TwoNode twoNodeLeftChild = (TwoNode) leftChild;\n newLeftChild = new ThreeNode(twoNodeLeftChild.key, twoNodeLeftChild.value,\n fourNodeParent.leftKey, fourNodeParent.leftValue, leftChild.size + 1\n + size(rightChild.left));\n\n newLeftChild.left = leftChild.left;\n ((ThreeNode) newLeftChild).middle = leftChild.right;\n } else {\n newLeftChild = new TwoNode(fourNodeParent.leftKey, fourNodeParent.leftValue, 1);\n }\n newLeftChild.right = rightChildThreeNode.left;\n\n fourNodeParent.leftKey = rightChildThreeNode.leftKey;\n fourNodeParent.leftValue = rightChildThreeNode.leftValue;\n\n newRightChild = new TwoNode(rightChildThreeNode.rightKey, rightChildThreeNode.rightValue,\n rightChildThreeNode.size - 1 - size(rightChild.left));\n newRightChild.left = rightChildThreeNode.middle;\n newRightChild.right = rightChildThreeNode.right;\n\n fourNodeParent.left = newLeftChild;\n fourNodeParent.middle1 = newRightChild;\n\n break;\n case 2:\n if (leftChild != null) {\n TwoNode twoNodeLeftChild = (TwoNode) leftChild;\n newLeftChild = new ThreeNode(twoNodeLeftChild.key, twoNodeLeftChild.value,\n fourNodeParent.middleKey, fourNodeParent.middleValue, leftChild.size + 1\n + size(rightChild.left));\n\n newLeftChild.left = leftChild.left;\n ((ThreeNode) newLeftChild).middle = leftChild.right;\n } else {\n newLeftChild = new TwoNode(fourNodeParent.middleKey, fourNodeParent.middleValue, 1);\n }\n newLeftChild.right = rightChildThreeNode.left;\n\n fourNodeParent.middleKey = rightChildThreeNode.leftKey;\n fourNodeParent.middleValue = rightChildThreeNode.leftValue;\n\n newRightChild = new TwoNode(rightChildThreeNode.rightKey, rightChildThreeNode.rightValue,\n rightChildThreeNode.size - 1 - size(rightChild.left));\n newRightChild.left = rightChildThreeNode.middle;\n newRightChild.right = rightChildThreeNode.right;\n\n fourNodeParent.middle1 = newLeftChild;\n fourNodeParent.middle2 = newRightChild;\n\n break;\n case 3:\n if (leftChild != null) {\n TwoNode twoNodeLeftChild = (TwoNode) leftChild;\n newLeftChild = new ThreeNode(twoNodeLeftChild.key, twoNodeLeftChild.value,\n fourNodeParent.rightKey, fourNodeParent.rightValue, leftChild.size + 1\n + size(rightChild.left));\n\n newLeftChild.left = leftChild.left;\n ((ThreeNode) newLeftChild).middle = leftChild.right;\n } else {\n newLeftChild = new TwoNode(fourNodeParent.rightKey, fourNodeParent.rightValue, 1);\n }\n newLeftChild.right = rightChildThreeNode.left;\n\n fourNodeParent.rightKey = rightChildThreeNode.leftKey;\n fourNodeParent.rightValue = rightChildThreeNode.leftValue;\n\n newRightChild = new TwoNode(rightChildThreeNode.rightKey, rightChildThreeNode.rightValue,\n rightChildThreeNode.size - 1 - size(rightChild.left));\n newRightChild.left = rightChildThreeNode.middle;\n newRightChild.right = rightChildThreeNode.right;\n\n fourNodeParent.middle2 = newLeftChild;\n fourNodeParent.right = newRightChild;\n\n break;\n }\n }\n }\n } else {\n if (is2Node(leftChild)) {\n //No point in moving a 2-node\n return parent;\n } else if (is3Node(leftChild)) {\n ThreeNode leftChildThreeNode = (ThreeNode) leftChild;\n Node newRightChild;\n\n if (is2Node(parent)) {\n TwoNode twoNodeParent = (TwoNode) parent;\n\n if (rightChild != null) {\n TwoNode twoNodeRightChild = (TwoNode) rightChild;\n newRightChild = new ThreeNode(twoNodeParent.key, twoNodeParent.value,\n twoNodeRightChild.key, twoNodeRightChild.value,rightChild.size + 1\n + size(leftChild.right));\n\n newRightChild.right = rightChild.right;\n ((ThreeNode) newRightChild).middle = rightChild.left;\n } else {\n newRightChild = new TwoNode(twoNodeParent.key, twoNodeParent.value, 1);\n }\n newRightChild.left = leftChildThreeNode.right;\n\n twoNodeParent.key = leftChildThreeNode.rightKey;\n twoNodeParent.value = leftChildThreeNode.rightValue;\n\n TwoNode newLeftChild = new TwoNode(leftChildThreeNode.leftKey, leftChildThreeNode.leftValue,\n leftChildThreeNode.size - 1 - size(leftChild.right));\n newLeftChild.left = leftChildThreeNode.left;\n newLeftChild.right = leftChildThreeNode.middle;\n\n twoNodeParent.left = newLeftChild;\n twoNodeParent.right = newRightChild;\n } else if (is3Node(parent)) {\n ThreeNode threeNodeParent = (ThreeNode) parent;\n TwoNode newLeftChild;\n\n switch (source) {\n case 0:\n if (rightChild != null) {\n TwoNode twoNodeRightChild = (TwoNode) rightChild;\n newRightChild = new ThreeNode(threeNodeParent.leftKey, threeNodeParent.leftValue,\n twoNodeRightChild.key, twoNodeRightChild.value,rightChild.size + 1\n + size(leftChild.right));\n\n newRightChild.right = rightChild.right;\n ((ThreeNode) newRightChild).middle = rightChild.left;\n } else {\n newRightChild = new TwoNode(threeNodeParent.leftKey, threeNodeParent.leftValue, 1);\n }\n newRightChild.left = leftChildThreeNode.right;\n\n threeNodeParent.leftKey = leftChildThreeNode.rightKey;\n threeNodeParent.leftValue = leftChildThreeNode.rightValue;\n\n newLeftChild = new TwoNode(leftChildThreeNode.leftKey, leftChildThreeNode.leftValue,\n leftChildThreeNode.size - 1 - size(leftChild.right));\n newLeftChild.left = leftChildThreeNode.left;\n newLeftChild.right = leftChildThreeNode.middle;\n\n threeNodeParent.left = newLeftChild;\n threeNodeParent.middle = newRightChild;\n\n break;\n case 1:\n if (rightChild != null) {\n TwoNode twoNodeRightChild = (TwoNode) rightChild;\n newRightChild = new ThreeNode(threeNodeParent.rightKey, threeNodeParent.rightValue,\n twoNodeRightChild.key, twoNodeRightChild.value,rightChild.size + 1\n + size(leftChild.right));\n\n newRightChild.right = rightChild.right;\n ((ThreeNode) newRightChild).middle = rightChild.left;\n } else {\n newRightChild = new TwoNode(threeNodeParent.rightKey, threeNodeParent.rightValue, 1);\n }\n newRightChild.left = leftChildThreeNode.right;\n\n threeNodeParent.rightKey = leftChildThreeNode.rightKey;\n threeNodeParent.rightValue = leftChildThreeNode.rightValue;\n\n newLeftChild = new TwoNode(leftChildThreeNode.leftKey, leftChildThreeNode.leftValue,\n leftChildThreeNode.size - 1 - size(leftChild.right));\n newLeftChild.left = leftChildThreeNode.left;\n newLeftChild.right = leftChildThreeNode.middle;\n\n threeNodeParent.middle = newLeftChild;\n threeNodeParent.right = newRightChild;\n\n break;\n }\n } else if (is4Node(parent)) {\n FourNode fourNodeParent = (FourNode) parent;\n TwoNode newLeftChild;\n\n switch (source) {\n case 0:\n if (rightChild != null) {\n TwoNode twoNodeRightChild = (TwoNode) rightChild;\n newRightChild = new ThreeNode(fourNodeParent.leftKey, fourNodeParent.leftValue,\n twoNodeRightChild.key, twoNodeRightChild.value, rightChild.size + 1\n + size(leftChild.right));\n\n newRightChild.right = rightChild.right;\n ((ThreeNode) newRightChild).middle = rightChild.left;\n } else {\n newRightChild = new TwoNode(fourNodeParent.leftKey, fourNodeParent.leftValue, 1);\n }\n newRightChild.left = leftChildThreeNode.right;\n\n fourNodeParent.leftKey = leftChildThreeNode.rightKey;\n fourNodeParent.leftValue = leftChildThreeNode.rightValue;\n\n newLeftChild = new TwoNode(leftChildThreeNode.leftKey, leftChildThreeNode.leftValue,\n leftChildThreeNode.size - 1 - size(leftChild.right));\n newLeftChild.left = leftChildThreeNode.left;\n newLeftChild.right = leftChildThreeNode.middle;\n\n fourNodeParent.left = newLeftChild;\n fourNodeParent.middle1 = newRightChild;\n\n break;\n case 2:\n if (rightChild != null) {\n TwoNode twoNodeRightChild = (TwoNode) rightChild;\n newRightChild = new ThreeNode(fourNodeParent.middleKey, fourNodeParent.middleValue,\n twoNodeRightChild.key, twoNodeRightChild.value,rightChild.size + 1\n + size(leftChild.right));\n\n newRightChild.right = rightChild.right;\n ((ThreeNode) newRightChild).middle = rightChild.left;\n } else {\n newRightChild = new TwoNode(fourNodeParent.middleKey, fourNodeParent.middleValue, 1);\n }\n newRightChild.left = leftChildThreeNode.right;\n\n fourNodeParent.middleKey = leftChildThreeNode.rightKey;\n fourNodeParent.middleValue = leftChildThreeNode.rightValue;\n\n newLeftChild = new TwoNode(leftChildThreeNode.leftKey, leftChildThreeNode.leftValue,\n leftChildThreeNode.size - 1 - size(leftChild.right));\n newLeftChild.left = leftChildThreeNode.left;\n newLeftChild.right = leftChildThreeNode.middle;\n\n fourNodeParent.middle1 = newLeftChild;\n fourNodeParent.middle2 = newRightChild;\n\n break;\n case 3:\n if (rightChild != null) {\n TwoNode twoNodeRightChild = (TwoNode) rightChild;\n newRightChild = new ThreeNode(fourNodeParent.rightKey, fourNodeParent.rightValue,\n twoNodeRightChild.key, twoNodeRightChild.value, rightChild.size + 1\n + size(leftChild.right));\n\n newRightChild.right = rightChild.right;\n ((ThreeNode) newRightChild).middle = rightChild.left;\n } else {\n newRightChild = new TwoNode(fourNodeParent.rightKey, fourNodeParent.rightValue, 1);\n }\n newRightChild.left = leftChildThreeNode.right;\n\n fourNodeParent.rightKey = leftChildThreeNode.rightKey;\n fourNodeParent.rightValue = leftChildThreeNode.rightValue;\n\n newLeftChild = new TwoNode(leftChildThreeNode.leftKey, leftChildThreeNode.leftValue,\n leftChildThreeNode.size - 1 - size(leftChild.right));\n newLeftChild.left = leftChildThreeNode.left;\n newLeftChild.right = leftChildThreeNode.middle;\n\n fourNodeParent.middle2 = newLeftChild;\n fourNodeParent.right = newRightChild;\n\n break;\n }\n }\n }\n }\n\n return parent;\n }\n\n private Node mergeParentKeyInto4NodeChild(Node parent, Node leftChild, Node rightChild, NodePosition destinationNode) {\n Node newParent = null;\n\n if (!is2Node(leftChild) || !is2Node(rightChild)) {\n return parent;\n }\n\n TwoNode childLeftTwoNode = (TwoNode) leftChild;\n TwoNode childRightTwoNode = (TwoNode) rightChild;\n\n int newChildSize = size(leftChild) + 1 + size(rightChild);\n\n FourNode newChild = null;\n\n if (is2Node(parent)) {\n TwoNode parentTwoNode = (TwoNode) parent;\n\n newChild = new FourNode(childLeftTwoNode.key, childLeftTwoNode.value,\n parentTwoNode.key, parentTwoNode.value, childRightTwoNode.key, childRightTwoNode.value,\n newChildSize);\n\n newParent = newChild;\n } else if (is3Node(parent)) {\n ThreeNode parentThreeNode = (ThreeNode) parent;\n\n //Go left\n if (destinationNode == NodePosition.LEFT) {\n newChild = new FourNode(childLeftTwoNode.key, childLeftTwoNode.value,\n parentThreeNode.leftKey, parentThreeNode.leftValue, childRightTwoNode.key, childRightTwoNode.value,\n newChildSize);\n\n newParent = new TwoNode(parentThreeNode.rightKey, parentThreeNode.rightValue, parentThreeNode.size);\n newParent.left = newChild;\n newParent.right = parent.right;\n } else if (destinationNode == NodePosition.RIGHT) {\n //Go right\n newChild = new FourNode(childLeftTwoNode.key, childLeftTwoNode.value,\n parentThreeNode.rightKey, parentThreeNode.rightValue, childRightTwoNode.key, childRightTwoNode.value,\n newChildSize);\n\n newParent = new TwoNode(parentThreeNode.leftKey, parentThreeNode.leftValue, parentThreeNode.size);\n newParent.left = parent.left;\n newParent.right = newChild;\n }\n } else {\n FourNode parentFourNode = (FourNode) parent;\n\n //Go left\n if (destinationNode == NodePosition.LEFT) {\n newChild = new FourNode(childLeftTwoNode.key, childLeftTwoNode.value,\n parentFourNode.leftKey, parentFourNode.leftValue, childRightTwoNode.key, childRightTwoNode.value,\n newChildSize);\n\n newParent = new ThreeNode(parentFourNode.middleKey, parentFourNode.middleValue,\n parentFourNode.rightKey, parentFourNode.rightValue, parentFourNode.size);\n newParent.left = newChild;\n ((ThreeNode) newParent).middle = parentFourNode.middle2;\n newParent.right = parent.right;\n } else if (destinationNode == NodePosition.MIDDLE1) {\n //Go to the middle\n newChild = new FourNode(childLeftTwoNode.key, childLeftTwoNode.value,\n parentFourNode.middleKey, parentFourNode.middleValue, childRightTwoNode.key, childRightTwoNode.value,\n newChildSize);\n\n newParent = new ThreeNode(parentFourNode.leftKey, parentFourNode.leftValue,\n parentFourNode.rightKey, parentFourNode.rightValue, parentFourNode.size);\n newParent.left = parent.left;\n ((ThreeNode) newParent).middle = newChild;\n newParent.right = parent.right;\n } else if (destinationNode == NodePosition.RIGHT) {\n //Go right\n newChild = new FourNode(childLeftTwoNode.key, childLeftTwoNode.value,\n parentFourNode.rightKey, parentFourNode.rightValue, childRightTwoNode.key, childRightTwoNode.value,\n newChildSize);\n\n newParent = new ThreeNode(parentFourNode.leftKey, parentFourNode.leftValue,\n parentFourNode.middleKey, parentFourNode.middleValue, parentFourNode.size);\n newParent.left = parent.left;\n ((ThreeNode) newParent).middle = parentFourNode.middle1;\n newParent.right = newChild;\n }\n }\n\n newChild.left = leftChild.left;\n newChild.middle1 = leftChild.right;\n newChild.middle2 = rightChild.left;\n newChild.right = rightChild.right;\n\n return newParent;\n }\n\n public void put(Key key, Value value) {\n if (key == null) {\n return;\n }\n\n if (value == null) {\n delete(key);\n return;\n }\n\n root = put(root, null, key, value);\n if (is4Node(root)) {\n root = split4Node((FourNode) root);\n }\n }\n\n private Node put(Node node, Node parent, Key key, Value value) {\n if (node == null) {\n TwoNode newNode = new TwoNode(key, value, 1);\n\n if (parent == null) {\n return newNode;\n } else if (is2Node(parent)) {\n TwoNode parentNode = (TwoNode) parent;\n return generate3Node(parentNode, newNode);\n } else {\n //Parent is a 3-node\n ThreeNode parentNode = (ThreeNode) parent;\n\n //Create temporary 4-node\n return generate4Node(parentNode, newNode);\n }\n }\n\n if (is2Node(node)) {\n TwoNode twoNode = (TwoNode) node;\n\n int compare = key.compareTo(twoNode.key);\n\n if (compare < 0) {\n Node newNode = put(node.left, node, key, value);\n\n if (is2Node(newNode)) {\n node.left = newNode;\n } else {\n ThreeNode newThreeNode = (ThreeNode) newNode;\n\n if (containsKey(newThreeNode, twoNode.key)) {\n node = newNode;\n } else {\n node.left = newNode;\n }\n }\n } else if (compare > 0) {\n Node newNode = put(node.right, node, key, value);\n\n if (is2Node(newNode)) {\n node.right = newNode;\n } else {\n ThreeNode newThreeNode = (ThreeNode) newNode;\n\n if (containsKey(newThreeNode, twoNode.key)) {\n node = newNode;\n } else {\n node.right = newNode;\n }\n }\n } else {\n twoNode.value = value;\n }\n } else {\n //Parent is a 3-node\n ThreeNode threeNode = (ThreeNode) node;\n\n int compareLeft = key.compareTo(threeNode.leftKey);\n int compareRight = key.compareTo(threeNode.rightKey);\n\n if (compareLeft < 0) {\n Node newNode = put(threeNode.left, threeNode, key, value);\n\n if (!is4Node(newNode)) {\n node.left = newNode;\n } else {\n FourNode fourNode = (FourNode) newNode;\n node = splitNodeAndBuildTree(parent, fourNode);\n }\n } else if (compareLeft > 0 && compareRight < 0) {\n Node newNode = put(threeNode.middle, node, key, value);\n\n if (!is4Node(newNode)) {\n threeNode.middle = newNode;\n } else {\n FourNode fourNode = (FourNode) newNode;\n node = splitNodeAndBuildTree(parent, fourNode);\n }\n } else if (compareRight > 0) {\n Node newNode = put(node.right, node, key, value);\n\n if (!is4Node(newNode)) {\n node.right = newNode;\n } else {\n FourNode fourNode = (FourNode) newNode;\n node = splitNodeAndBuildTree(parent, fourNode);\n }\n } else {\n if (threeNode.leftKey.compareTo(key) == 0) {\n threeNode.leftValue = value;\n } else if (threeNode.rightKey.compareTo(key) == 0) {\n threeNode.rightValue = value;\n }\n }\n }\n\n if (!is3Node(node)) {\n node.size = size(node.left) + 1 + size(node.right);\n } else {\n ThreeNode threeNode = (ThreeNode) node;\n threeNode.size = size(threeNode.left) + 2 + size(threeNode.middle) + size(threeNode.right);\n }\n\n return node;\n }\n\n private Node splitNodeAndBuildTree(Node parent, FourNode fourNode) {\n Node returnNode;\n\n TwoNode splitNode = split4Node(fourNode);\n if (parent == null) {\n returnNode = splitNode;\n } else if (!is3Node(parent)) {\n TwoNode parentNode = (TwoNode) parent;\n returnNode = generate3Node(parentNode, splitNode);\n } else {\n ThreeNode parentNode = (ThreeNode) parent;\n returnNode = generate4Node(parentNode, splitNode);\n }\n\n return returnNode;\n }\n\n private boolean containsKey(ThreeNode threeNode, Key key) {\n if ((threeNode.leftKey != null && threeNode.leftKey.compareTo(key) == 0)\n || (threeNode.rightKey != null && threeNode.rightKey.compareTo(key) == 0)) {\n return true;\n } else {\n return false;\n }\n }\n\n public Value get(Key key) {\n if (key == null) {\n return null;\n }\n\n return get(root, key);\n }\n\n private Value get(Node node, Key key) {\n if (node == null) {\n return null;\n }\n\n if (is2Node(node)) {\n TwoNode twoNode = (TwoNode) node;\n\n int compare = key.compareTo(twoNode.key);\n if (compare < 0) {\n return get(twoNode.left, key);\n } else if (compare > 0) {\n return get(twoNode.right, key);\n } else {\n return twoNode.value;\n }\n } else {\n ThreeNode threeNode = (ThreeNode) node;\n\n int compareLeft = key.compareTo(threeNode.leftKey);\n int compareRight = key.compareTo(threeNode.rightKey);\n\n if (compareLeft < 0) {\n return get(threeNode.left, key);\n } else if (compareLeft > 0 && compareRight < 0) {\n return get(threeNode.middle, key);\n } else if (compareRight > 0) {\n return get(threeNode.right, key);\n } else {\n if (compareLeft == 0) {\n return threeNode.leftValue;\n } else {\n return threeNode.rightValue;\n }\n }\n }\n }\n\n public boolean contains(Key key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Argument to contains() cannot be null\");\n }\n return get(key) != null;\n }\n\n public Key min() {\n if (root == null) {\n throw new NoSuchElementException(\"Empty binary search tree\");\n }\n\n Node minNode = min(root);\n\n if (is2Node(minNode)) {\n return ((TwoNode) minNode).key;\n } else {\n return ((ThreeNode) minNode).leftKey;\n }\n }\n\n private Node min(Node node) {\n if (node.left == null) {\n return node;\n }\n\n return min(node.left);\n }\n\n public Key max() {\n if (root == null) {\n throw new NoSuchElementException(\"Empty binary search tree\");\n }\n\n Node maxNode = max(root);\n\n if (is2Node(maxNode)) {\n return ((TwoNode) maxNode).key;\n } else {\n return ((ThreeNode) maxNode).rightKey;\n }\n }\n\n private Node max(Node node) {\n if (node.right == null) {\n return node;\n }\n\n return max(node.right);\n }\n\n //Returns the highest key in the symbol table smaller than or equal to key.\n public Key floor(Key key) {\n Node node = floor(root, key);\n if (node == null) {\n return null;\n }\n\n if (is2Node(node)) {\n return ((TwoNode) node).key;\n } else {\n ThreeNode threeNode = (ThreeNode) node;\n\n int compareLeft = key.compareTo(threeNode.leftKey);\n int compareRight = key.compareTo(threeNode.rightKey);\n\n //compareLeft < 0 is not possible\n if (compareLeft > 0 && compareRight < 0) {\n return threeNode.leftKey;\n } else if (compareRight > 0) {\n return threeNode.rightKey;\n } else {\n if (threeNode.leftKey.compareTo(key) == 0) {\n return threeNode.leftKey;\n } else {\n return threeNode.rightKey;\n }\n }\n }\n }\n\n private Node floor(Node node, Key key) {\n if (node == null) {\n return null;\n }\n\n if (is2Node(node)) {\n TwoNode twoNode = (TwoNode) node;\n\n int compare = key.compareTo(twoNode.key);\n if (compare == 0) {\n return node;\n } else if (compare < 0) {\n return floor(twoNode.left, key);\n } else {\n Node rightNode = floor(twoNode.right, key);\n if (rightNode != null) {\n return rightNode;\n } else {\n return node;\n }\n }\n } else {\n ThreeNode threeNode = (ThreeNode) node;\n\n int compareLeft = key.compareTo(threeNode.leftKey);\n int compareRight = key.compareTo(threeNode.rightKey);\n\n if (compareLeft < 0) {\n return floor(threeNode.left, key);\n } else if (compareLeft > 0 && compareRight < 0) {\n Node middleNode = floor(threeNode.middle, key);\n if (middleNode != null) {\n return middleNode;\n } else {\n return node;\n }\n } else if (compareRight > 0) {\n Node rightNode = floor(threeNode.right, key);\n if (rightNode != null) {\n return rightNode;\n } else {\n return node;\n }\n } else {\n return node;\n }\n }\n }\n\n //Returns the smallest key in the symbol table greater than or equal to key.\n public Key ceiling(Key key) {\n Node node = ceiling(root, key);\n if (node == null) {\n return null;\n }\n\n if (is2Node(node)) {\n return ((TwoNode) node).key;\n } else {\n ThreeNode threeNode = (ThreeNode) node;\n\n int compareLeft = key.compareTo(threeNode.leftKey);\n int compareRight = key.compareTo(threeNode.rightKey);\n\n //compareRight > 0 is not possible\n if (compareLeft < 0) {\n return threeNode.leftKey;\n } else if (compareLeft > 0 && compareRight < 0) {\n return threeNode.rightKey;\n } else {\n if (threeNode.leftKey.compareTo(key) == 0) {\n return threeNode.leftKey;\n } else {\n return threeNode.rightKey;\n }\n }\n }\n }\n\n private Node ceiling(Node node, Key key) {\n if (node == null) {\n return null;\n }\n\n if (is2Node(node)) {\n TwoNode twoNode = (TwoNode) node;\n\n int compare = key.compareTo(twoNode.key);\n if (compare == 0) {\n return node;\n } else if (compare > 0) {\n return ceiling(twoNode.right, key);\n } else {\n Node leftNode = ceiling(twoNode.left, key);\n if (leftNode != null) {\n return leftNode;\n } else {\n return node;\n }\n }\n } else {\n ThreeNode threeNode = (ThreeNode) node;\n\n int compareLeft = key.compareTo(threeNode.leftKey);\n int compareRight = key.compareTo(threeNode.rightKey);\n\n if (compareRight > 0) {\n return ceiling(threeNode.right, key);\n } else if (compareLeft > 0 && compareRight < 0) {\n Node middleNode = ceiling(threeNode.middle, key);\n if (middleNode != null) {\n return middleNode;\n } else {\n return node;\n }\n } else if (compareLeft < 0) {\n Node leftNode = ceiling(threeNode.left, key);\n if (leftNode != null) {\n return leftNode;\n } else {\n return node;\n }\n } else {\n return node;\n }\n }\n }\n\n public Key select(int index) {\n if (index >= size()) {\n throw new IllegalArgumentException(\"Index is higher than tree size\");\n }\n\n Node selectedNode = select(root, index);\n return ((TwoNode) selectedNode).key;\n }\n\n private Node select(Node node, int index) {\n int leftSubtreeSize = size(node.left);\n\n if (is2Node(node)) {\n if (leftSubtreeSize == index) {\n return node;\n } else if (leftSubtreeSize > index) {\n return select(node.left, index);\n } else {\n return select(node.right, index - leftSubtreeSize - 1);\n }\n } else {\n ThreeNode threeNode = (ThreeNode) node;\n int middleSubtreeSize = size(threeNode.middle);\n\n if (leftSubtreeSize == index) {\n return new TwoNode(threeNode.leftKey, threeNode.leftValue, threeNode.size);\n } else if (leftSubtreeSize + 1 + middleSubtreeSize == index) {\n return new TwoNode(threeNode.rightKey, threeNode.rightValue, threeNode.size);\n } else if (leftSubtreeSize > index) {\n return select(node.left, index);\n } else if (leftSubtreeSize + 1 + middleSubtreeSize > index) {\n return select(threeNode.middle, index - leftSubtreeSize - 1);\n } else {\n return select(node.right, index - leftSubtreeSize - 1 - middleSubtreeSize - 1);\n }\n }\n }\n\n public int rank(Key key) {\n return rank(root, key);\n }\n\n private int rank(Node node, Key key) {\n if (node == null) {\n return 0;\n }\n\n //Returns the number of keys less than node.key in the subtree rooted at node\n if (is2Node(node)) {\n TwoNode twoNode = (TwoNode) node;\n\n int compare = key.compareTo(twoNode.key);\n if (compare < 0) {\n return rank(node.left, key);\n } else if (compare > 0) {\n return size(node.left) + 1 + rank(node.right, key);\n } else {\n return size(node.left);\n }\n } else {\n ThreeNode threeNode = (ThreeNode) node;\n\n int compareLeft = key.compareTo(threeNode.leftKey);\n int compareRight = key.compareTo(threeNode.rightKey);\n\n if (compareLeft < 0) {\n return rank(threeNode.left, key);\n } else if (compareLeft > 0 && compareRight < 0) {\n return size(threeNode.left) + 1 + rank(threeNode.middle, key);\n } else if (compareRight > 0) {\n return size(threeNode.left) + 1 + size(threeNode.middle) + 1 + rank(threeNode.right, key);\n } else {\n if (compareLeft == 0) {\n return size(node.left);\n } else {\n return size(node.left) + 1 + size(threeNode.middle);\n }\n }\n }\n }\n\n public void deleteMin() {\n if (isEmpty()) {\n return;\n }\n\n if (is2Node(root)) {\n if (root.right != null && is2Node(root.left) && is2Node(root.right)) {\n root = mergeParentKeyInto4NodeChild(root, root.left, root.right, NodePosition.LEFT);\n } else if (is2Node(root.left) &&\n (is3Node(root.right) || is4Node(root.right))) {\n root = moveKey(root, NodePosition.RIGHT, NodePosition.LEFT);\n }\n }\n\n root = deleteMin(root);\n\n if (!isEmpty() && is4Node(root)) {\n root = split4Node((FourNode) root);\n }\n }\n\n private Node deleteMin(Node node) {\n //Current node is a 2-node\n if (is2Node(node)) {\n if (is2Node(node.left)) {\n if (!is2Node(node.right)) {\n node = moveKey(node, NodePosition.RIGHT, NodePosition.LEFT);\n } else {\n node = mergeParentKeyInto4NodeChild(node, node.left, node.right, NodePosition.LEFT);\n }\n }\n } else if (is3Node(node)) {\n //Current node is a 3-node\n ThreeNode threeNode = (ThreeNode) node;\n\n if (is2Node(node.left)) {\n if (!is2Node(threeNode.middle)) {\n node = moveKey(node, NodePosition.MIDDLE1, NodePosition.LEFT);\n } else if (!is2Node(threeNode.right)) {\n node = moveKey(node, NodePosition.RIGHT, NodePosition.LEFT);\n } else {\n node = mergeParentKeyInto4NodeChild(threeNode, threeNode.left, threeNode.middle, NodePosition.LEFT);\n }\n }\n } else {\n //Current node is a 4-node\n FourNode fourNode = (FourNode) node;\n\n if (is2Node(node.left)) {\n if (!is2Node(fourNode.middle1)) {\n node = moveKey(node, NodePosition.MIDDLE1, NodePosition.LEFT);\n } else if (!is2Node(fourNode.middle2)) {\n node = moveKey(node, NodePosition.MIDDLE2, NodePosition.LEFT);\n } else if (!is2Node(fourNode.middle2)) {\n node = moveKey(node, NodePosition.RIGHT, NodePosition.LEFT);\n } else {\n node = mergeParentKeyInto4NodeChild(fourNode, fourNode.left, fourNode.middle1, NodePosition.LEFT);\n }\n }\n }\n\n if (node.left == null) {\n return removeMinKeyFromNode(node);\n } else {\n node.left = deleteMin(node.left);\n }\n\n return balance(node);\n }\n\n public void deleteMax() {\n if (isEmpty()) {\n return;\n }\n\n if (is2Node(root)) {\n if (root.left != null && is2Node(root.left) && is2Node(root.right)) {\n root = mergeParentKeyInto4NodeChild(root, root.left, root.right, NodePosition.RIGHT);\n } else if (is2Node(root.right) &&\n (is3Node(root.left) || is4Node(root.left))) {\n root = moveKey(root, NodePosition.LEFT, NodePosition.RIGHT);\n }\n }\n\n root = deleteMax(root);\n\n if (!isEmpty() && is4Node(root)) {\n root = split4Node((FourNode) root);\n }\n }\n\n private Node deleteMax(Node node) {\n //Current node is a 2-node\n if (is2Node(node)) {\n if (is2Node(node.right)) {\n if (!is2Node(node.left)) {\n node = moveKey(node, NodePosition.LEFT, NodePosition.RIGHT);\n } else {\n node = mergeParentKeyInto4NodeChild(node, node.left, node.right, NodePosition.RIGHT);\n }\n }\n } else if (is3Node(node)) {\n //Current node is a 3-node\n ThreeNode threeNode = (ThreeNode) node;\n\n if (is2Node(node.right)) {\n if (!is2Node(threeNode.middle)) {\n node = moveKey(threeNode, NodePosition.MIDDLE1, NodePosition.RIGHT);\n } else if (!is2Node(threeNode.left)) {\n node = moveKey(threeNode, NodePosition.LEFT, NodePosition.RIGHT);\n } else {\n node = mergeParentKeyInto4NodeChild(threeNode, threeNode.middle, threeNode.right, NodePosition.RIGHT);\n }\n }\n } else {\n //Current node is a 4-node\n FourNode fourNode = (FourNode) node;\n\n if (is2Node(node.right)) {\n if (!is2Node(fourNode.middle2)) {\n node = moveKey(fourNode, NodePosition.MIDDLE2, NodePosition.RIGHT);\n } else if (!is2Node(fourNode.middle1)) {\n node = moveKey(fourNode, NodePosition.MIDDLE1, NodePosition.RIGHT);\n } else if (!is2Node(fourNode.middle1)) {\n node = moveKey(fourNode, NodePosition.LEFT, NodePosition.RIGHT);\n } else {\n node = mergeParentKeyInto4NodeChild(fourNode, fourNode.middle2, fourNode.right, NodePosition.RIGHT);\n }\n }\n }\n\n if (node.right == null) {\n return removeMaxKeyFromNode(node);\n } else {\n node.right = deleteMax(node.right);\n }\n\n return balance(node);\n }\n\n public void delete(Key key) {\n if (isEmpty()) {\n return;\n }\n\n if (!contains(key)) {\n return;\n }\n\n if (is2Node(root)) {\n TwoNode rootNode = (TwoNode) root;\n\n //If root is the key to delete and we can't make a 4-node\n if (rootNode.key.compareTo(key) == 0 && is2Node(root)\n && (rootNode.left == null || rootNode.right == null)) {\n if (rootNode.right == null) {\n root = rootNode.left;\n } else {\n Node aux = min(rootNode.right);\n\n if (is2Node(aux)) {\n TwoNode auxNode = (TwoNode) aux;\n rootNode.key = auxNode.key;\n rootNode.value = auxNode.value;\n rootNode.right = deleteMin(rootNode.right);\n } else if (is3Node(aux)) {\n ThreeNode auxNode = (ThreeNode) aux;\n rootNode.key = auxNode.leftKey;\n rootNode.value = auxNode.leftValue;\n rootNode.right = deleteMin(rootNode.right);\n }\n\n rootNode.size--;\n }\n\n return;\n }\n\n if (root.left != null && is2Node(root.left) && is2Node(root.right)) {\n TwoNode leftNode = (TwoNode) root.left;\n TwoNode middleNode = (TwoNode) root;\n TwoNode rightNode = (TwoNode) root.right;\n\n ThreeNode threeNode = generate3Node(middleNode, leftNode);\n root = generate4Node(threeNode, rightNode);\n } else if (is3Node(rootNode.left)) {\n root = moveThreeNodeLeftToCenter(root);\n } else if (is3Node(rootNode.right)) {\n root = moveThreeNodeRightToCenter(root);\n }\n }\n\n root = delete(root, key);\n\n if (!isEmpty() && is4Node(root)) {\n root = split4Node((FourNode) root);\n }\n }\n\n private Node delete(Node node, Key key) {\n if (node == null) {\n return null;\n }\n\n //Move left\n if ((is2Node(node) && key.compareTo(((TwoNode) node).key) < 0)\n || (is3Node(node) && key.compareTo(((ThreeNode) node).leftKey) < 0)\n || (is4Node(node) && key.compareTo(((FourNode) node).leftKey) < 0)) {\n\n //Current node is a 2-node\n if (is2Node(node)) {\n if (is2Node(node.left)) {\n if (!is2Node(node.right)) {\n node = moveKey(node, NodePosition.RIGHT, NodePosition.LEFT);\n } else {\n node = mergeParentKeyInto4NodeChild(node, node.left, node.right, NodePosition.LEFT);\n }\n }\n } else if (is3Node(node)) {\n //Current node is a 3-node\n ThreeNode threeNode = (ThreeNode) node;\n\n if (is2Node(node.left)) {\n if (threeNode.middle != null && !is2Node(threeNode.middle)) {\n node = moveKey(node, NodePosition.MIDDLE1, NodePosition.LEFT);\n } else if (!is2Node(threeNode.right)) {\n node = moveKey(node, NodePosition.RIGHT, NodePosition.LEFT);\n } else {\n node = mergeParentKeyInto4NodeChild(threeNode, threeNode.left, threeNode.middle, NodePosition.LEFT);\n }\n }\n } else {\n //Current node is a 4-node\n FourNode fourNode = (FourNode) node;\n\n if (is2Node(node.left)) {\n if (fourNode.middle1 != null && !is2Node(fourNode.middle1)) {\n node = moveKey(node, NodePosition.MIDDLE1, NodePosition.LEFT);\n } else if (fourNode.middle2 != null && !is2Node(fourNode.middle2)) {\n node = moveKey(node, NodePosition.MIDDLE2, NodePosition.LEFT);\n } else if (!is2Node(fourNode.right)) {\n node = moveKey(node, NodePosition.RIGHT, NodePosition.LEFT);\n } else {\n node = mergeParentKeyInto4NodeChild(fourNode, fourNode.left, fourNode.middle1, NodePosition.LEFT);\n }\n }\n }\n\n node.left = delete(node.left, key);\n } else if ((is3Node(node)\n && ((ThreeNode) node).leftKey.compareTo(key) < 0\n && ((ThreeNode) node).rightKey.compareTo(key) > 0)) {\n //Move middle\n ThreeNode threeNode = (ThreeNode) node;\n\n if (is3Node(threeNode.middle) || is4Node(threeNode.middle)) {\n threeNode.middle = delete(threeNode.middle, key);\n } else {\n //The middle node is a 2-node\n if (threeNode.left != null && !is2Node(threeNode.left)) {\n node = moveKey(threeNode, NodePosition.LEFT, NodePosition.MIDDLE1);\n threeNode.middle = delete(threeNode.middle, key);\n } else if (!is2Node(threeNode.right)) {\n node = moveKey(threeNode, NodePosition.RIGHT, NodePosition.MIDDLE1);\n threeNode.middle = delete(threeNode.middle, key);\n } else {\n node = mergeParentKeyInto4NodeChild(threeNode, threeNode.left, threeNode.middle, NodePosition.LEFT);\n node.left = delete(node.left, key);\n }\n }\n } else if ((is4Node(node)\n && ((FourNode) node).leftKey.compareTo(key) < 0\n && ((FourNode) node).middleKey.compareTo(key) > 0)) {\n //Move to middle 1\n FourNode fourNode = (FourNode) node;\n\n if (is3Node(fourNode.middle1) || is4Node(fourNode.middle1)) {\n fourNode.middle1 = delete(fourNode.middle1, key);\n } else {\n //The middle1 node is a 2-node\n if (fourNode.left != null && !is2Node(fourNode.left)) {\n node = moveKey(fourNode, NodePosition.LEFT, NodePosition.MIDDLE1);\n fourNode.middle1 = delete(fourNode.middle1, key);\n } else if (fourNode.middle2 != null && !is2Node(fourNode.middle2)) {\n node = moveKey(fourNode, NodePosition.MIDDLE2, NodePosition.MIDDLE1);\n fourNode.middle1 = delete(fourNode.middle1, key);\n } else if (!is2Node(fourNode.right)) {\n node = moveKey(fourNode, NodePosition.RIGHT, NodePosition.MIDDLE1);\n fourNode.middle1 = delete(fourNode.middle1, key);\n } else {\n node = mergeParentKeyInto4NodeChild(fourNode, fourNode.left, fourNode.middle1, NodePosition.LEFT);\n node.left = delete(node.left, key);\n }\n }\n } else if ((is4Node(node)\n && ((FourNode) node).middleKey.compareTo(key) < 0\n && ((FourNode) node).rightKey.compareTo(key) > 0)) {\n //Move to middle 2\n FourNode fourNode = (FourNode) node;\n\n if (is3Node(fourNode.middle2) || is4Node(fourNode.middle2)) {\n fourNode.middle2 = delete(fourNode.middle2, key);\n } else {\n //The middle2 node is a 2-node\n if (fourNode.middle1 != null && !is2Node(fourNode.middle1)) {\n node = moveKey(fourNode, NodePosition.MIDDLE1, NodePosition.MIDDLE2);\n fourNode.middle2 = delete(fourNode.middle2, key);\n } else if (fourNode.right != null && !is2Node(fourNode.right)) {\n node = moveKey(fourNode, NodePosition.RIGHT, NodePosition.MIDDLE2);\n fourNode.middle2 = delete(fourNode.middle2, key);\n } else if (!is2Node(fourNode.left)) {\n node = moveKey(fourNode, NodePosition.LEFT, NodePosition.MIDDLE2);\n fourNode.middle2 = delete(fourNode.middle2, key);\n } else {\n node = mergeParentKeyInto4NodeChild(fourNode, fourNode.middle1, fourNode.middle2, NodePosition.MIDDLE1);\n\n //Now we have a 3-node as parent\n ThreeNode newThreeNodeParent = (ThreeNode) node;\n newThreeNodeParent.middle = delete(newThreeNodeParent.middle, key);\n }\n }\n } else {\n //Move right or delete\n if ((is2Node(node)\n && key.compareTo(((TwoNode) node).key) == 0 && node.right == null)) {\n return null;\n } else if (is3Node(node)\n && (key.compareTo(((ThreeNode) node).rightKey) == 0)) {\n return removeMaxKeyFromNode(node);\n } else if (is4Node(node)\n && (key.compareTo(((FourNode) node).rightKey) == 0)) {\n return removeMaxKeyFromNode(node);\n }\n\n //Current node is a 2-node\n if (is2Node(node)) {\n if (is2Node(node.right)) {\n if (!is2Node(node.left)) {\n node = moveKey(node, NodePosition.LEFT, NodePosition.RIGHT);\n } else {\n node = mergeParentKeyInto4NodeChild(node, node.left, node.right, NodePosition.RIGHT);\n }\n }\n } else if (is3Node(node)) {\n //Current node is a 3-node\n ThreeNode threeNode = (ThreeNode) node;\n\n if (is2Node(node.right)) {\n if (threeNode.middle != null && !is2Node(threeNode.middle)) {\n node = moveKey(threeNode, NodePosition.MIDDLE1, NodePosition.RIGHT);\n } else if (!is2Node(threeNode.left)) {\n node = moveKey(threeNode, NodePosition.LEFT, NodePosition.RIGHT);\n } else {\n node = mergeParentKeyInto4NodeChild(threeNode, threeNode.middle, threeNode.right, NodePosition.RIGHT);\n }\n }\n } else {\n //Current node is a 4-node\n FourNode fourNode = (FourNode) node;\n\n if (is2Node(node.right)) {\n if (fourNode.middle2 != null && !is2Node(fourNode.middle2)) {\n node = moveKey(fourNode, NodePosition.MIDDLE2, NodePosition.RIGHT);\n } else if (fourNode.middle1 != null && !is2Node(fourNode.middle1)) {\n node = moveKey(fourNode, NodePosition.MIDDLE1, NodePosition.RIGHT);\n } else if (!is2Node(fourNode.left)) {\n node = moveKey(fourNode, NodePosition.LEFT, NodePosition.RIGHT);\n } else {\n node = mergeParentKeyInto4NodeChild(fourNode, fourNode.middle2, fourNode.right, NodePosition.RIGHT);\n }\n }\n }\n\n //Check to see if key was found or if it is higher than current key\n if (is2Node(node)) {\n TwoNode twoNode = (TwoNode) node;\n\n if (key.compareTo(twoNode.key) == 0) {\n Node aux = min(twoNode.right);\n\n if (is2Node(aux)) {\n TwoNode auxNode = (TwoNode) aux;\n twoNode.key = auxNode.key;\n twoNode.value = auxNode.value;\n twoNode.right = deleteMin(twoNode.right);\n } else if (is3Node(aux)) {\n ThreeNode auxNode = (ThreeNode) aux;\n twoNode.key = auxNode.leftKey;\n twoNode.value = auxNode.leftValue;\n twoNode.right = deleteMin(twoNode.right);\n }\n } else {\n node.right = delete(node.right, key);\n }\n } else if (is3Node(node)) {\n ThreeNode threeNode = (ThreeNode) node;\n\n if (key.compareTo(threeNode.leftKey) == 0) {\n if (threeNode.middle != null) {\n Node aux = min(threeNode.middle);\n\n if (is2Node(aux)) {\n TwoNode auxNode = (TwoNode) aux;\n threeNode.leftKey = auxNode.key;\n threeNode.leftValue = auxNode.value;\n threeNode.middle = deleteMin(threeNode.middle);\n } else if (is3Node(aux)) {\n ThreeNode auxNode = (ThreeNode) aux;\n threeNode.leftKey = auxNode.leftKey;\n threeNode.leftValue = auxNode.leftValue;\n threeNode.middle = deleteMin(threeNode.middle);\n }\n } else {\n //Delete left key reference\n node = new TwoNode(threeNode.rightKey, threeNode.rightValue, threeNode.size - 1);\n //We know that there is nothing in the middle, so just set left and right references\n node.left = threeNode.left;\n node.right = threeNode.right;\n }\n } else if (key.compareTo(threeNode.rightKey) == 0) {\n Node aux = min(threeNode.right);\n\n if (is2Node(aux)) {\n TwoNode auxNode = (TwoNode) aux;\n threeNode.rightKey = auxNode.key;\n threeNode.rightValue = auxNode.value;\n threeNode.right = deleteMin(threeNode.right);\n } else if (is3Node(aux)) {\n ThreeNode auxNode = (ThreeNode) aux;\n threeNode.rightKey = auxNode.leftKey;\n threeNode.rightValue = auxNode.leftValue;\n threeNode.right = deleteMin(threeNode.right);\n }\n } else {\n node.right = delete(node.right, key);\n }\n } else if (is4Node(node)) {\n FourNode fourNode = (FourNode) node;\n\n if (key.compareTo(fourNode.leftKey) == 0) {\n if (fourNode.middle1 != null) {\n Node aux = min(fourNode.middle1);\n\n if (is2Node(aux)) {\n TwoNode auxNode = (TwoNode) aux;\n fourNode.leftKey = auxNode.key;\n fourNode.leftValue = auxNode.value;\n fourNode.middle1 = deleteMin(fourNode.middle1);\n } else if (is3Node(aux)) {\n ThreeNode auxNode = (ThreeNode) aux;\n fourNode.leftKey = auxNode.leftKey;\n fourNode.leftValue = auxNode.leftValue;\n fourNode.middle1 = deleteMin(fourNode.middle1);\n }\n } else {\n //Delete left key reference\n node = new ThreeNode(fourNode.middleKey, fourNode.middleValue,\n fourNode.rightKey, fourNode.rightValue, fourNode.size - 1);\n //We know that there is nothing in the middle1 reference, so just set left, middle2 and right references\n node.left = fourNode.left;\n ((ThreeNode) node).middle = fourNode.middle2;\n node.right = fourNode.right;\n }\n } else if (key.compareTo(fourNode.middleKey) == 0) {\n if (fourNode.middle2 != null) {\n Node aux = min(fourNode.middle2);\n\n if (is2Node(aux)) {\n TwoNode auxNode = (TwoNode) aux;\n fourNode.middleKey = auxNode.key;\n fourNode.middleValue = auxNode.value;\n fourNode.middle2 = deleteMin(fourNode.middle2);\n } else if (is3Node(aux)) {\n ThreeNode auxNode = (ThreeNode) aux;\n fourNode.middleKey = auxNode.leftKey;\n fourNode.middleValue = auxNode.leftValue;\n fourNode.middle2 = deleteMin(fourNode.middle2);\n }\n } else {\n //Delete middle1 key reference\n node = new ThreeNode(fourNode.leftKey, fourNode.leftValue,\n fourNode.rightKey, fourNode.rightValue, fourNode.size - 1);\n //We know that there is nothing in the middle2 reference, so just set left, middle1 and right references\n node.left = fourNode.left;\n ((ThreeNode) node).middle = fourNode.middle1;\n node.right = fourNode.right;\n }\n } else if (key.compareTo(fourNode.rightKey) == 0) {\n Node aux = min(fourNode.right);\n\n if (is2Node(aux)) {\n TwoNode auxNode = (TwoNode) aux;\n fourNode.rightKey = auxNode.key;\n fourNode.rightValue = auxNode.value;\n fourNode.right = deleteMin(fourNode.right);\n } else if (is3Node(aux)) {\n ThreeNode auxNode = (ThreeNode) aux;\n fourNode.rightKey = auxNode.leftKey;\n fourNode.rightValue = auxNode.leftValue;\n fourNode.right = deleteMin(fourNode.right);\n }\n } else {\n node.right = delete(node.right, key);\n }\n }\n\n node.right = delete(node.right, key);\n }\n\n return balance(node);\n }\n\n private Node removeMinKeyFromNode(Node node) {\n if (is2Node(node)) {\n return null;\n }\n\n Node bottomNode = null;\n\n if (is4Node(node)) {\n FourNode fourNode = (FourNode) node;\n\n ThreeNode finalThreeNode = new ThreeNode(fourNode.middleKey, fourNode.middleValue, fourNode.rightKey,\n fourNode.rightValue, node.size - 1);\n finalThreeNode.left = fourNode.middle1;\n finalThreeNode.middle = fourNode.middle2;\n finalThreeNode.right = fourNode.right;\n\n bottomNode = finalThreeNode;\n } else if (is3Node(node)) {\n ThreeNode threeNode = (ThreeNode) node;\n\n TwoNode finalTwoNode = new TwoNode(threeNode.rightKey, threeNode.rightValue, node.size - 1);\n finalTwoNode.left = threeNode.middle;\n finalTwoNode.right = threeNode.right;\n\n bottomNode = finalTwoNode;\n }\n\n return bottomNode;\n }\n\n private Node removeMaxKeyFromNode(Node node) {\n if (is2Node(node)) {\n return null;\n }\n\n Node bottomNode = null;\n\n if (is4Node(node)) {\n FourNode fourNode = (FourNode) node;\n\n ThreeNode finalThreeNode = new ThreeNode(fourNode.leftKey, fourNode.leftValue, fourNode.middleKey,\n fourNode.middleValue, node.size - 1);\n finalThreeNode.left = fourNode.left;\n finalThreeNode.middle = fourNode.middle1;\n finalThreeNode.right = fourNode.middle2;\n\n bottomNode = finalThreeNode;\n } else if (is3Node(node)) {\n ThreeNode threeNode = (ThreeNode) node;\n\n TwoNode finalTwoNode = new TwoNode(threeNode.leftKey, threeNode.leftValue, node.size - 1);\n finalTwoNode.left = threeNode.left;\n finalTwoNode.right = threeNode.middle;\n\n bottomNode = finalTwoNode;\n }\n\n return bottomNode;\n }\n\n private Node moveThreeNodeRightToCenter(Node node) {\n if (!is2Node(node) || is2Node(node.right)) {\n return node;\n }\n\n TwoNode twoNodeRoot = (TwoNode) node;\n TwoNode splitTwoNodeRight;\n\n if (is4Node(node.right)) {\n FourNode fourNode = (FourNode) node.right;\n splitTwoNodeRight = split4Node(fourNode);\n } else {\n ThreeNode threeNode = (ThreeNode) node.right;\n splitTwoNodeRight = split3NodeAndMakeRightNodeParent(threeNode);\n }\n\n //Generate 3-node at root\n TwoNode leftNodeFromSplit = (TwoNode) splitTwoNodeRight.left;\n\n //Move node from right subtree to root\n int splitTwoNodeRightSubtreeLeftSize = size(splitTwoNodeRight.left); //This will become its middle node size\n splitTwoNodeRight.left = splitTwoNodeRight.left.right;\n splitTwoNodeRight.size = size(splitTwoNodeRight) - splitTwoNodeRightSubtreeLeftSize + size(splitTwoNodeRight.left);\n\n ThreeNode threeNodeRoot = new ThreeNode(twoNodeRoot.key, twoNodeRoot.value, leftNodeFromSplit.key,\n leftNodeFromSplit.value, twoNodeRoot.size);\n threeNodeRoot.left = twoNodeRoot.left;\n threeNodeRoot.middle = leftNodeFromSplit.left;\n threeNodeRoot.right = splitTwoNodeRight;\n\n return threeNodeRoot;\n }\n\n private Node moveThreeNodeLeftToCenter(Node node) {\n if (!is2Node(node) || is2Node(node.left)) {\n return node;\n }\n\n TwoNode twoNodeRoot = (TwoNode) node;\n TwoNode splitTwoNodeLeft;\n\n if (is4Node(node.left)) {\n FourNode fourNode = (FourNode) node.left;\n splitTwoNodeLeft = split4Node(fourNode);\n } else {\n ThreeNode threeNode = (ThreeNode) node.left;\n splitTwoNodeLeft = split3NodeAndMakeLeftNodeParent(threeNode);\n }\n\n //Generate 3-node at root\n TwoNode rightNodeFromSplit = (TwoNode) splitTwoNodeLeft.right;\n\n //Move node from left subtree to root\n int splitTwoNodeLeftSubtreeRightSize = size(splitTwoNodeLeft.right); //This will become its middle node size\n splitTwoNodeLeft.right = splitTwoNodeLeft.right.left;\n splitTwoNodeLeft.size = size(splitTwoNodeLeft) - splitTwoNodeLeftSubtreeRightSize + size(splitTwoNodeLeft.right);\n\n ThreeNode threeNodeRoot = new ThreeNode(rightNodeFromSplit.key, rightNodeFromSplit.value,\n twoNodeRoot.key, twoNodeRoot.value, twoNodeRoot.size);\n threeNodeRoot.left = splitTwoNodeLeft;\n threeNodeRoot.middle = rightNodeFromSplit.right;\n threeNodeRoot.right = twoNodeRoot.right;\n\n return threeNodeRoot;\n }\n\n private Node balance(Node node) {\n if (node == null) {\n return null;\n }\n\n if (is4Node(node)) {\n node = split4Node((FourNode) node);\n }\n\n if (is2Node(node)) {\n node.size = size(node.left) + 1 + size(node.right);\n } else if (is3Node(node)) {\n node.size = size(node.left) + size(((ThreeNode) node).middle) + 2 + size(node.right);\n }\n\n return node;\n }\n\n public Iterable keys() {\n return keys(min(), max());\n }\n\n public Iterable keys(Key low, Key high) {\n if (low == null) {\n throw new IllegalArgumentException(\"First argument to keys() cannot be null\");\n }\n if (high == null) {\n throw new IllegalArgumentException(\"Second argument to keys() cannot be null\");\n }\n\n Queue queue = new Queue<>();\n keys(root, queue, low, high);\n return queue;\n }\n\n private void keys(Node node, Queue queue, Key low, Key high) {\n if (node == null) {\n return;\n }\n\n if (is2Node(node)) {\n TwoNode twoNode = (TwoNode) node;\n\n int compareLow = low.compareTo(twoNode.key);\n int compareHigh = high.compareTo(twoNode.key);\n\n if (compareLow < 0) {\n keys(node.left, queue, low, high);\n }\n\n if (compareLow <= 0 && compareHigh >= 0) {\n queue.enqueue(twoNode.key);\n }\n\n if (compareHigh > 0) {\n keys(node.right, queue, low, high);\n }\n } else {\n ThreeNode threeNode = (ThreeNode) node;\n\n int compareLeftLow = low.compareTo(threeNode.leftKey);\n int compareLeftHigh = high.compareTo(threeNode.leftKey);\n int compareRightLow = low.compareTo(threeNode.rightKey);\n int compareRightHigh = high.compareTo(threeNode.rightKey);\n\n if (compareLeftLow < 0) {\n keys(threeNode.left, queue, low, high);\n }\n\n if (compareLeftLow <= 0 && compareLeftHigh >= 0) {\n queue.enqueue(threeNode.leftKey);\n }\n\n if (compareLeftHigh > 0 && compareRightLow < 0) {\n keys(threeNode.middle, queue, low, high);\n }\n\n if (compareRightLow <= 0 && compareRightHigh >= 0) {\n queue.enqueue(threeNode.rightKey);\n }\n\n if (compareRightHigh > 0) {\n keys(threeNode.right, queue, low, high);\n }\n }\n\n }\n\n public int size(Key low, Key high) {\n if (low == null) {\n throw new IllegalArgumentException(\"First argument to size() cannot be null\");\n }\n if (high == null) {\n throw new IllegalArgumentException(\"Second argument to size() cannot be null\");\n }\n\n if (low.compareTo(high) > 0) {\n return 0;\n }\n\n if (contains(high)) {\n return rank(high) - rank(low) + 1;\n } else {\n return rank(high) - rank(low);\n }\n }\n\n private boolean isBST() {\n return isBST(root, null, null);\n }\n\n private boolean isBST(Node node, Comparable low, Comparable high) {\n if (node == null) {\n return true;\n }\n\n if (is2Node(node)) {\n TwoNode twoNode = (TwoNode) node;\n\n if (low != null && low.compareTo(twoNode.key) >= 0) {\n return false;\n }\n if (high != null && high.compareTo(twoNode.key) <= 0) {\n return false;\n }\n\n return isBST(node.left, low, twoNode.key) && isBST(node.right, twoNode.key, high);\n } else {\n ThreeNode threeNode = (ThreeNode) node;\n\n if (low != null &&\n (low.compareTo(threeNode.leftKey) >= 0 || low.compareTo(threeNode.rightKey) >= 0)) {\n return false;\n }\n if (high != null &&\n (high.compareTo(threeNode.leftKey) <= 0 || high.compareTo(threeNode.rightKey) <= 0)) {\n return false;\n }\n\n return isBST(node.left, low, threeNode.leftKey)\n && isBST(threeNode.middle, threeNode.leftKey, threeNode.rightKey)\n && isBST(node.right, threeNode.rightKey, high);\n }\n }\n\n private boolean isSubtreeCountConsistent() {\n return isSubtreeCountConsistent(root);\n }\n\n private boolean isSubtreeCountConsistent(Node node) {\n if (node == null) {\n return true;\n }\n\n if (is2Node(node)) {\n if (size(node) != size(node.left) + size(node.right) + 1) {\n return false;\n }\n\n return isSubtreeCountConsistent(node.left) && isSubtreeCountConsistent(node.right);\n } else {\n ThreeNode threeNode = (ThreeNode) node;\n\n if (size(node) != size(threeNode.left) + size(threeNode.middle) + 2 + size(threeNode.right)) {\n return false;\n }\n\n return isSubtreeCountConsistent(threeNode.left)\n && isSubtreeCountConsistent(threeNode.middle)\n && isSubtreeCountConsistent(threeNode.right);\n }\n }\n\n }\n\n public static void main(String[] args) {\n // Expected 2-3 tree\n // 1\n // -1 5 9\n // -5 -2 0 2 3 7 99\n //\n\n TwoThreeST twoThreeST = new Exercise35_23Trees.TwoThreeST<>();\n twoThreeST.put(5, 5);\n StdOut.println(\"Is BST: \" + twoThreeST.isBST() + \" Expected: true\");\n StdOut.println(\"Size consistent: \" + twoThreeST.isSubtreeCountConsistent() + \" Expected: true\");\n twoThreeST.put(1, 1);\n StdOut.println(\"Is BST: \" + twoThreeST.isBST() + \" Expected: true\");\n StdOut.println(\"Size consistent: \" + twoThreeST.isSubtreeCountConsistent() + \" Expected: true\");\n twoThreeST.put(9, 9);\n StdOut.println(\"Is BST: \" + twoThreeST.isBST() + \" Expected: true\");\n StdOut.println(\"Size consistent: \" + twoThreeST.isSubtreeCountConsistent() + \" Expected: true\");\n twoThreeST.put(2, 2);\n StdOut.println(\"Is BST: \" + twoThreeST.isBST() + \" Expected: true\");\n StdOut.println(\"Size consistent: \" + twoThreeST.isSubtreeCountConsistent() + \" Expected: true\");\n twoThreeST.put(0, 0);\n StdOut.println(\"Is BST: \" + twoThreeST.isBST() + \" Expected: true\");\n StdOut.println(\"Size consistent: \" + twoThreeST.isSubtreeCountConsistent() + \" Expected: true\");\n twoThreeST.put(99, 99);\n StdOut.println(\"Is BST: \" + twoThreeST.isBST() + \" Expected: true\");\n StdOut.println(\"Size consistent: \" + twoThreeST.isSubtreeCountConsistent() + \" Expected: true\");\n twoThreeST.put(-1, -1);\n StdOut.println(\"Is BST: \" + twoThreeST.isBST() + \" Expected: true\");\n StdOut.println(\"Size consistent: \" + twoThreeST.isSubtreeCountConsistent() + \" Expected: true\");\n twoThreeST.put(-2, -2);\n StdOut.println(\"Is BST: \" + twoThreeST.isBST() + \" Expected: true\");\n StdOut.println(\"Size consistent: \" + twoThreeST.isSubtreeCountConsistent() + \" Expected: true\");\n twoThreeST.put(3, 3);\n StdOut.println(\"Is BST: \" + twoThreeST.isBST() + \" Expected: true\");\n StdOut.println(\"Size consistent: \" + twoThreeST.isSubtreeCountConsistent() + \" Expected: true\");\n twoThreeST.put(-5, -5);\n StdOut.println(\"Is BST: \" + twoThreeST.isBST() + \" Expected: true\");\n StdOut.println(\"Size consistent: \" + twoThreeST.isSubtreeCountConsistent() + \" Expected: true\");\n twoThreeST.put(7, 7);\n StdOut.println(\"Is BST: \" + twoThreeST.isBST() + \" Expected: true\");\n StdOut.println(\"Size consistent: \" + twoThreeST.isSubtreeCountConsistent() + \" Expected: true\\n\");\n\n StdOut.println(\"Keys() test\");\n\n for (Integer key : twoThreeST.keys()) {\n StdOut.println(\"Key \" + key + \": \" + twoThreeST.get(key));\n }\n StdOut.println(\"Expected: -5 -2 -1 0 1 2 3 5 7 9 99\\n\");\n\n // Test min()\n StdOut.println(\"Min key: \" + twoThreeST.min() + \" Expected: -5\");\n\n // Test max()\n StdOut.println(\"Max key: \" + twoThreeST.max() + \" Expected: 99\");\n\n // Test floor()\n StdOut.println(\"Floor of 5: \" + twoThreeST.floor(5) + \" Expected: 5\");\n StdOut.println(\"Floor of 15: \" + twoThreeST.floor(15) + \" Expected: 9\");\n\n // Test ceiling()\n StdOut.println(\"Ceiling of 5: \" + twoThreeST.ceiling(5) + \" Expected: 5\");\n StdOut.println(\"Ceiling of 15: \" + twoThreeST.ceiling(15) + \" Expected: 99\");\n\n // Test select()\n StdOut.println(\"Select key of rank 4: \" + twoThreeST.select(4) + \" Expected: 1\");\n StdOut.println(\"Select key of rank 7: \" + twoThreeST.select(7) + \" Expected: 5\");\n StdOut.println(\"Select key of rank 8: \" + twoThreeST.select(8) + \" Expected: 7\");\n\n // Test rank()\n StdOut.println(\"Rank of key -5: \" + twoThreeST.rank(-5) + \" Expected: 0\");\n StdOut.println(\"Rank of key -4: \" + twoThreeST.rank(-4) + \" Expected: 1\");\n StdOut.println(\"Rank of key 7: \" + twoThreeST.rank(7) + \" Expected: 8\");\n StdOut.println(\"Rank of key 9: \" + twoThreeST.rank(9) + \" Expected: 9\");\n StdOut.println(\"Rank of key 10: \" + twoThreeST.rank(10) + \" Expected: 10\");\n StdOut.println(\"Rank of key 100: \" + twoThreeST.rank(100) + \" Expected: 11\");\n\n // Test delete()\n StdOut.println(\"\\nDelete key 2\");\n twoThreeST.delete(2);\n\n for (Integer key : twoThreeST.keys()) {\n StdOut.println(\"Key \" + key + \": \" + twoThreeST.get(key));\n }\n StdOut.println(\"Is BST: \" + twoThreeST.isBST() + \" Expected: true\");\n StdOut.println(\"Size consistent: \" + twoThreeST.isSubtreeCountConsistent() + \" Expected: true\");\n\n // Test deleteMin()\n StdOut.println(\"\\nDelete min (key -5)\");\n twoThreeST.deleteMin();\n\n for (Integer key : twoThreeST.keys()) {\n StdOut.println(\"Key \" + key + \": \" + twoThreeST.get(key));\n }\n StdOut.println(\"Is BST: \" + twoThreeST.isBST() + \" Expected: true\");\n StdOut.println(\"Size consistent: \" + twoThreeST.isSubtreeCountConsistent() + \" Expected: true\");\n\n // Test deleteMax()\n StdOut.println(\"\\nDelete max (key 99)\");\n twoThreeST.deleteMax();\n\n for (Integer key : twoThreeST.keys()) {\n StdOut.println(\"Key \" + key + \": \" + twoThreeST.get(key));\n }\n StdOut.println(\"Is BST: \" + twoThreeST.isBST() + \" Expected: true\");\n StdOut.println(\"Size consistent: \" + twoThreeST.isSubtreeCountConsistent() + \" Expected: true\");\n\n // Test keys() with range\n StdOut.println(\"\\nKeys in range [2, 10]\");\n for (Integer key : twoThreeST.keys(2, 10)) {\n StdOut.println(\"Key \" + key + \": \" + twoThreeST.get(key));\n }\n\n StdOut.println(\"\\nKeys in range [-4, -1]\");\n for (Integer key : twoThreeST.keys(-4, -1)) {\n StdOut.println(\"Key \" + key + \": \" + twoThreeST.get(key));\n }\n\n // Delete all\n StdOut.println(\"\\nDelete all\");\n while (twoThreeST.size() > 0) {\n for (Integer key : twoThreeST.keys()) {\n StdOut.println(\"Key \" + key + \": \" + twoThreeST.get(key));\n }\n\n // twoThreeST.delete(twoThreeST.select(0));\n twoThreeST.delete(twoThreeST.select(twoThreeST.size() - 1));\n StdOut.println(\"Is BST: \" + twoThreeST.isBST() + \" Expected: true\");\n StdOut.println(\"Size consistent: \" + twoThreeST.isSubtreeCountConsistent() + \" Expected: true\");\n\n StdOut.println();\n }\n }\n}\n", "support_files": [], "metadata": {"number": "3.3.35", "chapter": 3, "chapter_title": "Searching", "section": 3.3, "section_title": "Balanced Search Trees", "type": "Creative Problem", "code_execution": false}} {"question": "2-3-4-5-6-7-8 trees. Describe algorithms for search and insertion in balanced 2-3-4-5-6-7-8 search trees.", "answer": "Search is the direct multiway-search generalization. In a node containing `k` sorted keys (`1 <= k <= 7`), compare the search key with the node keys, return if equal, otherwise follow one of the `k + 1` child links determined by the interval containing the key.\n\nInsertion is the B-tree insertion algorithm for order 8. Maintain all leaves at the same depth. On the way down, if a child is full (7 keys / 8 links), split it before descending: promote its median key to the parent and replace the full child by two nodes containing the lower and upper halves. Then insert the new key in the appropriate leaf. If the root is full, split it first and create a new root.\n\nThe important correction is that a full 8-node is split into two roughly half-full nodes plus one promoted median key; it is not split into eight 2-nodes. Search and insertion both take logarithmic time because every internal node has between 2 and 8 children, except for the root.", "support_files": [], "metadata": {"number": "3.3.36", "chapter": 3, "chapter_title": "Searching", "section": 3.3, "section_title": "Balanced Search Trees", "type": "Creative Problem", "code_execution": false}} {"question": "Memoryless. Show that red-black BSTs are not memoryless: for example, if you insert a key that is smaller than all the keys in the tree and then immediately delete the minimum, you may get a different tree.", "answer": "3.3.37 - Memoryless\n\nIt can be seen that red-black BSTs are not memoryless by observing the following example:\n\nInserting keys in the order N, G, D, F, E, O, L, K, M generates the red-black tree:\n\n (B)G\n (B)E (B)N\n(B)D (B)F (R)L (B)O\n (B)K (B)M\n\n\nTree after inserting minimum key (key A):\n\n (B)G\n (B)E (B)N\n (B)D (B)F (R)L (B)O\n(R)A (B)K (B)M\n\n\nDeleting minimum key (key A):\n\n (R)G (Flip colors)\n (R)E (R)N\n (B)D (B)F (R)L (B)O\n(R)A (B)K (B)M\n\n (R)G (Rotate L right)\n (R)E (R)L\n (B)D (B)F (B)K (R)N\n(R)A (B)M (B)O\n\n (R)L (Rotate G left)\n (R)G (R)N\n (R)E (B)K (B)M (B)O\n (B)D (B)F\n(R)A\n\n (B)L (Flip colors)\n (B)G (B)N\n (R)E (B)K (B)M (B)O\n (B)D (B)F\n(R)A\n\n (B)L (Delete min)\n (B)G (B)N\n (R)E (B)K (B)M (B)O\n(B)D (B)F\n\nThe final red-black tree is different from the original one.\n\nThanks to Hunter-Chen (https://github.com/Hunter-Chen) for mentioning that the previous answer was incorrect.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/186\n", "support_files": [], "metadata": {"number": "3.3.37", "chapter": 3, "chapter_title": "Searching", "section": 3.3, "section_title": "Balanced Search Trees", "type": "Creative Problem", "code_execution": false}} {"question": "Delete the minimum. Implement the deleteMin() operation for red-black BSTs by maintaining the correspondence with the transformations given in the text for moving down the left spine of the tree while maintaining the invariant that the current node is not a 2-node.", "answer": "package chapter3.section3;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 19/06/17.\n */\npublic class Exercise39_DeleteTheMinimum {\n\n private class RedBlackBSTDeleteMin, Value> extends RedBlackBST {\n\n public void deleteMin() {\n if (isEmpty()) {\n return;\n }\n\n if (!isRed(root.left) && !isRed(root.right)) {\n root.color = RED;\n }\n\n root = deleteMin(root);\n\n if (!isEmpty()) {\n root.color = BLACK;\n }\n }\n\n protected Node deleteMin(Node node) {\n if (node.left == null) {\n return null;\n }\n\n if (!isRed(node.left) && !isRed(node.left.left)) {\n node = moveRedLeft(node);\n }\n\n node.left = deleteMin(node.left);\n return balance(node);\n }\n\n protected Node moveRedLeft(Node node) {\n //Assuming that node is red and both node.left and node.left.left are black,\n // make node.left or one of its children red\n flipColors(node);\n\n if (node.right != null && isRed(node.right.left)) {\n node.right = rotateRight(node.right);\n node = rotateLeft(node);\n flipColors(node);\n }\n\n return node;\n }\n\n protected Node balance(Node node) {\n if (node == null) {\n return null;\n }\n\n if (isRed(node.right) && !isRed(node.left)) {\n node = rotateLeft(node);\n }\n\n if (isRed(node.left) && node.left != null && isRed(node.left.left)) {\n node = rotateRight(node);\n }\n\n if (isRed(node.left) && isRed(node.right)) {\n flipColors(node);\n }\n\n node.size = size(node.left) + 1 + size(node.right);\n\n return node;\n }\n\n protected void flipColors(Node node) {\n if (node != null) {\n node.color = !node.color;\n\n if (node.left != null) {\n node.left.color = !node.left.color;\n }\n if (node.right != null) {\n node.right.color = !node.right.color;\n }\n }\n }\n }\n\n public static void main(String[] args) {\n Exercise39_DeleteTheMinimum deleteTheMinimum = new Exercise39_DeleteTheMinimum();\n RedBlackBSTDeleteMin redBlackBST = deleteTheMinimum.new RedBlackBSTDeleteMin<>();\n\n redBlackBST.put(10, 10);\n redBlackBST.put(4, 4);\n redBlackBST.put(6, 6);\n redBlackBST.put(1, 1);\n redBlackBST.put(2, 2);\n redBlackBST.put(15, 15);\n redBlackBST.put(12, 12);\n\n while (!redBlackBST.isEmpty()) {\n for (Integer key : redBlackBST.keys()) {\n StdOut.println(key);\n }\n\n StdOut.println();\n\n StdOut.println(\"Delete min\");\n redBlackBST.deleteMin();\n }\n }\n}\n", "support_files": [], "metadata": {"number": "3.3.39", "chapter": 3, "chapter_title": "Searching", "section": 3.3, "section_title": "Balanced Search Trees", "type": "Creative Problem", "code_execution": false}} {"question": "Delete the maximum. Implement the deleteMax() operation for red-black BSTs. Note that the transformations involved differ slightly from those in the previous exercise because red links are left-leaning.", "answer": "package chapter3.section3;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 21/06/17.\n */\npublic class Exercise40_DeleteTheMaximum {\n\n private class RedBlackBSTDeleteMax, Value> extends RedBlackBST {\n\n public void deleteMax() {\n if (isEmpty()) {\n return;\n }\n\n if (!isRed(root.left) && !isRed(root.right)) {\n root.color = RED;\n }\n\n root = deleteMax(root);\n\n if (!isEmpty()) {\n root.color = BLACK;\n }\n }\n\n private Node deleteMax(Node node) {\n if (isRed(node.left)) {\n node = rotateRight(node);\n }\n\n if (node.right == null) {\n return null;\n }\n\n if (!isRed(node.right) && !isRed(node.right.left)) {\n node = moveRedRight(node);\n }\n\n node.right = deleteMax(node.right);\n return balance(node);\n }\n\n protected Node moveRedRight(Node node) {\n //Assuming that node is red and both node.right and node.right.left are black,\n // make node.right or one of its children red\n flipColors(node);\n\n if (node.left != null && isRed(node.left.left)) {\n node = rotateRight(node);\n flipColors(node);\n }\n\n return node;\n }\n\n protected Node balance(Node node) {\n if (node == null) {\n return null;\n }\n\n if (isRed(node.right) && !isRed(node.left)) {\n node = rotateLeft(node);\n }\n\n if (isRed(node.left) && node.left != null && isRed(node.left.left)) {\n node = rotateRight(node);\n }\n\n if (isRed(node.left) && isRed(node.right)) {\n flipColors(node);\n }\n\n node.size = size(node.left) + 1 + size(node.right);\n\n return node;\n }\n\n protected void flipColors(Node node) {\n if (node != null) {\n node.color = !node.color;\n\n if (node.left != null) {\n node.left.color = !node.left.color;\n }\n if (node.right != null) {\n node.right.color = !node.right.color;\n }\n }\n }\n\n }\n\n public static void main(String[] args) {\n Exercise40_DeleteTheMaximum deleteTheMaximum = new Exercise40_DeleteTheMaximum();\n RedBlackBSTDeleteMax redBlackBST = deleteTheMaximum.new RedBlackBSTDeleteMax<>();\n\n redBlackBST.put(10, 10);\n redBlackBST.put(4, 4);\n redBlackBST.put(6, 6);\n redBlackBST.put(1, 1);\n redBlackBST.put(2, 2);\n redBlackBST.put(15, 15);\n redBlackBST.put(12, 12);\n\n while (!redBlackBST.isEmpty()) {\n\n for (Integer key : redBlackBST.keys()) {\n StdOut.println(key);\n }\n\n StdOut.println();\n\n StdOut.println(\"Delete max\");\n redBlackBST.deleteMax();\n }\n }\n}\n", "support_files": [], "metadata": {"number": "3.3.40", "chapter": 3, "chapter_title": "Searching", "section": 3.3, "section_title": "Balanced Search Trees", "type": "Creative Problem", "code_execution": false}} {"question": "Delete. Implement the delete() operation for red-black BSTs, combining the methods of the previous two exercises with the delete() operation for BSTs.", "answer": "package chapter3.section3;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 22/06/17.\n */\npublic class Exercise41_Delete {\n\n private class RedBlackBSTDelete, Value> extends RedBlackBST {\n\n public void delete(Key key) {\n if (isEmpty()) {\n return;\n }\n\n if (!contains(key)) {\n return;\n }\n\n if (!isRed(root.left) && !isRed(root.right)) {\n root.color = RED;\n }\n\n root = delete(root, key);\n\n if (!isEmpty()) {\n root.color = BLACK;\n }\n }\n\n private Node delete(Node node, Key key) {\n if (node == null) {\n return null;\n }\n\n if (key.compareTo(node.key) < 0) {\n if (!isRed(node.left) && node.left != null && !isRed(node.left.left)) {\n node = moveRedLeft(node);\n }\n\n node.left = delete(node.left, key);\n } else {\n if (isRed(node.left)) {\n node = rotateRight(node);\n }\n\n if (key.compareTo(node.key) == 0 && node.right == null) {\n return null;\n }\n\n if (!isRed(node.right) && node.right != null && !isRed(node.right.left)) {\n node = moveRedRight(node);\n }\n\n if (key.compareTo(node.key) == 0) {\n Node aux = min(node.right);\n node.key = aux.key;\n node.value = aux.value;\n node.right = deleteMin(node.right);\n } else {\n node.right = delete(node.right, key);\n }\n }\n\n return balance(node);\n }\n\n protected Node moveRedLeft(Node node) {\n flipColors(node);\n\n if (node.right != null && isRed(node.right.left)) {\n node.right = rotateRight(node.right);\n node = rotateLeft(node);\n flipColors(node);\n }\n\n return node;\n }\n\n protected Node moveRedRight(Node node) {\n flipColors(node);\n\n if (node.left != null && isRed(node.left.left)) {\n node = rotateRight(node);\n flipColors(node);\n }\n\n return node;\n }\n\n protected Node balance(Node node) {\n if (node == null) {\n return null;\n }\n\n if (isRed(node.right) && !isRed(node.left)) {\n node = rotateLeft(node);\n }\n\n if (isRed(node.left) && node.left != null && isRed(node.left.left)) {\n node = rotateRight(node);\n }\n\n if (isRed(node.left) && isRed(node.right)) {\n flipColors(node);\n }\n\n node.size = size(node.left) + 1 + size(node.right);\n\n return node;\n }\n\n protected void flipColors(Node node) {\n if (node != null) {\n node.color = !node.color;\n\n if (node.left != null) {\n node.left.color = !node.left.color;\n }\n\n if (node.right != null) {\n node.right.color = !node.right.color;\n }\n }\n }\n\n }\n\n public static void main(String[] args) {\n Exercise41_Delete delete = new Exercise41_Delete();\n RedBlackBSTDelete redBlackBST = delete.new RedBlackBSTDelete<>();\n\n redBlackBST.put(10, 10);\n redBlackBST.put(4, 4);\n redBlackBST.put(6, 6);\n redBlackBST.put(1, 1);\n redBlackBST.put(2, 2);\n redBlackBST.put(15, 15);\n redBlackBST.put(12, 12);\n\n StdOut.println(\"Keys\");\n delete.printKeys(redBlackBST);\n\n StdOut.println(\"Delete 1\");\n redBlackBST.delete(1);\n delete.printKeys(redBlackBST);\n\n StdOut.println(\"Delete 15\");\n redBlackBST.delete(15);\n delete.printKeys(redBlackBST);\n\n StdOut.println(\"Delete 10\");\n redBlackBST.delete(10);\n delete.printKeys(redBlackBST);\n\n StdOut.println(\"Delete 6\");\n redBlackBST.delete(6);\n delete.printKeys(redBlackBST);\n\n while (redBlackBST.size() > 0) {\n redBlackBST.delete(redBlackBST.select(0));\n }\n StdOut.println(\"Final size after deleting all keys: \" + redBlackBST.size());\n }\n\n private void printKeys(RedBlackBSTDelete redBlackBST) {\n for (Integer key : redBlackBST.keys()) {\n StdOut.println(key);\n }\n StdOut.println();\n }\n}\n", "support_files": [], "metadata": {"number": "3.3.41", "chapter": 3, "chapter_title": "Searching", "section": 3.3, "section_title": "Balanced Search Trees", "type": "Creative Problem", "code_execution": false}} {"question": "Suppose that keys are t-bit integers. For a modular hash function with prime M, prove that each key bit has the property that there exist two keys differing only in that bit that have different hash values.", "answer": "3.4.6\n\nProposition: With keys that are t-bit integers, for a hash function with prime M, each key bit has the property that there exist two keys differing only in that bit that have different hash values.\n\nProof: Consider the hash function k % M where k is an integer and M is a prime number. \nEvery time that we modify exactly one bit in an integer, we either add (when modifying from 0 to 1) or subtract (when modifying from 1 to 0) a value that is a power of 2 (0, 1, 2, 4, etc). Since we are never adding or subtracting a prime number (other than 2) or any prime number multiples, the modular hash function with a prime M (other than 2) will yield a different result for both numbers.\n\nExample: 5-bit integer 16\n16: 10000\n17: 10001 (differing only in the 1st bit)\n18: 10010 (differing only in the 2nd bit)\n20: 10100 (differing only in the 3rd bit)\n24: 11000 (differing only in the 4th bit)\n8: 01000 (differing only in the 5th bit)\n\nFor M = 7\n\n16 % 7 = 2\n17 % 7 = 3\n18 % 7 = 4\n20 % 7 = 6\n24 % 7 = 3\n8 % 7 = 1\n\nThis definition does not hold for M = 2 though, as can be seen with the numbers 16 and 18, which differ by only 1 bit but have the same hash value in a modular hash function:\n16 % 2 = 0\n18 % 2 = 0\n", "support_files": [], "metadata": {"number": "3.4.6", "chapter": 3, "chapter_title": "Searching", "section": 3.4, "section_title": "Hash Tables", "type": "Exercise", "code_execution": false}} {"question": "Consider the idea of implementing modular hashing for integer keys with the code (a * k) % M, where a is an arbitrary fixed prime. Does this change mix up the bits sufficiently well that you can use nonprime M?", "answer": "3.4.7\n\nIf and only if a and M are coprime, the change will mix up the bits sufficiently well that a nonprime M can be used.\n\nProof:\n1- (a * k) % M = hash\n2- This means that a * k = M * q + hash, which is equivalent to hash = a * k - M * q, where q is a natural number.\n3- Now let's consider that a and M are not coprime.\nThis means that there exists a non-zero natural number t where M = a * t.\nhash = a * k - M * q expands to hash = a * k - a * t * q = a * (k - t * q)\nThis means that all hash values will be divisible by a, which greatly reduces the distribution of keys.\nFor example, if a = 37 and M = 37 * t, then all hash values will be only 0, 37, 74, 111, ...\n\nExample where a is an arbitrary fixed prime:\na = 7\nk = 1, 2, 3, 4\nM = 6\n\n(7 * 1) % 6 = 1\n(7 * 2) % 6 = 2\n(7 * 3) % 6 = 3\n(7 * 4) % 6 = 4\n(7 * 5) % 6 = 5\n(7 * 6) % 6 = 0\n\nExample where a is not an arbitrary fixed prime:\na = 8\nk = 1, 2, 3, 4\nM = 6\n\n(8 * 1) % 6 = 2\n(8 * 2) % 6 = 4\n(8 * 3) % 6 = 0\n(8 * 4) % 6 = 2\n(8 * 5) % 6 = 4\n(8 * 6) % 6 = 0\n\nThanks to dragon-dreamer (https://github.com/dragon-dreamer) for observing and providing the proof that a and M must be coprime.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/125\n", "support_files": [], "metadata": {"number": "3.4.7", "chapter": 3, "chapter_title": "Searching", "section": 3.4, "section_title": "Hash Tables", "type": "Exercise", "code_execution": false}} {"question": "How many empty lists do you expect to see when you insert N keys into a hash table with SeparateChainingHashST, for N=10, 10^2, 10^3, 10^4, 10^5, and 10^6? Hint: See Exercise 2.5.31.", "answer": "3.4.8\n\nAs we have seen on exercise 2.5.31, probability theory says that after generating N random values, the number of distinct values is about M(1 - e^(-a)) where M = the maximum value generated - 1 (in this case, the hash table length - 1), N = number of keys generated and a = N / M.\n\nIn this case M = N, so the hash table length is the same as the number of keys to be inserted:\na = 1\nNumber of distinct values = M(1 - e^(-1))\n\nFor N = 10\nNumber of distinct values = 10(1 - e^(-1))\nNumber of distinct values ~ 6\n\nFor N = 10^2\nNumber of distinct values = 10^2(1 - e^(-1))\nNumber of distinct values ~ 63\n\nFor N = 10^3\nNumber of distinct values = 10^3(1 - e^(-1))\nNumber of distinct values ~ 632\n\nFor N = 10^4\nNumber of distinct values = 10^4(1 - e^(-1))\nNumber of distinct values ~ 6321\n\nFor N = 10^5\nNumber of distinct values = 10^5(1 - e^(-1))\nNumber of distinct values ~ 63212\n\nFor N = 10^6\nNumber of distinct values = 10^6(1 - e^(-1))\nNumber of distinct values ~ 632120\n\nAlso, considering assumption J (uniform hashing assumption) the distinct keys will be distributed uniformly among the M buckets and the lists will have length > 1 only when duplicate keys are inserted. We know that in the real world other collisions may happen but it is a valid approximation. This means that the number of empty lists in the hash table will be equal to M - D where M is the hash table length and D is the number of distinct values inserted. \n\nFor N = 10\nNumber of empty lists expected = 10 - 6 = 4\n\nFor N = 10^2\nNumber of empty lists expected = 10^2 - 63 = 37\n\nFor N = 10^3\nNumber of empty lists expected = 10^3 - 632 = 368\n\nFor N = 10^4\nNumber of empty lists expected = 10^4 - 6321 = 3679\n\nFor N = 10^5\nNumber of empty lists expected = 10^5 - 63212 = 36788\n\nFor N = 10^6\nNumber of empty lists expected = 10^6 - 632120 = 367880\n", "support_files": [], "metadata": {"number": "3.4.8", "chapter": 3, "chapter_title": "Searching", "section": 3.4, "section_title": "Hash Tables", "type": "Exercise", "code_execution": false}} {"question": "Implement an eager delete() method for SeparateChainingHashST.", "answer": "package chapter3.section4;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 20/07/17.\n */\n@SuppressWarnings(\"unchecked\")\npublic class Exercise9 {\n\n private class SeparateChainingHashTableWithDelete extends SeparateChainingHashTable {\n\n public void delete(Key key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Argument to delete() cannot be null\");\n }\n\n if (isEmpty()) {\n return;\n }\n\n if (!contains(key)) {\n return;\n }\n\n symbolTable[hash(key)].delete(key);\n keysSize--;\n\n if (getLoadFactor() <= averageListSize / (double) 4) {\n resize(size / 2);\n }\n }\n\n }\n\n public static void main(String[] args) {\n Exercise9 exercise9 = new Exercise9();\n SeparateChainingHashTableWithDelete separateChainingHashTableWithDelete =\n exercise9.new SeparateChainingHashTableWithDelete<>();\n\n separateChainingHashTableWithDelete.put(1, 1);\n separateChainingHashTableWithDelete.put(2, 2);\n separateChainingHashTableWithDelete.put(3, 3);\n separateChainingHashTableWithDelete.put(4, 4);\n separateChainingHashTableWithDelete.put(5, 5);\n separateChainingHashTableWithDelete.put(6, 6);\n separateChainingHashTableWithDelete.put(7, 7);\n\n StdOut.println(\"Keys\");\n for (Integer key : separateChainingHashTableWithDelete.keys()) {\n StdOut.print(key + \" \");\n }\n\n int[] keysToDelete = {-1, 1, 2, 7, 6, 4, 5, 3};\n for (int k : keysToDelete) {\n StdOut.println(\"\\nDelete key \" + k);\n separateChainingHashTableWithDelete.delete(k);\n\n for (Integer key : separateChainingHashTableWithDelete.keys()) {\n StdOut.print(key + \" \");\n }\n StdOut.println(\"\\nSize: \" + separateChainingHashTableWithDelete.size());\n }\n }\n}\n", "support_files": [], "metadata": {"number": "3.4.9", "chapter": 3, "chapter_title": "Searching", "section": 3.4, "section_title": "Hash Tables", "type": "Exercise", "code_execution": false}} {"question": "Insert the keys E A S Y Q U T I O N in that order into an initially empty table of size M =16 using linear probing. Use the hash function 11 k % M to transform the kth letter of the alphabet into a table index. Redo this exercise for M = 10.", "answer": "3.4.10\n\nM = 16\n\nkey hash value\n E 7 0\n\n0 null 8 null\n1 null 9 null\n2 null 10 null\n3 null 11 null\n4 null 12 null\n5 null 13 null\n6 null 14 null\n7 E0 15 null\n\nkey hash value\n A 11 1\n\n0 null 8 null\n1 null 9 null\n2 null 10 null\n3 null 11 A1\n4 null 12 null\n5 null 13 null\n6 null 14 null\n7 E0 15 null\n\nkey hash value\n S 1 2\n\n0 null 8 null\n1 S2 9 null\n2 null 10 null\n3 null 11 A1\n4 null 12 null\n5 null 13 null\n6 null 14 null\n7 E0 15 null\n\nkey hash value\n Y 3 3\n\n0 null 8 null\n1 S2 9 null\n2 null 10 null\n3 Y3 11 A1\n4 null 12 null\n5 null 13 null\n6 null 14 null\n7 E0 15 null\n\nkey hash value\n Q 11 4\n\n0 null 8 null\n1 S2 9 null\n2 null 10 null\n3 Y3 11 A1\n4 null 12 Q4\n5 null 13 null\n6 null 14 null\n7 E0 15 null\n\nkey hash value\n U 7 5\n\n0 null 8 U5\n1 S2 9 null\n2 null 10 null\n3 Y3 11 A1\n4 null 12 Q4\n5 null 13 null\n6 null 14 null\n7 E0 15 null\n\nkey hash value\n T 12 6\n\n0 null 8 U5\n1 S2 9 null\n2 null 10 null\n3 Y3 11 A1\n4 null 12 Q4\n5 null 13 T6\n6 null 14 null\n7 E0 15 null\n\nkey hash value\n I 3 7\n\n0 null 8 U5\n1 S2 9 null\n2 null 10 null\n3 Y3 11 A1\n4 I7 12 Q4\n5 null 13 T6\n6 null 14 null\n7 E0 15 null\n\nkey hash value\n O 5 8\n\n0 null 8 U5\n1 S2 9 null\n2 null 10 null\n3 Y3 11 A1\n4 I7 12 Q4\n5 O8 13 T6\n6 null 14 null\n7 E0 15 null\n\nkey hash value\n N 10 9\n\n0 null 8 U5\n1 S2 9 null\n2 null 10 N9\n3 Y3 11 A1\n4 I7 12 Q4\n5 O8 13 T6\n6 null 14 null\n7 E0 15 null\n\nM = 10\n\nkey hash value\n E 5 0\n\n0 null 5 E0\n1 null 6 null\n2 null 7 null\n3 null 8 null\n4 null 9 null\n\nkey hash value\n A 1 1\n\n0 null 5 E0\n1 A1 6 null\n2 null 7 null\n3 null 8 null\n4 null 9 null\n\nkey hash value\n S 9 2\n\n0 null 5 E0\n1 A1 6 null\n2 null 7 null\n3 null 8 null\n4 null 9 S2\n\nkey hash value\n Y 5 3\n\n0 null 5 E0\n1 A1 6 Y3\n2 null 7 null\n3 null 8 null\n4 null 9 S2\n\nkey hash value\n Q 7 4\n\n0 null 5 E0\n1 A1 6 Y3\n2 null 7 Q4\n3 null 8 null\n4 null 9 S2\n\nkey hash value\n U 1 5\n\n0 null 5 E0\n1 A1 6 Y3\n2 U5 7 Q4\n3 null 8 null\n4 null 9 S2\n\nkey hash value\n T 0 6\n\n0 T6 5 E0\n1 A1 6 Y3\n2 U5 7 Q4\n3 null 8 null\n4 null 9 S2\n\nkey hash value\n I 9 7\n\n0 T6 5 E0\n1 A1 6 Y3\n2 U5 7 Q4\n3 I7 8 null\n4 null 9 S2\n\nkey hash value\n O 5 8\n\n0 T6 5 E0\n1 A1 6 Y3\n2 U5 7 Q4\n3 I7 8 O8\n4 null 9 S2\n\nkey hash value\n N 4 9\n\n0 T6 5 E0\n1 A1 6 Y3\n2 U5 7 Q4\n3 I7 8 O8\n4 N9 9 S2\n\nThanks to Kongkille (https://github.com/Kongkille) for finding an error in some M = 16 insertions.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/37\n", "support_files": [], "metadata": {"number": "3.4.10", "chapter": 3, "chapter_title": "Searching", "section": 3.4, "section_title": "Hash Tables", "type": "Exercise", "code_execution": false}} {"question": "Give the contents of a linear-probing hash table that results when you insert the keys E A S Y Q U T I O N in that order into an initially empty table of initial size M = 4 that is expanded with doubling whenever half full. Use the hash function 11 k % M to transform the kth letter of the alphabet into a table index.", "answer": "3.4.11\n\nkey hash value\n E 3 0\n\n0 null 2 null\n1 null 3 E0\n\nkey hash value\n A 3 1\n\n0 A1 2 null\n1 null 3 E0\n\nDoubles hash table size and M becomes 8\n\n0 null 4 null\n1 null 5 null\n2 null 6 null\n3 null 7 null\n\nReinsert A1\nkey hash value\n A 3 1\n\n0 null 4 null\n1 null 5 null\n2 null 6 null\n3 A1 7 null\n\nReinsert E0\nkey hash value\n E 7 0\n\n0 null 4 null\n1 null 5 null\n2 null 6 null\n3 A1 7 E0\n\nkey hash value\n S 1 2\n\n0 null 4 null\n1 S2 5 null\n2 null 6 null\n3 A1 7 E0\n\nkey hash value\n Y 3 3\n\n0 null 4 Y3\n1 S2 5 null\n2 null 6 null\n3 A1 7 E0\n\nDoubles hash table size and M becomes 16\n\n0 null 8 null\n1 null 9 null\n2 null 10 null\n3 null 11 null\n4 null 12 null\n5 null 13 null\n6 null 14 null\n7 null 15 null\n\nReinsert A1\nkey hash value\n A 11 1\n\n0 null 8 null\n1 null 9 null\n2 null 10 null\n3 null 11 A1\n4 null 12 null\n5 null 13 null\n6 null 14 null\n7 null 15 null\n\nReinsert E0\nkey hash value\n E 7 0\n\n0 null 8 null\n1 null 9 null\n2 null 10 null\n3 null 11 A1\n4 null 12 null\n5 null 13 null\n6 null 14 null\n7 E0 15 null\n\nReinsert S2\nkey hash value\n S 1 2\n\n0 null 8 null\n1 S2 9 null\n2 null 10 null\n3 null 11 A1\n4 null 12 null\n5 null 13 null\n6 null 14 null\n7 E0 15 null\n\nReinsert Y3\nkey hash value\n Y 3 3\n\n0 null 8 null\n1 S2 9 null\n2 null 10 null\n3 Y3 11 A1\n4 null 12 null\n5 null 13 null\n6 null 14 null\n7 E0 15 null\n\nkey hash value\n Q 11 4\n\n0 null 8 null\n1 S2 9 null\n2 null 10 null\n3 Y3 11 A1\n4 null 12 Q4\n5 null 13 null\n6 null 14 null\n7 E0 15 null\n\nkey hash value\n U 7 5\n\n0 null 8 U5\n1 S2 9 null\n2 null 10 null\n3 Y3 11 A1\n4 null 12 Q4\n5 null 13 null\n6 null 14 null\n7 E0 15 null\n\nkey hash value\n T 12 6\n\n0 null 8 U5\n1 S2 9 null\n2 null 10 null\n3 Y3 11 A1\n4 null 12 Q4\n5 null 13 T6\n6 null 14 null\n7 E0 15 null\n\nkey hash value\n I 3 7\n\n0 null 8 U5\n1 S2 9 null\n2 null 10 null\n3 Y3 11 A1\n4 I7 12 Q4\n5 null 13 T6\n6 null 14 null\n7 E0 15 null\n\nDoubles hash table size and M becomes 32\n\n 0 null 16 null\n 1 null 17 null\n 2 null 18 null\n 3 null 19 null\n 4 null 20 null\n 5 null 21 null\n 6 null 22 null\n 7 null 23 null\n 8 null 24 null\n 9 null 25 null\n10 null 26 null\n11 null 27 null\n12 null 28 null\n13 null 29 null\n14 null 30 null\n15 null 31 null\n\nReinsert A1\nkey hash value\n A 11 1\n\n 0 null 16 null\n 1 null 17 null\n 2 null 18 null\n 3 null 19 null\n 4 null 20 null\n 5 null 21 null\n 6 null 22 null\n 7 null 23 null\n 8 null 24 null\n 9 null 25 null\n10 null 26 null\n11 A1 27 null\n12 null 28 null\n13 null 29 null\n14 null 30 null\n15 null 31 null\n\nReinsert E0\nkey hash value\n E 23 0\n\n 0 null 16 null\n 1 null 17 null\n 2 null 18 null\n 3 null 19 null\n 4 null 20 null\n 5 null 21 null\n 6 null 22 null\n 7 null 23 E0\n 8 null 24 null\n 9 null 25 null\n10 null 26 null\n11 A1 27 null\n12 null 28 null\n13 null 29 null\n14 null 30 null\n15 null 31 null\n\nReinsert I7\nkey hash value\n I 3 7\n\n 0 null 16 null\n 1 null 17 null\n 2 null 18 null\n 3 I7 19 null\n 4 null 20 null\n 5 null 21 null\n 6 null 22 null\n 7 null 23 E0\n 8 null 24 null\n 9 null 25 null\n10 null 26 null\n11 A1 27 null\n12 null 28 null\n13 null 29 null\n14 null 30 null\n15 null 31 null\n\nReinsert Q4\nkey hash value\n Q 27 4\n\n 0 null 16 null\n 1 null 17 null\n 2 null 18 null\n 3 I7 19 null\n 4 null 20 null\n 5 null 21 null\n 6 null 22 null\n 7 null 23 E0\n 8 null 24 null\n 9 null 25 null\n10 null 26 null\n11 A1 27 Q4\n12 null 28 null\n13 null 29 null\n14 null 30 null\n15 null 31 null\n\nReinsert S2\nkey hash value\n S 17 2\n\n 0 null 16 null\n 1 null 17 S2\n 2 null 18 null\n 3 I7 19 null\n 4 null 20 null\n 5 null 21 null\n 6 null 22 null\n 7 null 23 E0\n 8 null 24 null\n 9 null 25 null\n10 null 26 null\n11 A1 27 Q4\n12 null 28 null\n13 null 29 null\n14 null 30 null\n15 null 31 null\n\nReinsert T6\nkey hash value\n T 28 6\n\n 0 null 16 null\n 1 null 17 S2\n 2 null 18 null\n 3 I7 19 null\n 4 null 20 null\n 5 null 21 null\n 6 null 22 null\n 7 null 23 E0\n 8 null 24 null\n 9 null 25 null\n10 null 26 null\n11 A1 27 Q4\n12 null 28 T6\n13 null 29 null\n14 null 30 null\n15 null 31 null\n\nReinsert U5\nkey hash value\n U 7 5\n\n 0 null 16 null\n 1 null 17 S2\n 2 null 18 null\n 3 I7 19 null\n 4 null 20 null\n 5 null 21 null\n 6 null 22 null\n 7 U5 23 E0\n 8 null 24 null\n 9 null 25 null\n10 null 26 null\n11 A1 27 Q4\n12 null 28 T6\n13 null 29 null\n14 null 30 null\n15 null 31 null\n\nReinsert Y3\nkey hash value\n Y 19 3\n\n 0 null 16 null\n 1 null 17 S2\n 2 null 18 null\n 3 I7 19 Y3\n 4 null 20 null\n 5 null 21 null\n 6 null 22 null\n 7 U5 23 E0\n 8 null 24 null\n 9 null 25 null\n10 null 26 null\n11 A1 27 Q4\n12 null 28 T6\n13 null 29 null\n14 null 30 null\n15 null 31 null\n\nkey hash value\n O 5 8\n\n 0 null 16 null\n 1 null 17 S2\n 2 null 18 null\n 3 I7 19 Y3\n 4 null 20 null\n 5 O8 21 null\n 6 null 22 null\n 7 U5 23 E0\n 8 null 24 null\n 9 null 25 null\n10 null 26 null\n11 A1 27 Q4\n12 null 28 T6\n13 null 29 null\n14 null 30 null\n15 null 31 null\n\nkey hash value\n N 26 9\n\n 0 null 16 null\n 1 null 17 S2\n 2 null 18 null\n 3 I7 19 Y3\n 4 null 20 null\n 5 O8 21 null\n 6 null 22 null\n 7 U5 23 E0\n 8 null 24 null\n 9 null 25 null\n10 null 26 N9\n11 A1 27 Q4\n12 null 28 T6\n13 null 29 null\n14 null 30 null\n15 null 31 null\n", "support_files": [], "metadata": {"number": "3.4.11", "chapter": 3, "chapter_title": "Searching", "section": 3.4, "section_title": "Hash Tables", "type": "Exercise", "code_execution": false}} {"question": "Which of the following scenarios leads to expected linear running time for a random search hit in a linear-probing hash table?\na. All keys hash to the same index.\nb. All keys hash to different indices.\nc. All keys hash to an even-numbered index.\nd. All keys hash to different even-numbered indices.", "answer": "Only scenario (a) necessarily leads to expected linear running time for a random search hit: if all keys hash to the same table index, they form one contiguous cluster, and a random hit probes a linear number of positions on average.\n\nScenario (b) is the best case. Scenario (d) is not necessarily linear, because different even positions may still keep probe sequences short when the load factor is moderate. Scenario (c) is not sufficient as stated: hashing only to even-numbered positions can create extra clustering, but it is not guaranteed to make every random successful search linear unless the keys also form a linear-size cluster.", "support_files": [], "metadata": {"number": "3.4.13", "chapter": 3, "chapter_title": "Searching", "section": 3.4, "section_title": "Hash Tables", "type": "Exercise", "code_execution": false}} {"question": "Which of the following scenarios leads to expected linear running time for a search miss in a linear-probing hash table, assuming the search key is equally likely to hash to each table position?\n\na. All keys hash to the same index.\nb. All keys hash to different indices.\nc. All keys hash to an even-numbered index.\nd. All keys hash to different even-numbered indices.", "answer": "Scenario (a) necessarily gives expected linear time for a search miss: all keys form one large cluster, and misses that hash into or before that cluster scan a linear number of entries.\n\nScenario (c) can also be linear when the even-index restriction creates a linear-size cluster, but it is not guaranteed solely from the statement. Scenarios (b) and (d) do not necessarily give linear miss cost; with well-spread keys and a bounded load factor, misses can remain constant expected time.", "support_files": [], "metadata": {"number": "3.4.14", "chapter": 3, "chapter_title": "Searching", "section": 3.4, "section_title": "Hash Tables", "type": "Exercise", "code_execution": false}} {"question": "How many compares could it take, in the worst case, to insert N keys into an initially empty table, using linear probing with array resizing?", "answer": "3.4.15\n\nIn the worst case all keys hash to the same index.\nThe exercise description does not mention the initial hash table size. This is important to compute the number of compares in a hash table with array resizing. This exercise answer assumes that the initial hash table size is N and its size is expanded with doubling whenever half full.\n\nThe number of compares per insert is:\n1 for the first insert, 2 for the second insert, 3 for the third insert and so on, until the (N/2)th insert.\nWhen the table is half full it is resized to 2N and the keys are reinserted, with 1, 2, 3, ..., N/2 compares.\n\nThen, for the insert of the other keys there are N/2 + 1, N/2 + 2, ..., N compares per insert.\n\nThis is equal to:\nNumber of compares = (1 + 2 + 3 + ... + N/2) + 1 + 2 + 3 + ... + N/2 + (N/2 + 1) + (N/2 + 2) + ... + N\nNumber of compares = (N/2 + 1) * N / 2 / 2 + (N + 1) * N / 2\nNumber of compares = (N^2/2 + N) / 4 + (N^2 + N) / 2\nNumber of compares = (N^2/2 + N) / 4 + (2N^2 + 2N) / 4\nNumber of compares = (N^2/2 + (2N / 2)) / 4 + (2N^2 + 2N) / 4\nNumber of compares = (N^2 + 2N) / 8 + (4N^2 + 4N) / 8\nNumber of compares = (5N^2 + 6N) / 8\n\nIn the worst case, to insert N keys into an initially empty table, using linear probing with array resizing it would take (5N^2 + 6N) / 8 compares.\n", "support_files": [], "metadata": {"number": "3.4.15", "chapter": 3, "chapter_title": "Searching", "section": 3.4, "section_title": "Hash Tables", "type": "Exercise", "code_execution": false}} {"question": "Add a constructor to SeparateChainingHashST that gives the client the ability to specify the average number of probes to be tolerated for searches. Use array resizing to keep the average list size less than the specified value, and use the technique described on page 478 to ensure that the modulus for hash() is prime.", "answer": "package chapter3.section4;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 21/07/17.\n */\n@SuppressWarnings(\"unchecked\")\npublic class Exercise18 {\n\n private class SeparateChainingHashTableResize extends SeparateChainingHashTable{\n private int averageListSize;\n\n // The largest prime <= 2^i for i = 1 to 31\n // Used to distribute keys uniformly in the hash table after resizes\n // PRIMES[n] = 2^k - Ak where k is the power of 2 and Ak is the value to subtract to reach the previous prime number\n private final int[] PRIMES = {\n 1, 1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381,\n 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301,\n 8388593, 16777213, 33554393, 67108859, 134217689, 268435399,\n 536870909, 1073741789, 2147483647\n };\n\n //The lg of the hash table size\n //Used in combination with PRIMES[] to distribute keys uniformly in the hash function after resizes\n private int lgM;\n\n public SeparateChainingHashTableResize(int initialSize, int averageListSize) {\n super(initialSize, averageListSize);\n\n this.size = initialSize;\n this.averageListSize = averageListSize;\n symbolTable = new SequentialSearchSymbolTable[size];\n\n for (int i = 0; i < size; i++) {\n symbolTable[i] = new SequentialSearchSymbolTable();\n }\n\n lgM = (int) (Math.log(size) / Math.log(2));\n }\n\n protected int hash(Key key) {\n int hash = key.hashCode() & 0x7fffffff;\n\n if (lgM < 26) {\n hash = hash % PRIMES[lgM + 5];\n }\n\n return hash % size;\n }\n\n public void resize(int newSize) {\n SeparateChainingHashTableResize separateChainingHashTableTemp =\n new SeparateChainingHashTableResize<>(newSize, averageListSize);\n\n for (Key key : keys()) {\n separateChainingHashTableTemp.put(key, get(key));\n }\n\n symbolTable = separateChainingHashTableTemp.symbolTable;\n size = separateChainingHashTableTemp.size;\n keysSize = separateChainingHashTableTemp.keysSize;\n lgM = separateChainingHashTableTemp.lgM;\n }\n\n public void put(Key key, Value value) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n if (value == null) {\n delete(key);\n return;\n }\n\n int hashIndex = hash(key);\n int currentSize = symbolTable[hashIndex].size;\n symbolTable[hashIndex].put(key, value);\n\n if (currentSize < symbolTable[hashIndex].size) {\n keysSize++;\n }\n\n if (getLoadFactor() >= averageListSize) {\n StdOut.println(\"Resize - doubling hash table size\");\n\n resize(size * 2);\n }\n }\n\n public void delete(Key key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Argument to delete() cannot be null\");\n }\n\n if (isEmpty() || !contains(key)) {\n return;\n }\n\n symbolTable[hash(key)].delete(key);\n keysSize--;\n\n if (size > 1 && getLoadFactor() <= averageListSize / (double) 4) {\n StdOut.println(\"Resize - shrinking hash table size\");\n\n resize(size / 2);\n }\n }\n }\n\n public static void main(String[] args) {\n Exercise18 exercise18 = new Exercise18();\n SeparateChainingHashTableResize separateChainingHashTableResize =\n exercise18.new SeparateChainingHashTableResize<>(5, 2);\n\n for (int i = 0; i < 20; i++) {\n separateChainingHashTableResize.put(i, i);\n }\n StdOut.println(\"Expected: Resize - doubling hash table size 2x\");\n\n for (int i = 0; i < 10; i++) {\n separateChainingHashTableResize.delete(i);\n }\n StdOut.println(\"Expected: Resize - shrinking hash table size\");\n\n for (int i = 10; i < 15; i++) {\n separateChainingHashTableResize.delete(i);\n }\n StdOut.println(\"Expected: Resize - shrinking hash table size\");\n }\n}\n", "support_files": [], "metadata": {"number": "3.4.18", "chapter": 3, "chapter_title": "Searching", "section": 3.4, "section_title": "Hash Tables", "type": "Exercise", "code_execution": false}} {"question": "Add a method to LinearProbingHashST that computes the average cost of a search hit in the table, assuming that each key in the table is equally likely to be sought.", "answer": "package chapter3.section4;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 21/07/17.\n */\n// Thanks to faame (https://github.com/faame) for fixing a bug in the compare count in this exercise.\n// https://github.com/reneargento/algorithms-sedgewick-wayne/issues/236\npublic class Exercise20 {\n\n private class LinearProbingHashTableAvgSearchHitCost extends LinearProbingHashTable {\n\n LinearProbingHashTableAvgSearchHitCost(int size) {\n super(size);\n }\n\n public double getAverageCostOfSearchHit() {\n if (keysSize == 0) {\n return 0.0;\n }\n int totalCompares = 0;\n for (int i = 0; i < size; i++) {\n if (keys[i] == null) {\n continue;\n }\n int compares = 1;\n for (int tableIndex = hash(keys[i]); !keys[tableIndex].equals(keys[i]);\n tableIndex = (tableIndex + 1) % size) {\n compares++;\n }\n totalCompares += compares;\n }\n return totalCompares / (double) keysSize;\n }\n\n private double totalNumberOfComparesForSearchHit;\n\n private void resize(int newSize) {\n LinearProbingHashTableAvgSearchHitCost tempHashTable =\n new LinearProbingHashTableAvgSearchHitCost<>(newSize);\n\n for (int i = 0; i < size; i++) {\n if (keys[i] != null) {\n tempHashTable.put(keys[i], values[i]);\n }\n }\n\n keys = tempHashTable.keys;\n values = tempHashTable.values;\n size = tempHashTable.size;\n totalNumberOfComparesForSearchHit = tempHashTable.totalNumberOfComparesForSearchHit;\n }\n\n public Value get(Key key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Argument to get() cannot be null\");\n }\n int numberOfComparesBeforeFindingKey = 0;\n\n for (int tableIndex = hash(key); keys[tableIndex] != null; tableIndex = (tableIndex + 1) % size) {\n numberOfComparesBeforeFindingKey++;\n\n if (keys[tableIndex].equals(key)) {\n totalNumberOfComparesForSearchHit += numberOfComparesBeforeFindingKey;\n return values[tableIndex];\n }\n }\n return null;\n }\n\n public void put(Key key, Value value) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n if (value == null) {\n delete(key);\n return;\n }\n\n if (keysSize >= size / (double) 2) {\n resize(size * 2);\n lgM++;\n }\n\n int numberOfComparesBeforeFindingKey = 0;\n\n int tableIndex;\n for (tableIndex = hash(key); keys[tableIndex] != null; tableIndex = (tableIndex + 1) % size) {\n numberOfComparesBeforeFindingKey++;\n\n if (keys[tableIndex].equals(key)) {\n totalNumberOfComparesForSearchHit += numberOfComparesBeforeFindingKey;\n values[tableIndex] = value;\n return;\n }\n }\n\n keys[tableIndex] = key;\n values[tableIndex] = value;\n keysSize++;\n }\n }\n\n public static void main(String[] args) {\n Exercise20 exercise20 = new Exercise20();\n LinearProbingHashTableAvgSearchHitCost linearProbingHashTableAvgSearchHitCost =\n exercise20.new LinearProbingHashTableAvgSearchHitCost<>(20);\n\n linearProbingHashTableAvgSearchHitCost.put(5, 5);\n StdOut.println(linearProbingHashTableAvgSearchHitCost.getAverageCostOfSearchHit() + \" Expected: 0.0\");\n\n linearProbingHashTableAvgSearchHitCost.get(5);\n StdOut.println(linearProbingHashTableAvgSearchHitCost.getAverageCostOfSearchHit() + \" Expected: 1.0\");\n\n linearProbingHashTableAvgSearchHitCost.get(5);\n StdOut.println(linearProbingHashTableAvgSearchHitCost.getAverageCostOfSearchHit() + \" Expected: 2.0\");\n\n linearProbingHashTableAvgSearchHitCost.put(5, 5);\n StdOut.println(linearProbingHashTableAvgSearchHitCost.getAverageCostOfSearchHit() + \" Expected: 3.0\");\n\n linearProbingHashTableAvgSearchHitCost.put(7, 7);\n StdOut.println(linearProbingHashTableAvgSearchHitCost.getAverageCostOfSearchHit() + \" Expected: 1.5\");\n }\n}\n", "support_files": [], "metadata": {"number": "3.4.20", "chapter": 3, "chapter_title": "Searching", "section": 3.4, "section_title": "Hash Tables", "type": "Exercise", "code_execution": false}} {"question": "Add a method to LinearProbingHashST that computes the average cost of a search miss in the table, assuming a random hash function. Note: You do not have to compute any hash functions to solve this problem.", "answer": "package chapter3.section4;\n\nimport edu.princeton.cs.algs4.StdOut;\nimport edu.princeton.cs.algs4.StdRandom;\n\n/**\n * Created by Rene Argento on 21/07/17.\n */\npublic class Exercise21 {\n\n private class LinearProbingHashTableAvgSearchMissCost extends LinearProbingHashTable {\n\n LinearProbingHashTableAvgSearchMissCost(int size) {\n super(size);\n }\n\n // Average cost of search miss = ~1/2 * (1 + (1 / (1 - a)^2))\n public double getAverageCostOfSearchMissByLoadFactor() {\n double loadFactor = getLoadFactor();\n return 0.5 * (1 + (1 / Math.pow(1 - loadFactor, 2)));\n }\n\n // Average cost of search miss = 1 + N / 2M + (sum((cluster[i].size)^2)) / 2M for all clusters in the table\n public double getAverageCostOfSearchMissByClusterSizes() {\n int clusterSize = 0;\n int clusterSizeSquareSum = 0;\n \n for (int i = 0; i < size; i++) {\n if (keys[i] != null) {\n clusterSize++;\n } else {\n clusterSizeSquareSum += clusterSize * clusterSize;\n clusterSize = 0;\n }\n }\n\n if (clusterSize != 0) {\n clusterSizeSquareSum += clusterSize * clusterSize;\n }\n return 1 + ((double) (keysSize + clusterSizeSquareSum)) / (size * 2);\n }\n }\n\n public static void main(String[] args) {\n Exercise21 exercise21 = new Exercise21();\n LinearProbingHashTableAvgSearchMissCost linearProbingHashTableAvgSearchMissCost =\n exercise21.new LinearProbingHashTableAvgSearchMissCost<>(1000000);\n\n for (int i = 0; i < 500000; i++) {\n int randomKey = StdRandom.uniform(Integer.MAX_VALUE);\n linearProbingHashTableAvgSearchMissCost.put(randomKey, randomKey);\n }\n\n StdOut.printf(\"Average cost of search miss by load factor: %.2f\\n\",\n linearProbingHashTableAvgSearchMissCost.getAverageCostOfSearchMissByLoadFactor());\n StdOut.printf(\"Average cost of search miss by cluster sizes: %.2f\\n\",\n linearProbingHashTableAvgSearchMissCost.getAverageCostOfSearchMissByClusterSizes());\n }\n}\n", "support_files": [], "metadata": {"number": "3.4.21", "chapter": 3, "chapter_title": "Searching", "section": 3.4, "section_title": "Hash Tables", "type": "Exercise", "code_execution": false}} {"question": "Consider modular hashing for string keys with R = 256 and M = 255. Show that this is a bad choice because any permutation of letters within a string hashes to the same value.", "answer": "3.4.23\n\nGiven R = 256 and M = 255, we shall prove that the hash of all strings with the same collection of chars is the same.\nIn fact, we can prove the proposition that hash(string) = (sum of chars) % 255 for all strings by induction on string\nlength.\n\nFor any string with only one char, the proposition holds trivially.\nLet hash(str{k}) denote the hash of a string no longer than k, char(k) is the k-th char.\nBy induction assumption, we have:\nhash(str{k}) = (sum of k chars) % 255\n\nThen we have:\nhash(str{k + 1}) = (hash(str{k}) * 256 + char(k + 1)) % 255\n = (hash(str{k}) * (255 + 1) + char(k + 1)) % 255\n = (hash(str{k}) * 255 + hash(str{k}) + char(k + 1)) % 255\n = (hash(str{k}) + char(k + 1)) % 255\n = ((sum of k chars) % 255 + char(k + 1)) % 255\n = ((sum of k chars + char(k + 1)) % 255) % 255\n = (sum of k + 1 chars) % 255\nNote that (N * 255) % 255 = 0, and the char values are always less than 255, so the chars can be moved into the modular\nexpression.\n\nHence, by induction, the proposition holds for strings of any length.\nAll strings with the same collection of chars must have the same sum of chars, so by the proposition they must have the\nsame hash.\n\nThanks to luowyang (https://github.com/luowyang) for improving the answer and providing a proof for this exercise.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/95\n", "support_files": [], "metadata": {"number": "3.4.23", "chapter": 3, "chapter_title": "Searching", "section": 3.4, "section_title": "Hash Tables", "type": "Exercise", "code_execution": false}} {"question": "Double probing. Modify SeparateChainingHashST to use a second hash function and pick the shorter of the two lists. Give a trace of the process of inserting the keys E A S Y Q U T I O N in that order into an initially empty table of size M =3 using the function 11 k % M (for the kth letter) as the first hash function and the function 17 k % M (for the kth letter) as the second hash function. Give the average number of probes for random search hit and search miss in this table.", "answer": "Because 11 mod 3 and 17 mod 3 are both 2, the two hash functions are identical for this table size. Double probing therefore degenerates to ordinary separate chaining with one candidate chain.\n\nUsing A=1, B=2, ..., Z=26, the final chains are:\n\n0: O, I, U\n1: N, T, Q, E\n2: Y, S, A\n\nIf new keys are inserted at the front of their chain, the average number of probes for a random successful search is\n\n (1 + 2 + 3 + 1 + 2 + 3 + 4 + 1 + 2 + 3) / 10 = 22 / 10 = 2.2\n\nFor an unsuccessful search, the chain searched is chosen by the hash value, so the average number of probes is\n\n (3 + 4 + 3) / 3 = 10 / 3\n\nThe trace should not average over a distinct second list, since the two hash functions choose the same list for every key when M = 3.\n", "support_files": [], "metadata": {"number": "3.4.27", "chapter": 3, "chapter_title": "Searching", "section": 3.4, "section_title": "Hash Tables", "type": "Creative Problem", "code_execution": false}} {"question": "Cuckoo hashing. Develop a symbol-table implementation that maintains two hash tables and two hash functions. Any given key is in one of the tables, but not both. When inserting a new key, hash to one of the tables; if the table position is occupied, replace that key with the new key and hash the old key into the other table (again kicking out a key that might reside there). If this process cycles, restart. Keep the tables less than half full. This method uses a constant number of equality tests in the worst case for search (trivial) and amortized constant time for insert.", "answer": "package chapter3.section4;\n\nimport edu.princeton.cs.algs4.Queue;\nimport edu.princeton.cs.algs4.StdOut;\nimport edu.princeton.cs.algs4.StdRandom;\n\nimport java.lang.reflect.Array;\nimport java.util.Arrays;\n\n/**\n * Created by Rene Argento on 24/07/17.\n */\n// Based on http://www.keithschwarz.com/interesting/code/cuckoo-hashmap/CuckooHashMap.java.html\n@SuppressWarnings(\"unchecked\")\npublic class Exercise31_CuckooHashing {\n\n private class CuckooHashing {\n\n private class Entry {\n Key key;\n Value value;\n\n Entry(Key key, Value value) {\n this.key = key;\n this.value = value;\n }\n }\n\n private final class HashFunction {\n private final int mA, mB; // Coefficients for this hash function\n private final int mLgSize; // Log of the size of the hash tables.\n\n /**\n * Constructs a new hash function using the specified coefficients and\n * the log of the number of buckets in the hash table.\n */\n public HashFunction(int coefficientA, int coefficientB, int lgSize) {\n mA = coefficientA;\n mB = coefficientB;\n mLgSize = lgSize;\n }\n\n public int hash(Key key) {\n /* If the object is null, just evaluate to zero. */\n if (key == null) {\n return 0;\n }\n\n /* Otherwise, split its hash code into upper and lower bits. */\n final int hashCode = key.hashCode();\n final int upper = hashCode >>> 16;\n final int lower = hashCode & (0xFFFF);\n\n /* Return the pairwise product of those bits, shifted down so that\n * only lgSize bits remain in the output.\n */\n return (upper * mA + lower * mB) >>> (32 - mLgSize);\n }\n }\n\n private int keysSize;\n private int size;\n\n private Entry keysAndValues[][];\n private HashFunction[] hashFunctions;\n\n CuckooHashing(int size) {\n this.size = size;\n\n keysAndValues = (Entry[][]) Array.newInstance(Entry.class,\n 2, size);\n\n // The lg of the hash table size\n // Used to distribute keys uniformly in the hash function\n int lgM = (int) (Math.log(size) / Math.log(2));\n\n hashFunctions = new HashFunction[2];\n for (int i = 0; i < 2; i++) {\n int randomCoefficientA = StdRandom.uniform(Integer.MAX_VALUE);\n int randomCoefficientB = StdRandom.uniform(Integer.MAX_VALUE);\n\n hashFunctions[i] = new HashFunction(randomCoefficientA, randomCoefficientB, lgM);\n }\n }\n\n public boolean isEmpty() {\n return keysSize == 0;\n }\n\n public int keysSize() {\n return keysSize;\n }\n\n private void updateHashFunctions() {\n int lgM = (int) (Math.log(size) / Math.log(2));\n\n for (int i = 0; i < 2; i++) {\n int randomCoefficientA = StdRandom.uniform(Integer.MAX_VALUE);\n int randomCoefficientB = StdRandom.uniform(Integer.MAX_VALUE);\n\n hashFunctions[i] = new HashFunction(randomCoefficientA, randomCoefficientB, lgM);\n }\n }\n\n private void resize(int newSize) {\n StdOut.println(\"New Size: \" + newSize);\n\n size = newSize;\n\n Entry[][] oldEntries = keysAndValues;\n keysAndValues = (Entry[][]) Array.newInstance(Entry.class,\n 2, newSize);\n\n boolean tryToResize = true;\n\n while (tryToResize) {\n tryToResize = false;\n\n updateHashFunctions();\n\n for (Entry[] keysAndValues : keysAndValues) {\n Arrays.fill(keysAndValues, null);\n }\n\n // Try to add all keys and values\n // Hash table 1\n for (Entry entry : oldEntries[0]) {\n if (entry != null && tryToInsert(entry) != null) {\n tryToResize = true;\n break;\n }\n }\n\n // Hash table 2\n if (!tryToResize) {\n for (Entry entry : oldEntries[1]) {\n if (entry != null && tryToInsert(entry) != null) {\n tryToResize = true;\n break;\n }\n }\n }\n }\n }\n\n private void rehash() {\n StdOut.println(\"Rehashing Keys: \" + keysSize);\n\n Entry[] tempKeysAndValues = (Entry[]) Array.newInstance(Entry.class, keysSize);\n int tempKeysAndValuesIndex = 0;\n\n for (int i = 0; i < 2; i++) {\n for (Entry entry : keysAndValues[i]) {\n if (entry != null) {\n tempKeysAndValues[tempKeysAndValuesIndex++] = entry;\n }\n }\n }\n\n boolean tryToRehash = true;\n\n while (tryToRehash) {\n tryToRehash = false;\n\n updateHashFunctions();\n\n for (Entry[] keysAndValues : keysAndValues) {\n Arrays.fill(keysAndValues, null);\n }\n\n // Try to add all keys and values\n for (Entry entry : tempKeysAndValues) {\n if (tryToInsert(entry) != null) {\n tryToRehash = true;\n break;\n }\n }\n }\n }\n\n public boolean contains(Key key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Argument to contains() cannot be null\");\n }\n return get(key) != null;\n }\n\n public Value get(Key key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Argument to get() cannot be null\");\n }\n\n for (int hashTableIndex = 0; hashTableIndex < 2; hashTableIndex++) {\n int hash = hashFunctions[hashTableIndex].hash(key);\n\n if (keysAndValues[hashTableIndex][hash] != null && keysAndValues[hashTableIndex][hash].key.equals(key)) {\n return keysAndValues[hashTableIndex][hash].value;\n }\n }\n return null;\n }\n\n public void put(Key key, Value value) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n if (value == null) {\n delete(key);\n return;\n }\n\n // Update key if it already exists\n for (int hashTableIndex = 0; hashTableIndex < 2; hashTableIndex++) {\n int hash = hashFunctions[hashTableIndex].hash(key);\n\n if (keysAndValues[hashTableIndex][hash] != null && keysAndValues[hashTableIndex][hash].key.equals(key)) {\n keysAndValues[hashTableIndex][hash].value = value;\n return;\n }\n }\n\n // Key does not exist, let's insert it\n // Check if the number of keys is equal or more than half of the hash table size\n if (keysSize >= size) {\n resize(size * 2);\n }\n\n Entry entry = new Entry(key, value);\n while (entry != null) {\n entry = tryToInsert(entry);\n\n if (entry != null) {\n rehash();\n }\n }\n\n keysSize++;\n }\n\n /**\n * Given an Entry, tries to insert that entry into the hash table, taking\n * several iterations if necessary.\n *\n * @return The last displaced entry, or null if all collisions were resolved.\n */\n private Entry tryToInsert(Entry entry) {\n int maxTries = size + 1;\n int hashTableIndex = 0;\n\n for (int numberOfTries = 0; numberOfTries < maxTries; numberOfTries++) {\n int hash = hashFunctions[hashTableIndex].hash(entry.key);\n\n if (keysAndValues[hashTableIndex][hash] == null) {\n keysAndValues[hashTableIndex][hash] = entry;\n return null;\n }\n\n Entry entryToDisplace = keysAndValues[hashTableIndex][hash];\n keysAndValues[hashTableIndex][hash] = entry;\n\n entry = entryToDisplace;\n hashTableIndex = (hashTableIndex + 1) % 2;\n }\n return entry;\n }\n\n public void delete(Key key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Argument to delete() cannot be null\");\n }\n\n if (!contains(key)) {\n return;\n }\n\n for (int hashTableIndex = 0; hashTableIndex < 2; hashTableIndex++) {\n int hash = hashFunctions[hashTableIndex].hash(key);\n\n if (keysAndValues[hashTableIndex][hash] != null && keysAndValues[hashTableIndex][hash].key.equals(key)) {\n keysAndValues[hashTableIndex][hash] = null;\n break;\n }\n }\n\n keysSize--;\n\n if (keysSize > 1 && keysSize <= size / (double) 8) {\n resize(size / 2);\n }\n }\n\n public Iterable keys() {\n Queue keySet = new Queue<>();\n\n for (int hashTableIndex = 0; hashTableIndex < keysAndValues.length; hashTableIndex++) {\n for (Entry entry : keysAndValues[hashTableIndex]) {\n if (entry != null) {\n keySet.enqueue(entry.key);\n }\n }\n }\n\n if (!keySet.isEmpty() && keySet.peek() instanceof Comparable) {\n Key[] keysToBeSorted = (Key[]) new Comparable[keySet.size()];\n for (int i = 0; i < keysToBeSorted.length; i++) {\n keysToBeSorted[i] = keySet.dequeue();\n }\n\n Arrays.sort(keysToBeSorted);\n\n for (Key key : keysToBeSorted) {\n keySet.enqueue(key);\n }\n }\n return keySet;\n }\n }\n\n public static void main(String[] args) {\n Exercise31_CuckooHashing exercise31_cuckooHashing = new Exercise31_CuckooHashing();\n CuckooHashing cuckooHashing = exercise31_cuckooHashing.new CuckooHashing<>(16);\n\n for (int key = 1; key < 10; key++) {\n int randomKey = StdRandom.uniform(Integer.MAX_VALUE);\n cuckooHashing.put(randomKey, randomKey);\n }\n\n cuckooHashing.get(5);\n\n for (Integer key : cuckooHashing.keys()) {\n StdOut.print(key + \" \");\n }\n\n StdOut.println();\n\n for (int key = 1; key < 1000000; key++) {\n cuckooHashing.put(key, key);\n }\n for (int key = 1; key < 1000000; key++) {\n cuckooHashing.delete(key);\n }\n\n for (int key = 1; key < 1500000; key++) {\n int randomKey = StdRandom.uniform(Integer.MAX_VALUE);\n cuckooHashing.put(randomKey, randomKey);\n }\n }\n}\n", "support_files": [], "metadata": {"number": "3.4.31", "chapter": 3, "chapter_title": "Searching", "section": 3.4, "section_title": "Hash Tables", "type": "Creative Problem", "code_execution": false}} {"question": "Hash attack. Find 2^N strings, each of length 2^N, that have the same hashCode() value, supposing that the hashCode() implementation for String is the following:\npublic int hashCode() { \n int hash = 0;\n for (int i = 0; i < length(); i ++)\n hash = (hash * 31) + charAt(i);\n return hash; \n} \nStrong hint: Aa and BB have the same value.", "answer": "The two strings `\"Aa\"` and `\"BB\"` have the same Java `String.hashCode()` value and the same length. Therefore any concatenation of equal-length blocks chosen from `{ \"Aa\", \"BB\" }` also has the same hash as any other concatenation with the same number of blocks.\n\nTo get at least `2^N` strings of length exactly `2^N`, use `m = 2^(N-1)` two-character blocks. This produces `2^m = 2^(2^(N-1))` colliding strings, each of length `2m = 2^N`; choose any `2^N` of them.\n\n```java\nprivate static void generate(int blocks, String prefix, List result, int limit) {\n if (result.size() == limit) return;\n if (blocks == 0) {\n result.add(prefix);\n return;\n }\n generate(blocks - 1, prefix + \"Aa\", result, limit);\n generate(blocks - 1, prefix + \"BB\", result, limit);\n}\n```", "support_files": [], "metadata": {"number": "3.4.32", "chapter": 3, "chapter_title": "Searching", "section": 3.4, "section_title": "Hash Tables", "type": "Creative Problem", "code_execution": false}} {"question": "Bad hash function. Consider the following hashCode() implementation for String, which was used in early versions of Java:\npublic int hashCode() { \n int hash = 0;\n int skip = Math.max(1, length()/8);\n for (int i = 0; i < length(); i += skip)\n hash = (hash * 37) + charAt(i);\n return hash; \n} \nExplain why you think the designers chose this implementation and then why you think it was abandoned in favor of the one in the previous exercise.", "answer": "3.4.33 - Bad hash function\n\nI think the designers chose this implementation because it multiplies the hash value by a prime number several times. By skipping max(1, 1/8) chars in every iteration, it guarantees that the multiplication will only happen a constant number of time, improving the performance of the hash function.\nI think it was abandoned because by skipping many characters on long strings, many similar strings (that differ by only a few characters) had the same hash code, causing several hash collisions.\n", "support_files": [], "metadata": {"number": "3.4.33", "chapter": 3, "chapter_title": "Searching", "section": 3.4, "section_title": "Hash Tables", "type": "Creative Problem", "code_execution": false}} {"question": "Develop classes HashSETint and HashSETdouble for maintaining sets of keys of primitive int and double types, respectively. (Eliminate code involving values in your solution to Exercise 3.5.4.)", "answer": "package chapter3.section5;\n\nimport edu.princeton.cs.algs4.Queue;\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.Arrays;\n\n/**\n * Created by Rene Argento on 03/08/17.\n */\n@SuppressWarnings(\"unchecked\")\npublic class Exercise6 {\n\n private class HashSETint {\n\n private int keysSize;\n private int size;\n private int[] keys;\n\n public final static int EMPTY_KEY = Integer.MIN_VALUE;\n\n //The largest prime <= 2^i for i = 1 to 31\n //Used to distribute keys uniformly in the hash table after resizes\n //PRIMES[n] = 2^k - Ak where k is the power of 2 and Ak is the value to subtract to reach the previous prime number\n private final int[] PRIMES = {\n 1, 1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381,\n 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301,\n 8388593, 16777213, 33554393, 67108859, 134217689, 268435399,\n 536870909, 1073741789, 2147483647\n };\n\n //The lg of the hash table size\n //Used in combination with PRIMES[] to distribute keys uniformly in the hash function after resizes\n private int lgM;\n\n private HashSETint(int size) {\n this.size = size;\n keys = new int[size];\n\n for (int i = 0; i < size; i++) {\n keys[i] = EMPTY_KEY;\n }\n\n lgM = (int) (Math.log(size) / Math.log(2));\n }\n\n public int size() {\n return keysSize;\n }\n\n public boolean isEmpty() {\n return keysSize == 0;\n }\n\n private int hash(int key) {\n int hash = Integer.valueOf(key).hashCode() & 0x7fffffff;\n\n if (lgM < 26) {\n hash = hash % PRIMES[lgM + 5];\n }\n\n return hash % size;\n }\n\n private double getLoadFactor() {\n return keysSize / (double) size;\n }\n\n private void resize(int newSize) {\n HashSETint tempSet = new HashSETint(newSize);\n\n for (int i = 0; i < size; i++) {\n if (keys[i] != EMPTY_KEY) {\n tempSet.add(keys[i]);\n }\n }\n\n keys = tempSet.keys;\n size = tempSet.size;\n }\n\n public boolean contains(int key) {\n if (key == EMPTY_KEY) {\n throw new IllegalArgumentException(\"Invalid key\");\n }\n\n for (int tableIndex = hash(key); keys[tableIndex] != EMPTY_KEY; tableIndex = (tableIndex + 1) % size) {\n if (keys[tableIndex] == key) {\n return true;\n }\n }\n\n return false;\n }\n\n public void add(int key) {\n if (key == EMPTY_KEY) {\n throw new IllegalArgumentException(\"Invalid key\");\n }\n\n if (keysSize >= size / (double) 2) {\n resize(size * 2);\n lgM++;\n }\n\n int tableIndex;\n for (tableIndex = hash(key); keys[tableIndex] != EMPTY_KEY; tableIndex = (tableIndex + 1) % size) {\n if (keys[tableIndex] == key) {\n keys[tableIndex] = key;\n return;\n }\n }\n\n keys[tableIndex] = key;\n keysSize++;\n }\n\n public void delete(int key) {\n if (key == EMPTY_KEY) {\n throw new IllegalArgumentException(\"Invalid key\");\n }\n\n if (!contains(key)) {\n return;\n }\n\n int tableIndex = hash(key);\n while (keys[tableIndex] != key) {\n tableIndex = (tableIndex + 1) % size;\n }\n\n keys[tableIndex] = EMPTY_KEY;\n keysSize--;\n\n tableIndex = (tableIndex + 1) % size;\n\n while (keys[tableIndex] != EMPTY_KEY) {\n int keyToRedo = keys[tableIndex];\n\n keys[tableIndex] = EMPTY_KEY;\n keysSize--;\n\n add(keyToRedo);\n tableIndex = (tableIndex + 1) % size;\n }\n\n if (keysSize > 1 && keysSize <= size / (double) 8) {\n resize(size / 2);\n lgM--;\n }\n }\n\n public int[] keys() {\n Queue keySet = new Queue<>();\n\n for (int key : keys) {\n if (key != EMPTY_KEY) {\n keySet.enqueue(key);\n }\n }\n\n int[] keys = new int[keySet.size()];\n for (int i = 0; i < keys.length; i++) {\n keys[i] = keySet.dequeue();\n }\n\n Arrays.sort(keys);\n\n return keys;\n }\n\n @Override\n public String toString() {\n if (isEmpty()) {\n return \"{ }\";\n }\n\n StringBuilder stringBuilder = new StringBuilder(\"{\");\n\n boolean isFirstKey = true;\n for (int key : keys()) {\n if (isFirstKey) {\n isFirstKey = false;\n } else {\n stringBuilder.append(\",\");\n }\n\n stringBuilder.append(\" \").append(key);\n }\n\n stringBuilder.append(\" }\");\n return stringBuilder.toString();\n }\n }\n\n private class HashSETdouble {\n private int keysSize;\n private int size;\n private double[] keys;\n\n public final static double EMPTY_VALUE = Double.MIN_VALUE;\n\n //The largest prime <= 2^i for i = 1 to 31\n //Used to distribute keys uniformly in the hash table after resizes\n //PRIMES[n] = 2^k - Ak where k is the power of 2 and Ak is the value to subtract to reach the previous prime number\n private final int[] PRIMES = {\n 1, 1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381,\n 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301,\n 8388593, 16777213, 33554393, 67108859, 134217689, 268435399,\n 536870909, 1073741789, 2147483647\n };\n\n //The lg of the hash table size\n //Used in combination with PRIMES[] to distribute keys uniformly in the hash function after resizes\n private int lgM;\n\n private HashSETdouble(int size) {\n this.size = size;\n keys = new double[size];\n\n for (int i = 0; i < size; i++) {\n keys[i] = EMPTY_VALUE;\n }\n\n lgM = (int) (Math.log(size) / Math.log(2));\n }\n\n public int size() {\n return keysSize;\n }\n\n public boolean isEmpty() {\n return keysSize == 0;\n }\n\n private int hash(double key) {\n int hash = Double.valueOf(key).hashCode() & 0x7fffffff;\n\n if (lgM < 26) {\n hash = hash % PRIMES[lgM + 5];\n }\n\n return hash % size;\n }\n\n private double getLoadFactor() {\n return keysSize / (double) size;\n }\n\n private void resize(int newSize) {\n HashSETdouble tempSet = new HashSETdouble(newSize);\n\n for (int i = 0; i < size; i++) {\n if (keys[i] != EMPTY_VALUE) {\n tempSet.add(keys[i]);\n }\n }\n\n keys = tempSet.keys;\n size = tempSet.size;\n }\n\n public boolean contains(double key) {\n if (key == EMPTY_VALUE) {\n throw new IllegalArgumentException(\"Invalid key\");\n }\n\n for (int tableIndex = hash(key); keys[tableIndex] != EMPTY_VALUE; tableIndex = (tableIndex + 1) % size) {\n if (keys[tableIndex] == key) {\n return true;\n }\n }\n\n return false;\n }\n\n public void add(double key) {\n if (key == EMPTY_VALUE) {\n throw new IllegalArgumentException(\"Invalid key\");\n }\n\n if (keysSize >= size / (double) 2) {\n resize(size * 2);\n lgM++;\n }\n\n int tableIndex;\n for (tableIndex = hash(key); keys[tableIndex] != EMPTY_VALUE; tableIndex = (tableIndex + 1) % size) {\n if (keys[tableIndex] == key) {\n keys[tableIndex] = key;\n return;\n }\n }\n\n keys[tableIndex] = key;\n keysSize++;\n }\n\n public void delete(double key) {\n if (key == EMPTY_VALUE) {\n throw new IllegalArgumentException(\"Invalid key\");\n }\n\n if (!contains(key)) {\n return;\n }\n\n int tableIndex = hash(key);\n while (keys[tableIndex] != key) {\n tableIndex = (tableIndex + 1) % size;\n }\n\n keys[tableIndex] = EMPTY_VALUE;\n keysSize--;\n\n tableIndex = (tableIndex + 1) % size;\n\n while (keys[tableIndex] != EMPTY_VALUE) {\n double keyToRedo = keys[tableIndex];\n\n keys[tableIndex] = EMPTY_VALUE;\n keysSize--;\n\n add(keyToRedo);\n tableIndex = (tableIndex + 1) % size;\n }\n\n if (keysSize > 1 && keysSize <= size / (double) 8) {\n resize(size / 2);\n lgM--;\n }\n }\n\n public double[] keys() {\n Queue keySet = new Queue<>();\n\n for (double key : keys) {\n if (key != EMPTY_VALUE) {\n keySet.enqueue(key);\n }\n }\n\n double[] keys = new double[keySet.size()];\n for (int i = 0; i < keys.length; i++) {\n keys[i] = keySet.dequeue();\n }\n\n Arrays.sort(keys);\n\n return keys;\n }\n\n @Override\n public String toString() {\n if (isEmpty()) {\n return \"{ }\";\n }\n\n StringBuilder stringBuilder = new StringBuilder(\"{\");\n\n boolean isFirstKey = true;\n for (double key : keys()) {\n if (isFirstKey) {\n isFirstKey = false;\n } else {\n stringBuilder.append(\",\");\n }\n\n stringBuilder.append(\" \").append(key);\n }\n\n stringBuilder.append(\" }\");\n return stringBuilder.toString();\n }\n }\n\n public static void main(String[] args) {\n Exercise6 exercise6 = new Exercise6();\n exercise6.testHashSTint();\n exercise6.testHashSTdouble();\n }\n\n private void testHashSTint() {\n StdOut.println(\"HashSTint test\");\n HashSETint hashSTint = new HashSETint(5);\n\n hashSTint.add(5);\n hashSTint.add(1);\n hashSTint.add(9);\n hashSTint.add(2);\n hashSTint.add(0);\n hashSTint.add(99);\n hashSTint.add(-1);\n hashSTint.add(-2);\n hashSTint.add(3);\n hashSTint.add(-5);\n\n StdOut.println(\"Keys() test\");\n\n for (Integer key : hashSTint.keys()) {\n StdOut.print(key + \" \");\n }\n StdOut.println(\"\\nExpected: -5 -2 -1 0 1 2 3 5 9 99\");\n\n StdOut.println(\"\\ntoString() test: \" + hashSTint);\n\n StdOut.println(\"\\nContains 0: \" + hashSTint.contains(0) + \" Expected: true\");\n StdOut.println(\"Contains 100: \" + hashSTint.contains(100) + \" Expected: false\");\n\n //Test delete()\n StdOut.println(\"\\nDelete key 2\");\n hashSTint.delete(2);\n StdOut.println(hashSTint);\n\n StdOut.println(\"\\nDelete key 99\");\n hashSTint.delete(99);\n StdOut.println(hashSTint);\n\n StdOut.println(\"\\nDelete key -5\");\n hashSTint.delete(-5);\n StdOut.println(hashSTint);\n }\n\n private void testHashSTdouble() {\n StdOut.println(\"\\n\\nHashSTdouble test\");\n HashSETdouble hashSTdouble = new HashSETdouble(5);\n\n hashSTdouble.add(5.0);\n hashSTdouble.add(1.0);\n hashSTdouble.add(9.5);\n hashSTdouble.add(2.1);\n hashSTdouble.add(0);\n hashSTdouble.add(99.999);\n hashSTdouble.add(-1.05);\n hashSTdouble.add(-2.20);\n hashSTdouble.add(3.0);\n hashSTdouble.add(-5.9);\n\n StdOut.println(\"Keys() test\");\n\n for (Double key : hashSTdouble.keys()) {\n StdOut.print(key + \" \");\n }\n StdOut.println(\"\\nExpected: -5.9 -2.2 -1.05 0.0 1.0 2.1 3.0 5.0 9.5 99.999\");\n\n StdOut.println(\"\\ntoString() test: \" + hashSTdouble);\n\n StdOut.println(\"\\nContains 0: \" + hashSTdouble.contains(0) + \" Expected: true\");\n StdOut.println(\"Contains 100: \" + hashSTdouble.contains(100) + \" Expected: false\");\n\n //Test delete()\n StdOut.println(\"\\nDelete key 2.1\");\n hashSTdouble.delete(2.1);\n StdOut.println(hashSTdouble);\n\n StdOut.println(\"\\nDelete key 99.999\");\n hashSTdouble.delete(99.999);\n StdOut.println(hashSTdouble);\n\n StdOut.println(\"\\nDelete key -5.9\");\n hashSTdouble.delete(-5.9);\n StdOut.println(hashSTdouble);\n }\n}\n", "support_files": [], "metadata": {"number": "3.5.6", "chapter": 3, "chapter_title": "Searching", "section": 3.5, "section_title": "Applications", "type": "Exercise", "code_execution": false}} {"question": "Develop classes SETint and SETdouble for maintaining ordered sets of keys of primitive int and double types, respectively. (Eliminate code involving values in your solution to Exercise 3.5.5.)", "answer": "package chapter3.section5;\n\nimport edu.princeton.cs.algs4.Queue;\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.NoSuchElementException;\n\n/**\n * Created by Rene Argento on 05/08/17.\n */\npublic class Exercise7 {\n\n private class SETint {\n private static final boolean RED = true;\n private static final boolean BLACK = false;\n\n public final static int EMPTY_KEY = Integer.MIN_VALUE;\n\n private class Node {\n int key;\n Node left, right;\n\n boolean color;\n int size;\n\n Node(int key, int size, boolean color) {\n this.key = key;\n\n this.size = size;\n this.color = color;\n }\n }\n\n private Node root;\n\n public int size() {\n return size(root);\n }\n\n private int size(Node node) {\n if (node == null) {\n return 0;\n }\n\n return node.size;\n }\n\n public boolean isEmpty() {\n return size(root) == 0;\n }\n\n private boolean isRed(Node node) {\n if (node == null) {\n return false;\n }\n\n return node.color == RED;\n }\n\n private Node rotateLeft(Node node) {\n if (node == null || node.right == null) {\n return node;\n }\n\n Node newRoot = node.right;\n\n node.right = newRoot.left;\n newRoot.left = node;\n\n newRoot.color = node.color;\n node.color = RED;\n\n newRoot.size = node.size;\n node.size = size(node.left) + 1 + size(node.right);\n\n return newRoot;\n }\n\n private Node rotateRight(Node node) {\n if (node == null || node.left == null) {\n return node;\n }\n\n Node newRoot = node.left;\n\n node.left = newRoot.right;\n newRoot.right = node;\n\n newRoot.color = node.color;\n node.color = RED;\n\n newRoot.size = node.size;\n node.size = size(node.left) + 1 + size(node.right);\n\n return newRoot;\n }\n\n private void flipColors(Node node) {\n if (node == null || node.left == null || node.right == null) {\n return;\n }\n\n // The root must have opposite color of its two children\n if ((isRed(node) && !isRed(node.left) && !isRed(node.right))\n || (!isRed(node) && isRed(node.left) && isRed(node.right))) {\n node.color = !node.color;\n node.left.color = !node.left.color;\n node.right.color = !node.right.color;\n }\n }\n\n public void add(int key) {\n if (key == EMPTY_KEY) {\n throw new IllegalArgumentException(\"Invalid key\");\n }\n\n root = add(root, key);\n root.color = BLACK;\n }\n\n private Node add(Node node, int key) {\n if (node == null) {\n return new Node(key, 1, RED);\n }\n\n if (key < node.key) {\n node.left = add(node.left, key);\n } else if (key > node.key) {\n node.right = add(node.right, key);\n } else {\n node.key = key;\n }\n\n if (isRed(node.right) && !isRed(node.left)) {\n node = rotateLeft(node);\n }\n if (isRed(node.left) && isRed(node.left.left)) {\n node = rotateRight(node);\n }\n if (isRed(node.left) && isRed(node.right)) {\n flipColors(node);\n }\n\n node.size = size(node.left) + 1 + size(node.right);\n return node;\n }\n\n public boolean contains(int key) {\n if (key == EMPTY_KEY) {\n throw new IllegalArgumentException(\"Invalid key\");\n }\n\n Node currentNode = root;\n while (currentNode != null) {\n if (key < currentNode.key) {\n currentNode = currentNode.left;\n } else if (key > currentNode.key) {\n currentNode = currentNode.right;\n } else {\n return true;\n }\n }\n\n return false;\n }\n\n public int min() {\n if (root == null) {\n throw new NoSuchElementException(\"Empty set\");\n }\n\n return min(root).key;\n }\n\n private Node min(Node node) {\n if (node.left == null) {\n return node;\n }\n\n return min(node.left);\n }\n\n public int max() {\n if (root == null) {\n throw new NoSuchElementException(\"Empty set\");\n }\n\n return max(root).key;\n }\n\n private Node max(Node node) {\n if (node.right == null) {\n return node;\n }\n\n return max(node.right);\n }\n\n // Returns the highest key in the set smaller than or equal to key.\n public int floor(int key) {\n Node node = floor(root, key);\n if (node == null) {\n return EMPTY_KEY;\n }\n\n return node.key;\n }\n\n private Node floor(Node node, int key) {\n if (node == null) {\n return null;\n }\n\n if (key == node.key) {\n return node;\n } else if (key < node.key) {\n return floor(node.left, key);\n } else {\n Node rightNode = floor(node.right, key);\n if (rightNode != null) {\n return rightNode;\n } else {\n return node;\n }\n }\n }\n\n // Returns the smallest key in the set greater than or equal to key.\n public int ceiling(int key) {\n Node node = ceiling(root, key);\n if (node == null) {\n return EMPTY_KEY;\n }\n\n return node.key;\n }\n\n private Node ceiling(Node node, int key) {\n if (node == null) {\n return null;\n }\n\n if (key == node.key) {\n return node;\n } else if (key > node.key) {\n return ceiling(node.right, key);\n } else {\n Node leftNode = ceiling(node.left, key);\n if (leftNode != null) {\n return leftNode;\n } else {\n return node;\n }\n }\n }\n\n public int select(int index) {\n if (index >= size()) {\n throw new IllegalArgumentException(\"Index is higher than set size\");\n }\n\n return select(root, index).key;\n }\n\n private Node select(Node node, int index) {\n int leftSubtreeSize = size(node.left);\n\n if (leftSubtreeSize == index) {\n return node;\n } else if (leftSubtreeSize > index) {\n return select(node.left, index);\n } else {\n return select(node.right, index - leftSubtreeSize - 1);\n }\n }\n\n public int rank(int key) {\n return rank(root, key);\n }\n\n private int rank(Node node, int key) {\n if (node == null) {\n return 0;\n }\n\n // Returns the number of keys less than node.key in the subtree rooted at node\n if (key < node.key) {\n return rank(node.left, key);\n } else if (key > node.key) {\n return size(node.left) + 1 + rank(node.right, key);\n } else {\n return size(node.left);\n }\n }\n\n public void deleteMin() {\n if (isEmpty()) {\n return;\n }\n\n if (!isRed(root.left) && !isRed(root.right)) {\n root.color = RED;\n }\n\n root = deleteMin(root);\n\n if (!isEmpty()) {\n root.color = BLACK;\n }\n }\n\n private Node deleteMin(Node node) {\n if (node.left == null) {\n return null;\n }\n\n if (!isRed(node.left) && !isRed(node.left.left)) {\n node = moveRedLeft(node);\n }\n\n node.left = deleteMin(node.left);\n return balance(node);\n }\n\n public void deleteMax() {\n if (isEmpty()) {\n return;\n }\n\n if (!isRed(root.left) && !isRed(root.right)) {\n root.color = RED;\n }\n\n root = deleteMax(root);\n\n if (!isEmpty()) {\n root.color = BLACK;\n }\n }\n\n private Node deleteMax(Node node) {\n if (isRed(node.left)) {\n node = rotateRight(node);\n }\n\n if (node.right == null) {\n return null;\n }\n\n if (!isRed(node.right) && !isRed(node.right.left)) {\n node = moveRedRight(node);\n }\n\n node.right = deleteMax(node.right);\n return balance(node);\n }\n\n public void delete(int key) {\n if (key == EMPTY_KEY) {\n throw new IllegalArgumentException(\"Invalid key\");\n }\n\n if (isEmpty() || !contains(key)) {\n return;\n }\n\n if (!isRed(root.left) && !isRed(root.right)) {\n root.color = RED;\n }\n\n root = delete(root, key);\n\n if (!isEmpty()) {\n root.color = BLACK;\n }\n }\n\n private Node delete(Node node, int key) {\n if (node == null) {\n return null;\n }\n\n if (key < node.key) {\n if (!isRed(node.left) && node.left != null && !isRed(node.left.left)) {\n node = moveRedLeft(node);\n }\n\n node.left = delete(node.left, key);\n } else {\n if (isRed(node.left)) {\n node = rotateRight(node);\n }\n\n if (key == node.key && node.right == null) {\n return null;\n }\n\n if (!isRed(node.right) && node.right != null && !isRed(node.right.left)) {\n node = moveRedRight(node);\n }\n\n if (key == node.key) {\n Node aux = min(node.right);\n node.key = aux.key;\n node.right = deleteMin(node.right);\n } else {\n node.right = delete(node.right, key);\n }\n }\n\n return balance(node);\n }\n\n private Node moveRedLeft(Node node) {\n // Assuming that node is red and both node.left and node.left.left are black,\n // make node.left or one of its children red\n flipColors(node);\n\n if (node.right != null && isRed(node.right.left)) {\n node.right = rotateRight(node.right);\n node = rotateLeft(node);\n flipColors(node);\n }\n\n return node;\n }\n\n private Node moveRedRight(Node node) {\n // Assuming that node is red and both node.right and node.right.left are black,\n // make node.right or one of its children red\n flipColors(node);\n\n if (node.left != null && isRed(node.left.left)) {\n node = rotateRight(node);\n flipColors(node);\n }\n\n return node;\n }\n\n private Node balance(Node node) {\n if (node == null) {\n return null;\n }\n\n if (isRed(node.right)) {\n node = rotateLeft(node);\n }\n\n if (isRed(node.left) && isRed(node.left.left)) {\n node = rotateRight(node);\n }\n\n if (isRed(node.left) && isRed(node.right)) {\n flipColors(node);\n }\n\n node.size = size(node.left) + 1 + size(node.right);\n\n return node;\n }\n\n public int[] keys() {\n return keys(min(), max());\n }\n\n public int[] keys(int low, int high) {\n if (low == EMPTY_KEY) {\n throw new IllegalArgumentException(\"Invalid key on the first argument\");\n }\n if (high == EMPTY_KEY) {\n throw new IllegalArgumentException(\"Invalid key on the second argument\");\n }\n\n Queue queue = new Queue<>();\n keys(root, queue, low, high);\n\n int[] keys = new int[queue.size()];\n for (int i = 0; i < keys.length; i++) {\n keys[i] = queue.dequeue();\n }\n\n return keys;\n }\n\n private void keys(Node node, Queue queue, int low, int high) {\n if (node == null) {\n return;\n }\n\n int compareLow;\n\n if (low < node.key) {\n compareLow = -1;\n } else if (low > node.key) {\n compareLow = 1;\n } else {\n compareLow = 0;\n }\n\n int compareHigh;\n\n if (high < node.key) {\n compareHigh = -1;\n } else if (high > node.key) {\n compareHigh = 1;\n } else {\n compareHigh = 0;\n }\n\n if (compareLow < 0) {\n keys(node.left, queue, low, high);\n }\n\n if (compareLow <= 0 && compareHigh >= 0) {\n queue.enqueue(node.key);\n }\n\n if (compareHigh > 0) {\n keys(node.right, queue, low, high);\n }\n }\n\n public int size(int low, int high) {\n if (low == EMPTY_KEY) {\n throw new IllegalArgumentException(\"Invalid key on the first argument\");\n }\n if (high == EMPTY_KEY) {\n throw new IllegalArgumentException(\"Invalid key on the second argument\");\n }\n\n if (low > high) {\n return 0;\n }\n\n if (contains(high)) {\n return rank(high) - rank(low) + 1;\n } else {\n return rank(high) - rank(low);\n }\n }\n\n }\n\n private class SETdouble {\n private static final boolean RED = true;\n private static final boolean BLACK = false;\n\n public final static double EMPTY_KEY = Double.MIN_VALUE;\n\n private class Node {\n double key;\n Node left, right;\n\n boolean color;\n int size;\n\n Node(double key, int size, boolean color) {\n this.key = key;\n\n this.size = size;\n this.color = color;\n }\n }\n\n private Node root;\n\n public int size() {\n return size(root);\n }\n\n private int size(Node node) {\n if (node == null) {\n return 0;\n }\n\n return node.size;\n }\n\n public boolean isEmpty() {\n return size(root) == 0;\n }\n\n private boolean isRed(Node node) {\n if (node == null) {\n return false;\n }\n\n return node.color == RED;\n }\n\n private Node rotateLeft(Node node) {\n if (node == null || node.right == null) {\n return node;\n }\n\n Node newRoot = node.right;\n\n node.right = newRoot.left;\n newRoot.left = node;\n\n newRoot.color = node.color;\n node.color = RED;\n\n newRoot.size = node.size;\n node.size = size(node.left) + 1 + size(node.right);\n\n return newRoot;\n }\n\n private Node rotateRight(Node node) {\n if (node == null || node.left == null) {\n return node;\n }\n\n Node newRoot = node.left;\n\n node.left = newRoot.right;\n newRoot.right = node;\n\n newRoot.color = node.color;\n node.color = RED;\n\n newRoot.size = node.size;\n node.size = size(node.left) + 1 + size(node.right);\n\n return newRoot;\n }\n\n private void flipColors(Node node) {\n if (node == null || node.left == null || node.right == null) {\n return;\n }\n\n // The root must have opposite color of its two children\n if ((isRed(node) && !isRed(node.left) && !isRed(node.right))\n || (!isRed(node) && isRed(node.left) && isRed(node.right))) {\n node.color = !node.color;\n node.left.color = !node.left.color;\n node.right.color = !node.right.color;\n }\n }\n\n public void add(double key) {\n if (key == EMPTY_KEY) {\n throw new IllegalArgumentException(\"Invalid key\");\n }\n\n root = add(root, key);\n root.color = BLACK;\n }\n\n private Node add(Node node, double key) {\n if (node == null) {\n return new Node(key, 1, RED);\n }\n\n if (key < node.key) {\n node.left = add(node.left, key);\n } else if (key > node.key) {\n node.right = add(node.right, key);\n } else {\n node.key = key;\n }\n\n if (isRed(node.right) && !isRed(node.left)) {\n node = rotateLeft(node);\n }\n if (isRed(node.left) && isRed(node.left.left)) {\n node = rotateRight(node);\n }\n if (isRed(node.left) && isRed(node.right)) {\n flipColors(node);\n }\n\n node.size = size(node.left) + 1 + size(node.right);\n return node;\n }\n\n public boolean contains(double key) {\n if (key == EMPTY_KEY) {\n throw new IllegalArgumentException(\"Invalid key\");\n }\n\n Node currentNode = root;\n while (currentNode != null) {\n if (key < currentNode.key) {\n currentNode = currentNode.left;\n } else if (key > currentNode.key) {\n currentNode = currentNode.right;\n } else {\n return true;\n }\n }\n\n return false;\n }\n\n public double min() {\n if (root == null) {\n throw new NoSuchElementException(\"Empty set\");\n }\n\n return min(root).key;\n }\n\n private Node min(Node node) {\n if (node.left == null) {\n return node;\n }\n\n return min(node.left);\n }\n\n public double max() {\n if (root == null) {\n throw new NoSuchElementException(\"Empty set\");\n }\n\n return max(root).key;\n }\n\n private Node max(Node node) {\n if (node.right == null) {\n return node;\n }\n\n return max(node.right);\n }\n\n // Returns the highest key in the set smaller than or equal to key.\n public double floor(double key) {\n Node node = floor(root, key);\n if (node == null) {\n return EMPTY_KEY;\n }\n return node.key;\n }\n\n private Node floor(Node node, double key) {\n if (node == null) {\n return null;\n }\n\n if (key == node.key) {\n return node;\n } else if (key < node.key) {\n return floor(node.left, key);\n } else {\n Node rightNode = floor(node.right, key);\n if (rightNode != null) {\n return rightNode;\n } else {\n return node;\n }\n }\n }\n\n // Returns the smallest key in the set greater than or equal to key.\n public double ceiling(double key) {\n Node node = ceiling(root, key);\n if (node == null) {\n return EMPTY_KEY;\n }\n return node.key;\n }\n\n private Node ceiling(Node node, double key) {\n if (node == null) {\n return null;\n }\n\n if (key == node.key) {\n return node;\n } else if (key > node.key) {\n return ceiling(node.right, key);\n } else {\n Node leftNode = ceiling(node.left, key);\n if (leftNode != null) {\n return leftNode;\n } else {\n return node;\n }\n }\n }\n\n public double select(int index) {\n if (index >= size()) {\n throw new IllegalArgumentException(\"Index is higher than set size\");\n }\n\n return select(root, index).key;\n }\n\n private Node select(Node node, int index) {\n int leftSubtreeSize = size(node.left);\n\n if (leftSubtreeSize == index) {\n return node;\n } else if (leftSubtreeSize > index) {\n return select(node.left, index);\n } else {\n return select(node.right, index - leftSubtreeSize - 1);\n }\n }\n\n public int rank(double key) {\n return rank(root, key);\n }\n\n private int rank(Node node, double key) {\n if (node == null) {\n return 0;\n }\n\n // Returns the number of keys less than node.key in the subtree rooted at node\n if (key < node.key) {\n return rank(node.left, key);\n } else if (key > node.key) {\n return size(node.left) + 1 + rank(node.right, key);\n } else {\n return size(node.left);\n }\n }\n\n public void deleteMin() {\n if (isEmpty()) {\n return;\n }\n\n if (!isRed(root.left) && !isRed(root.right)) {\n root.color = RED;\n }\n\n root = deleteMin(root);\n\n if (!isEmpty()) {\n root.color = BLACK;\n }\n }\n\n private Node deleteMin(Node node) {\n if (node.left == null) {\n return null;\n }\n\n if (!isRed(node.left) && !isRed(node.left.left)) {\n node = moveRedLeft(node);\n }\n\n node.left = deleteMin(node.left);\n return balance(node);\n }\n\n public void deleteMax() {\n if (isEmpty()) {\n return;\n }\n\n if (!isRed(root.left) && !isRed(root.right)) {\n root.color = RED;\n }\n\n root = deleteMax(root);\n\n if (!isEmpty()) {\n root.color = BLACK;\n }\n }\n\n private Node deleteMax(Node node) {\n if (isRed(node.left)) {\n node = rotateRight(node);\n }\n\n if (node.right == null) {\n return null;\n }\n\n if (!isRed(node.right) && !isRed(node.right.left)) {\n node = moveRedRight(node);\n }\n\n node.right = deleteMax(node.right);\n return balance(node);\n }\n\n public void delete(double key) {\n if (key == EMPTY_KEY) {\n throw new IllegalArgumentException(\"Invalid key\");\n }\n\n if (isEmpty() || !contains(key)) {\n return;\n }\n\n if (!isRed(root.left) && !isRed(root.right)) {\n root.color = RED;\n }\n\n root = delete(root, key);\n\n if (!isEmpty()) {\n root.color = BLACK;\n }\n }\n\n private Node delete(Node node, double key) {\n if (node == null) {\n return null;\n }\n\n if (key < node.key) {\n if (!isRed(node.left) && node.left != null && !isRed(node.left.left)) {\n node = moveRedLeft(node);\n }\n\n node.left = delete(node.left, key);\n } else {\n if (isRed(node.left)) {\n node = rotateRight(node);\n }\n\n if (key == node.key && node.right == null) {\n return null;\n }\n\n if (!isRed(node.right) && node.right != null && !isRed(node.right.left)) {\n node = moveRedRight(node);\n }\n\n if (key == node.key) {\n Node aux = min(node.right);\n node.key = aux.key;\n node.right = deleteMin(node.right);\n } else {\n node.right = delete(node.right, key);\n }\n }\n\n return balance(node);\n }\n\n private Node moveRedLeft(Node node) {\n // Assuming that node is red and both node.left and node.left.left are black,\n // make node.left or one of its children red\n flipColors(node);\n\n if (node.right != null && isRed(node.right.left)) {\n node.right = rotateRight(node.right);\n node = rotateLeft(node);\n flipColors(node);\n }\n\n return node;\n }\n\n private Node moveRedRight(Node node) {\n // Assuming that node is red and both node.right and node.right.left are black,\n // make node.right or one of its children red\n flipColors(node);\n\n if (node.left != null && isRed(node.left.left)) {\n node = rotateRight(node);\n flipColors(node);\n }\n\n return node;\n }\n\n private Node balance(Node node) {\n if (node == null) {\n return null;\n }\n\n if (isRed(node.right)) {\n node = rotateLeft(node);\n }\n\n if (isRed(node.left) && isRed(node.left.left)) {\n node = rotateRight(node);\n }\n\n if (isRed(node.left) && isRed(node.right)) {\n flipColors(node);\n }\n\n node.size = size(node.left) + 1 + size(node.right);\n\n return node;\n }\n\n public double[] keys() {\n return keys(min(), max());\n }\n\n public double[] keys(double low, double high) {\n if (low == EMPTY_KEY) {\n throw new IllegalArgumentException(\"Invalid key on the first argument\");\n }\n if (high == EMPTY_KEY) {\n throw new IllegalArgumentException(\"Invalid key on the second argument\");\n }\n\n Queue queue = new Queue<>();\n keys(root, queue, low, high);\n\n double[] keys = new double[queue.size()];\n for (int i = 0; i < keys.length; i++) {\n keys[i] = queue.dequeue();\n }\n return keys;\n }\n\n private void keys(Node node, Queue queue, double low, double high) {\n if (node == null) {\n return;\n }\n\n int compareLow;\n\n if (low < node.key) {\n compareLow = -1;\n } else if (low > node.key) {\n compareLow = 1;\n } else {\n compareLow = 0;\n }\n\n int compareHigh;\n\n if (high < node.key) {\n compareHigh = -1;\n } else if (high > node.key) {\n compareHigh = 1;\n } else {\n compareHigh = 0;\n }\n\n if (compareLow < 0) {\n keys(node.left, queue, low, high);\n }\n\n if (compareLow <= 0 && compareHigh >= 0) {\n queue.enqueue(node.key);\n }\n\n if (compareHigh > 0) {\n keys(node.right, queue, low, high);\n }\n }\n\n public int size(double low, double high) {\n if (low == EMPTY_KEY) {\n throw new IllegalArgumentException(\"Invalid key on the first argument\");\n }\n if (high == EMPTY_KEY) {\n throw new IllegalArgumentException(\"Invalid key on the second argument\");\n }\n\n if (low > high) {\n return 0;\n }\n\n if (contains(high)) {\n return rank(high) - rank(low) + 1;\n } else {\n return rank(high) - rank(low);\n }\n }\n }\n\n public static void main(String[] args) {\n Exercise7 exercise7 = new Exercise7();\n exercise7.testSETint();\n exercise7.testSETdouble();\n }\n\n private void testSETint() {\n StdOut.println(\"SETint test\");\n\n SETint setInt = new SETint();\n\n setInt.add(5);\n setInt.add(1);\n setInt.add(9);\n setInt.add(2);\n setInt.add(0);\n setInt.add(99);\n setInt.add(-1);\n setInt.add(-2);\n setInt.add(3);\n setInt.add(-5);\n\n StdOut.println(\"\\nKeys() test\");\n\n for (Integer key : setInt.keys()) {\n StdOut.print(key + \" \");\n }\n StdOut.println(\"\\nExpected: -5 -2 -1 0 1 2 3 5 9 99\");\n\n // Test min()\n StdOut.println(\"\\nMin key: \" + setInt.min() + \" Expected: -5\");\n\n // Test max()\n StdOut.println(\"Max key: \" + setInt.max() + \" Expected: 99\");\n\n // Test floor()\n StdOut.println(\"Floor of 5: \" + setInt.floor(5) + \" Expected: 5\");\n StdOut.println(\"Floor of 15: \" + setInt.floor(15) + \" Expected: 9\");\n\n // Test ceiling()\n StdOut.println(\"Ceiling of 5: \" + setInt.ceiling(5) + \" Expected: 5\");\n StdOut.println(\"Ceiling of 15: \" + setInt.ceiling(15) + \" Expected: 99\");\n\n // Test select()\n StdOut.println(\"Select key of rank 4: \" + setInt.select(4) + \" Expected: 1\");\n\n // Test rank()\n StdOut.println(\"Rank of key 9: \" + setInt.rank(9) + \" Expected: 8\");\n StdOut.println(\"Rank of key 10: \" + setInt.rank(10) + \" Expected: 9\");\n\n // Test delete()\n StdOut.println(\"\\nDelete key 2\");\n setInt.delete(2);\n\n for (Integer key : setInt.keys()) {\n StdOut.print(key + \" \");\n }\n\n // Test deleteMin()\n StdOut.println(\"\\n\\nDelete min (key -5)\");\n setInt.deleteMin();\n\n for (Integer key : setInt.keys()) {\n StdOut.print(key + \" \");\n }\n\n // Test deleteMax()\n StdOut.println(\"\\n\\nDelete max (key 99)\");\n setInt.deleteMax();\n\n for (Integer key : setInt.keys()) {\n StdOut.print(key + \" \");\n }\n\n // Test keys() with range\n StdOut.println(\"\\n\\nKeys in range [2, 10]\");\n for (Integer key : setInt.keys(2, 10)) {\n StdOut.print(key + \" \");\n }\n\n StdOut.println(\"\\n\\nKeys in range [-4, -1]\");\n for (Integer key : setInt.keys(-4, -1)) {\n StdOut.print(key + \" \");\n }\n\n // Delete all\n StdOut.println(\"\\n\\nDelete all\");\n while (setInt.size() > 0) {\n for (Integer key : setInt.keys()) {\n StdOut.print(key + \" \");\n }\n // setInt.delete(setInt.select(0));\n setInt.delete(setInt.select(setInt.size() - 1));\n StdOut.println();\n }\n }\n\n private void testSETdouble() {\n StdOut.println(\"\\nSETdouble test\");\n\n SETdouble setDouble = new SETdouble();\n\n setDouble.add(5.0);\n setDouble.add(1.0);\n setDouble.add(9.5);\n setDouble.add(2.1);\n setDouble.add(0);\n setDouble.add(99.999);\n setDouble.add(-1.05);\n setDouble.add(-2.20);\n setDouble.add(3.0);\n setDouble.add(-5.9);\n\n StdOut.println(\"\\nKeys() test\");\n\n for (Double key : setDouble.keys()) {\n StdOut.print(key + \" \");\n }\n StdOut.println(\"\\nExpected: -5.9 -2.2 -1.05 0.0 1.0 2.1 3.0 5.0 9.5 99.999\");\n\n // Test min()\n StdOut.println(\"\\nMin key: \" + setDouble.min() + \" Expected: -5.9\");\n\n // Test max()\n StdOut.println(\"Max key: \" + setDouble.max() + \" Expected: 99.999\");\n\n // Test floor()\n StdOut.println(\"Floor of 5.0: \" + setDouble.floor(5.0) + \" Expected: 5.0\");\n StdOut.println(\"Floor of 15.0: \" + setDouble.floor(15.0) + \" Expected: 9.5\");\n\n // Test ceiling()\n StdOut.println(\"Ceiling of 5.0: \" + setDouble.ceiling(5.0) + \" Expected: 5.0\");\n StdOut.println(\"Ceiling of 15.0: \" + setDouble.ceiling(15.0) + \" Expected: 99.999\");\n\n // Test select()\n StdOut.println(\"Select key of rank 4: \" + setDouble.select(4) + \" Expected: 1.0\");\n\n // Test rank()\n StdOut.println(\"Rank of key 9: \" + setDouble.rank(9.5) + \" Expected: 8\");\n StdOut.println(\"Rank of key 10: \" + setDouble.rank(10.0) + \" Expected: 9\");\n\n // Test delete()\n StdOut.println(\"\\nDelete key 2.1\");\n setDouble.delete(2.1);\n\n for (Double key : setDouble.keys()) {\n StdOut.print(key + \" \");\n }\n\n // Test deleteMin()\n StdOut.println(\"\\n\\nDelete min (key -5.9)\");\n setDouble.deleteMin();\n\n for (Double key : setDouble.keys()) {\n StdOut.print(key + \" \");\n }\n\n // Test deleteMax()\n StdOut.println(\"\\n\\nDelete max (key 99.999)\");\n setDouble.deleteMax();\n\n for (Double key : setDouble.keys()) {\n StdOut.print(key + \" \");\n }\n\n // Test keys() with range\n StdOut.println(\"\\n\\nKeys in range [2.0, 10.0]\");\n for (Double key : setDouble.keys(2.0, 10.0)) {\n StdOut.print(key + \" \");\n }\n\n StdOut.println(\"\\n\\nKeys in range [-4.0, -1.0]\");\n for (Double key : setDouble.keys(-4.0, -1.0)) {\n StdOut.print(key + \" \");\n }\n\n // Delete all\n StdOut.println(\"\\n\\nDelete all\");\n while (setDouble.size() > 0) {\n for (Double key : setDouble.keys()) {\n StdOut.print(key + \" \");\n }\n // setDouble.delete(setDouble.select(0));\n setDouble.delete(setDouble.select(setDouble.size() - 1));\n StdOut.println();\n }\n }\n}\n", "support_files": [], "metadata": {"number": "3.5.7", "chapter": 3, "chapter_title": "Searching", "section": 3.5, "section_title": "Applications", "type": "Exercise", "code_execution": false}} {"question": "Modify LinearProbingHashST to keep duplicate keys in the table. Return any value associated with the given key for get(), and remove all items in the table that have keys equal to the given key for delete().", "answer": "package chapter3.section5;\n\nimport edu.princeton.cs.algs4.Queue;\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.Arrays;\n\n/**\n * Created by Rene Argento on 05/08/17.\n */\npublic class Exercise8 {\n\n @SuppressWarnings(\"unchecked\")\n private class LinearProbingHashTableDuplicateKeys {\n\n private int keysSize;\n private int size;\n\n private Key[] keys;\n private Value[] values;\n\n //The largest prime <= 2^i for i = 1 to 31\n //Used to distribute keys uniformly in the hash table after resizes\n //PRIMES[n] = 2^k - Ak where k is the power of 2 and Ak is the value to subtract to reach the previous prime number\n private final int[] PRIMES = {\n 1, 1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381,\n 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301,\n 8388593, 16777213, 33554393, 67108859, 134217689, 268435399,\n 536870909, 1073741789, 2147483647\n };\n\n //The lg of the hash table size\n //Used in combination with PRIMES[] to distribute keys uniformly in the hash function after resizes\n private int lgM;\n\n LinearProbingHashTableDuplicateKeys(int size) {\n this.size = size;\n keys = (Key[]) new Object[size];\n values = (Value[]) new Object[size];\n\n lgM = (int) (Math.log(size) / Math.log(2));\n }\n\n public int size() {\n return keysSize;\n }\n\n public boolean isEmpty() {\n return keysSize == 0;\n }\n\n private int hash(Key key) {\n int hash = key.hashCode() & 0x7fffffff;\n\n if (lgM < 26) {\n hash = hash % PRIMES[lgM + 5];\n }\n\n return hash % size;\n }\n\n private double getLoadFactor() {\n return keysSize / (double) size;\n }\n\n private void resize(int newSize) {\n LinearProbingHashTableDuplicateKeys tempHashTable = new LinearProbingHashTableDuplicateKeys<>(newSize);\n\n for (int i = 0; i < size; i++) {\n if (keys[i] != null) {\n tempHashTable.put(keys[i], values[i]);\n }\n }\n\n keys = tempHashTable.keys;\n values = tempHashTable.values;\n size = tempHashTable.size;\n }\n\n public boolean contains(Key key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Argument to contains() cannot be null\");\n }\n\n return get(key) != null;\n }\n\n public Value get(Key key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Argument to get() cannot be null\");\n }\n\n for (int tableIndex = hash(key); keys[tableIndex] != null; tableIndex = (tableIndex + 1) % size) {\n if (keys[tableIndex].equals(key)) {\n return values[tableIndex];\n }\n }\n\n return null;\n }\n\n public void put(Key key, Value value) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n if (value == null) {\n delete(key);\n return;\n }\n\n if (keysSize >= size / (double) 2) {\n resize(size * 2);\n lgM++;\n }\n\n int tableIndex = hash(key);\n while (keys[tableIndex] != null) {\n tableIndex = (tableIndex + 1) % size;\n }\n\n keys[tableIndex] = key;\n values[tableIndex] = value;\n\n keysSize++;\n }\n\n public void delete(Key key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Argument to delete() cannot be null\");\n }\n\n if (!contains(key)) {\n return;\n }\n\n int tableIndex = hash(key);\n while (!keys[tableIndex].equals(key)) {\n tableIndex = (tableIndex + 1) % size;\n }\n\n keys[tableIndex] = null;\n values[tableIndex] = null;\n keysSize--;\n\n tableIndex = (tableIndex + 1) % size;\n\n while (keys[tableIndex] != null) {\n Key keyToRedo = keys[tableIndex];\n Value valueToRedo = values[tableIndex];\n\n keys[tableIndex] = null;\n values[tableIndex] = null;\n keysSize--;\n\n if (!keyToRedo.equals(key)) {\n put(keyToRedo, valueToRedo);\n }\n\n tableIndex = (tableIndex + 1) % size;\n }\n\n if (keysSize > 1 && keysSize <= size / (double) 8) {\n resize(size / 2);\n lgM--;\n }\n }\n\n public Iterable keys() {\n Queue keySet = new Queue<>();\n\n for (Object key : keys) {\n if (key != null) {\n keySet.enqueue((Key) key);\n }\n }\n\n if (!keySet.isEmpty() && keySet.peek() instanceof Comparable) {\n Key[] keysToBeSorted = (Key[]) new Comparable[keySet.size()];\n for (int i = 0; i < keysToBeSorted.length; i++) {\n keysToBeSorted[i] = keySet.dequeue();\n }\n\n Arrays.sort(keysToBeSorted);\n\n for (Key key : keysToBeSorted) {\n keySet.enqueue(key);\n }\n }\n return keySet;\n }\n }\n\n public static void main(String[] args) {\n Exercise8 exercise8 = new Exercise8();\n LinearProbingHashTableDuplicateKeys linearProbingHashTableDuplicateKeys =\n exercise8.new LinearProbingHashTableDuplicateKeys<>(10);\n\n // Test put()\n linearProbingHashTableDuplicateKeys.put(0, 0);\n linearProbingHashTableDuplicateKeys.put(0, 1);\n linearProbingHashTableDuplicateKeys.put(0, 2);\n linearProbingHashTableDuplicateKeys.put(0, 3);\n\n linearProbingHashTableDuplicateKeys.put(5, 7);\n linearProbingHashTableDuplicateKeys.put(5, 8);\n\n linearProbingHashTableDuplicateKeys.put(8, 9);\n linearProbingHashTableDuplicateKeys.put(8, 10);\n\n linearProbingHashTableDuplicateKeys.put(20, 11);\n linearProbingHashTableDuplicateKeys.put(20, 12);\n linearProbingHashTableDuplicateKeys.put(20, 13);\n linearProbingHashTableDuplicateKeys.put(20, 14);\n\n // Test resize()\n linearProbingHashTableDuplicateKeys.put(21, 15);\n linearProbingHashTableDuplicateKeys.put(22, 16);\n linearProbingHashTableDuplicateKeys.put(23, 17);\n linearProbingHashTableDuplicateKeys.put(24, 18);\n\n for (Integer key : linearProbingHashTableDuplicateKeys.keys()) {\n StdOut.println(\"Key \" + key + \": \" + linearProbingHashTableDuplicateKeys.get(key));\n }\n\n StdOut.println(\"\\nExpected:\");\n StdOut.println(\"Key 0: 0\");\n StdOut.println(\"Key 0: 0\");\n StdOut.println(\"Key 0: 0\");\n StdOut.println(\"Key 0: 0\");\n StdOut.println(\"Key 5: 7\");\n StdOut.println(\"Key 5: 7\");\n StdOut.println(\"Key 8: 9\");\n StdOut.println(\"Key 8: 9\");\n StdOut.println(\"Key 20: 11\");\n StdOut.println(\"Key 20: 11\");\n StdOut.println(\"Key 20: 11\");\n StdOut.println(\"Key 20: 11\");\n StdOut.println(\"Key 21: 15\");\n StdOut.println(\"Key 22: 16\");\n StdOut.println(\"Key 23: 17\");\n StdOut.println(\"Key 24: 18\");\n\n // Test size()\n StdOut.println(\"Keys size: \" + linearProbingHashTableDuplicateKeys.size() + \" Expected: 16\");\n\n // Test contains()\n StdOut.println(\"\\nContains 8: \" + linearProbingHashTableDuplicateKeys.contains(8) + \" Expected: true\");\n StdOut.println(\"Contains 9: \" + linearProbingHashTableDuplicateKeys.contains(9) + \" Expected: false\");\n\n // Test delete\n StdOut.println(\"\\nDelete key 20\");\n linearProbingHashTableDuplicateKeys.delete(20);\n StdOut.println(\"Keys size: \" + linearProbingHashTableDuplicateKeys.size() + \" Expected: 12\");\n\n StdOut.println(\"\\nDelete key 5\");\n linearProbingHashTableDuplicateKeys.delete(5);\n StdOut.println(\"Keys size: \" + linearProbingHashTableDuplicateKeys.size() + \" Expected: 10\");\n }\n}\n", "support_files": [], "metadata": {"number": "3.5.8", "chapter": 3, "chapter_title": "Searching", "section": 3.5, "section_title": "Applications", "type": "Exercise", "code_execution": false}} {"question": "Modify BST to keep duplicate keys in the tree. Return any value associated with the given key for get(), and remove all nodes in the tree that have keys equal to the given key for delete().", "answer": "package chapter3.section5;\n\nimport edu.princeton.cs.algs4.Queue;\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.NoSuchElementException;\n\n/**\n * Created by Rene Argento on 05/08/17.\n */\npublic class Exercise9 {\n\n /**\n * This tree has the following property:\n *\n * Let x be a node in the binary search tree.\n * If y is a node in the left subtree of x, then y:key <= x:key.\n * If y is a node in the right subtree of x, then y:key > x:key.\n */\n private class BinarySearchTreeDuplicateKeys, Value> {\n\n private class Node {\n private Key key;\n private Value value;\n\n private Node left;\n private Node right;\n\n private int size; //# of nodes in subtree rooted here\n\n public Node(Key key, Value value, int size) {\n this.key = key;\n this.value = value;\n this.size = size;\n }\n }\n\n private Node root;\n\n public int size() {\n return size(root);\n }\n\n private int size(Node node) {\n if (node == null) {\n return 0;\n }\n\n return node.size;\n }\n\n public boolean isEmpty() {\n return size(root) == 0;\n }\n\n public Value get(Key key) {\n if (key == null) {\n return null;\n }\n\n return get(root, key);\n }\n\n private Value get(Node node, Key key) {\n if (node == null) {\n return null;\n }\n\n int compare = key.compareTo(node.key);\n if (compare < 0) {\n return get(node.left, key);\n } else if (compare > 0) {\n return get(node.right, key);\n } else {\n return node.value;\n }\n }\n\n public boolean contains(Key key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Argument to contains() cannot be null\");\n }\n return get(key) != null;\n }\n\n public void put(Key key, Value value) {\n if (key == null) {\n return;\n }\n\n if (value == null) {\n delete(key);\n return;\n }\n\n root = put(root, key, value);\n }\n\n private Node put(Node node, Key key, Value value) {\n if (node == null) {\n return new Node(key, value, 1);\n }\n\n int compare = key.compareTo(node.key);\n\n // If it is a duplicate key, put it on the left subtree\n if (compare <= 0) {\n node.left = put(node.left, key, value);\n } else if (compare > 0) {\n node.right = put(node.right, key, value);\n }\n\n node.size = size(node.left) + 1 + size(node.right);\n return node;\n }\n\n public Key min() {\n if (root == null) {\n throw new NoSuchElementException(\"Empty binary search tree\");\n }\n\n return min(root).key;\n }\n\n private Node min(Node node) {\n if (node.left == null) {\n return node;\n }\n\n return min(node.left);\n }\n\n public Key max() {\n if (root == null) {\n throw new NoSuchElementException(\"Empty binary search tree\");\n }\n\n return max(root).key;\n }\n\n private Node max(Node node) {\n if (node.right == null) {\n return node;\n }\n\n return max(node.right);\n }\n\n // Returns the highest key in the symbol table smaller than or equal to key.\n public Key floor(Key key) {\n Node node = floor(root, key);\n if (node == null) {\n return null;\n }\n\n return node.key;\n }\n\n private Node floor(Node node, Key key) {\n if (node == null) {\n return null;\n }\n\n int compare = key.compareTo(node.key);\n\n if (compare == 0) {\n return node;\n } else if (compare < 0) {\n return floor(node.left, key);\n } else {\n Node rightNode = floor(node.right, key);\n if (rightNode != null) {\n return rightNode;\n } else {\n return node;\n }\n }\n }\n\n // Returns the smallest key in the symbol table greater than or equal to key.\n public Key ceiling(Key key) {\n Node node = ceiling(root, key);\n if (node == null) {\n return null;\n }\n\n return node.key;\n }\n\n private Node ceiling(Node node, Key key) {\n if (node == null) {\n return null;\n }\n\n int compare = key.compareTo(node.key);\n\n if (compare == 0) {\n return node;\n } else if (compare > 0) {\n return ceiling(node.right, key);\n } else {\n Node leftNode = ceiling(node.left, key);\n if (leftNode != null) {\n return leftNode;\n } else {\n return node;\n }\n }\n }\n\n public Key select(int index) {\n if (index >= size()) {\n throw new IllegalArgumentException(\"Index is higher than tree size\");\n }\n\n return select(root, index).key;\n }\n\n private Node select(Node node, int index) {\n int leftSubtreeSize = size(node.left);\n\n if (leftSubtreeSize == index) {\n return node;\n } else if (leftSubtreeSize > index) {\n return select(node.left, index);\n } else {\n return select(node.right, index - leftSubtreeSize - 1);\n }\n }\n\n public int rankFirst(Key key) {\n return rankFirst(root, key);\n }\n\n private int rankFirst(Node node, Key key) {\n if (node == null) {\n return 0;\n }\n\n // Returns the number of keys less than node.key in the subtree rooted at node\n int compare = key.compareTo(node.key);\n if (compare < 0) {\n return rankFirst(node.left, key);\n } else if (compare > 0) {\n return size(node.left) + 1 + rankFirst(node.right, key);\n } else {\n boolean hasDuplicateOnLeftSubtree = false;\n\n if (node.left != null && max(node.left).key.compareTo(key) == 0) {\n hasDuplicateOnLeftSubtree = true;\n }\n\n if (hasDuplicateOnLeftSubtree) {\n return rankFirst(node.left, key);\n } else {\n return size(node.left);\n }\n }\n }\n\n public int rankLast(Key key) {\n return rankLast(root, key);\n }\n\n private int rankLast(Node node, Key key) {\n if (node == null) {\n return 0;\n }\n\n // Returns the number of keys less than node.key in the subtree rooted at node\n int compare = key.compareTo(node.key);\n if (compare < 0) {\n return rankLast(node.left, key);\n } else if (compare > 0) {\n return size(node.left) + 1 + rankLast(node.right, key);\n } else {\n boolean hasDuplicateOnRightSubtree = false;\n\n if (node.right != null && min(node.right).key.compareTo(key) == 0) {\n hasDuplicateOnRightSubtree = true;\n }\n\n if (hasDuplicateOnRightSubtree) {\n return size(node.left) + 1 + rankLast(node.right, key);\n } else {\n return size(node.left);\n }\n }\n }\n\n // In the case of duplicates, return the rank of the rightmost key\n public int rank(Key key) {\n return rankLast(key);\n }\n\n // O(n lg n) since we are removing all duplicate min keys\n public void deleteMin() {\n if (root == null) {\n return;\n }\n\n Key minKey = min();\n\n while (contains(minKey)) {\n root = deleteMin(root);\n }\n }\n\n private Node deleteMin(Node node) {\n if (node.left == null) {\n return node.right;\n }\n\n node.left = deleteMin(node.left);\n node.size = size(node.left) + 1 + size(node.right);\n return node;\n }\n\n // O(n lg n) since we are removing all duplicate max keys\n public void deleteMax() {\n if (root == null) {\n return;\n }\n\n Key maxKey = max();\n\n while (contains(maxKey)) {\n root = deleteMax(root);\n }\n }\n\n private Node deleteMax(Node node) {\n if (node.right == null) {\n return node.left;\n }\n\n node.right = deleteMax(node.right);\n node.size = size(node.left) + 1 + size(node.right);\n return node;\n }\n\n // O(n lg n) since we are removing all duplicate keys\n public void delete(Key key) {\n if (isEmpty()) {\n return;\n }\n\n while (contains(key)) {\n root = delete(root, key);\n }\n }\n\n private Node delete(Node node, Key key) {\n int compare = key.compareTo(node.key);\n if (compare < 0) {\n node.left = delete(node.left, key);\n } else if (compare > 0) {\n node.right = delete(node.right, key);\n } else {\n if (node.left == null) {\n return node.right;\n } else if (node.right == null) {\n return node.left;\n } else {\n Node aux = node;\n node = min(aux.right);\n node.right = deleteMin(aux.right);\n node.left = aux.left;\n }\n }\n\n node.size = size(node.left) + 1 + size(node.right);\n return node;\n }\n\n public Iterable keys() {\n return keys(min(), max());\n }\n\n public Iterable keys(Key low, Key high) {\n if (low == null) {\n throw new IllegalArgumentException(\"First argument to keys() cannot be null\");\n }\n if (high == null) {\n throw new IllegalArgumentException(\"Second argument to keys() cannot be null\");\n }\n\n Queue queue = new Queue<>();\n keys(root, queue, low, high);\n return queue;\n }\n\n private void keys(Node node, Queue queue, Key low, Key high) {\n if (node == null) {\n return;\n }\n\n int compareLow = low.compareTo(node.key);\n int compareHigh = high.compareTo(node.key);\n\n if (compareLow <= 0) {\n keys(node.left, queue, low, high);\n }\n\n if (compareLow <= 0 && compareHigh >= 0) {\n queue.enqueue(node.key);\n }\n\n if (compareHigh >= 0) {\n keys(node.right, queue, low, high);\n }\n }\n\n public int size(Key low, Key high) {\n if (low == null) {\n throw new IllegalArgumentException(\"First argument to size() cannot be null\");\n }\n if (high == null) {\n throw new IllegalArgumentException(\"Second argument to size() cannot be null\");\n }\n\n if (low.compareTo(high) > 0) {\n return 0;\n }\n\n if (contains(high)) {\n return rankLast(high) - rankFirst(low) + 1;\n } else {\n return rankLast(high) - rankFirst(low);\n }\n }\n }\n\n public static void main(String[] args) {\n Exercise9 exercise9 = new Exercise9();\n BinarySearchTreeDuplicateKeys binarySearchTreeDuplicateKeys =\n exercise9.new BinarySearchTreeDuplicateKeys<>();\n\n // Test put()\n binarySearchTreeDuplicateKeys.put(0, 0);\n binarySearchTreeDuplicateKeys.put(0, 1);\n binarySearchTreeDuplicateKeys.put(0, 2);\n binarySearchTreeDuplicateKeys.put(0, 3);\n\n binarySearchTreeDuplicateKeys.put(5, 7);\n binarySearchTreeDuplicateKeys.put(5, 8);\n\n binarySearchTreeDuplicateKeys.put(8, 9);\n binarySearchTreeDuplicateKeys.put(8, 10);\n\n binarySearchTreeDuplicateKeys.put(20, 11);\n binarySearchTreeDuplicateKeys.put(20, 12);\n binarySearchTreeDuplicateKeys.put(20, 13);\n binarySearchTreeDuplicateKeys.put(20, 14);\n\n binarySearchTreeDuplicateKeys.put(21, 15);\n binarySearchTreeDuplicateKeys.put(22, 16);\n binarySearchTreeDuplicateKeys.put(23, 17);\n binarySearchTreeDuplicateKeys.put(24, 18);\n\n StdOut.println(\"Keys() test\");\n for (Integer key : binarySearchTreeDuplicateKeys.keys()) {\n StdOut.println(\"Key \" + key + \": \" + binarySearchTreeDuplicateKeys.get(key));\n }\n StdOut.println(\"\\nExpected:\");\n // When there are duplicate keys the expected value is the value of the first inserted key\n StdOut.println(\"Key 0: 0\");\n StdOut.println(\"Key 0: 0\");\n StdOut.println(\"Key 0: 0\");\n StdOut.println(\"Key 0: 0\");\n StdOut.println(\"Key 5: 7\");\n StdOut.println(\"Key 5: 7\");\n StdOut.println(\"Key 8: 9\");\n StdOut.println(\"Key 8: 9\");\n StdOut.println(\"Key 20: 11\");\n StdOut.println(\"Key 20: 11\");\n StdOut.println(\"Key 20: 11\");\n StdOut.println(\"Key 20: 11\");\n StdOut.println(\"Key 21: 15\");\n StdOut.println(\"Key 22: 16\");\n StdOut.println(\"Key 23: 17\");\n StdOut.println(\"Key 24: 18\");\n\n // Test size()\n StdOut.println(\"Keys size: \" + binarySearchTreeDuplicateKeys.size() + \" Expected: 16\");\n\n // Test size() with range\n StdOut.println(\"Keys size [0, 20]: \" + binarySearchTreeDuplicateKeys.size(0, 20) + \" Expected: 12\");\n\n // Test contains()\n StdOut.println(\"\\nContains 8: \" + binarySearchTreeDuplicateKeys.contains(8) + \" Expected: true\");\n StdOut.println(\"Contains 9: \" + binarySearchTreeDuplicateKeys.contains(9) + \" Expected: false\");\n\n // Test min()\n StdOut.println(\"\\nMin key: \" + binarySearchTreeDuplicateKeys.min() + \" Expected: 0\");\n\n // Test max()\n StdOut.println(\"Max key: \" + binarySearchTreeDuplicateKeys.max() + \" Expected: 24\");\n\n // Test floor()\n StdOut.println(\"Floor of 5: \" + binarySearchTreeDuplicateKeys.floor(5) + \" Expected: 5\");\n StdOut.println(\"Floor of 15: \" + binarySearchTreeDuplicateKeys.floor(15) + \" Expected: 8\");\n\n // Test ceiling()\n StdOut.println(\"Ceiling of 5: \" + binarySearchTreeDuplicateKeys.ceiling(5) + \" Expected: 5\");\n StdOut.println(\"Ceiling of 15: \" + binarySearchTreeDuplicateKeys.ceiling(15) + \" Expected: 20\");\n\n // Test select()\n StdOut.println(\"Select key of rank 3: \" + binarySearchTreeDuplicateKeys.select(3) + \" Expected: 0\");\n StdOut.println(\"Select key of rank 4: \" + binarySearchTreeDuplicateKeys.select(4) + \" Expected: 5\");\n\n // Test rank()\n // Note that the expected rank of key 8 is 7 and not 6, because we are assuming that rank returns the index\n // of the rightmost key when there are duplicates\n StdOut.println(\"Rank of key 8: \" + binarySearchTreeDuplicateKeys.rank(8) + \" Expected: 7\");\n StdOut.println(\"Rank of key 9: \" + binarySearchTreeDuplicateKeys.rank(9) + \" Expected: 8\");\n\n // Test delete()\n StdOut.println(\"\\nDelete key 20\");\n binarySearchTreeDuplicateKeys.delete(20);\n\n for (Integer key : binarySearchTreeDuplicateKeys.keys()) {\n StdOut.println(\"Key \" + key + \": \" + binarySearchTreeDuplicateKeys.get(key));\n }\n StdOut.println(\"Keys size: \" + binarySearchTreeDuplicateKeys.size() + \" Expected: 12\");\n\n StdOut.println(\"\\nDelete key 5\");\n binarySearchTreeDuplicateKeys.delete(5);\n\n for (Integer key : binarySearchTreeDuplicateKeys.keys()) {\n StdOut.println(\"Key \" + key + \": \" + binarySearchTreeDuplicateKeys.get(key));\n }\n StdOut.println(\"Keys size: \" + binarySearchTreeDuplicateKeys.size() + \" Expected: 10\");\n\n // Test deleteMin()\n StdOut.println(\"\\nDelete min (key 0)\");\n binarySearchTreeDuplicateKeys.deleteMin();\n\n for (Integer key : binarySearchTreeDuplicateKeys.keys()) {\n StdOut.println(\"Key \" + key + \": \" + binarySearchTreeDuplicateKeys.get(key));\n }\n\n // Test deleteMax()\n StdOut.println(\"\\nDelete max (key 24)\");\n binarySearchTreeDuplicateKeys.deleteMax();\n\n for (Integer key : binarySearchTreeDuplicateKeys.keys()) {\n StdOut.println(\"Key \" + key + \": \" + binarySearchTreeDuplicateKeys.get(key));\n }\n\n // Test keys() with range\n StdOut.println(\"\\nKeys in range [2, 10]\");\n for (Integer key : binarySearchTreeDuplicateKeys.keys(2, 10)) {\n StdOut.println(\"Key \" + key + \": \" + binarySearchTreeDuplicateKeys.get(key));\n }\n\n StdOut.println(\"\\nKeys in range [20, 22]\");\n for (Integer key : binarySearchTreeDuplicateKeys.keys(20, 22)) {\n StdOut.println(\"Key \" + key + \": \" + binarySearchTreeDuplicateKeys.get(key));\n }\n\n // Delete all\n StdOut.println(\"\\nDelete all\");\n while (binarySearchTreeDuplicateKeys.size() > 0) {\n for (Integer key : binarySearchTreeDuplicateKeys.keys()) {\n StdOut.println(\"Key \" + key + \": \" + binarySearchTreeDuplicateKeys.get(key));\n }\n // binarySearchTreeDuplicateKeys.delete(binarySearchTreeDuplicateKeys.select(0));\n binarySearchTreeDuplicateKeys.delete(binarySearchTreeDuplicateKeys.select(binarySearchTreeDuplicateKeys.size() - 1));\n StdOut.println();\n }\n }\n}\n", "support_files": [], "metadata": {"number": "3.5.9", "chapter": 3, "chapter_title": "Searching", "section": 3.5, "section_title": "Applications", "type": "Exercise", "code_execution": false}} {"question": "Modify RedBlackBST to keep duplicate keys in the tree. Return any value associated with the given key for get(), and remove all nodes in the tree that have keys equal to the given key for delete().", "answer": "package chapter3.section5;\n\nimport edu.princeton.cs.algs4.Queue;\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.NoSuchElementException;\n\n/**\n * Created by Rene Argento on 05/08/17.\n */\npublic class Exercise10 {\n\n /**\n * This tree has the following property:\n *\n * Let x be a node in the red-black binary search tree.\n * If y is a node in the left subtree of x, then y:key <= x:key.\n * If y is a node in the right subtree of x, then y:key >= x:key.\n */\n private class RedBlackBSTDuplicateKeys, Value> {\n\n private static final boolean RED = true;\n private static final boolean BLACK = false;\n\n private class Node {\n Key key;\n Value value;\n Node left, right;\n\n boolean color;\n int size;\n\n Node(Key key, Value value, int size, boolean color) {\n this.key = key;\n this.value = value;\n\n this.size = size;\n this.color = color;\n }\n }\n\n private Node root;\n\n public int size() {\n return size(root);\n }\n\n private int size(Node node) {\n if (node == null) {\n return 0;\n }\n\n return node.size;\n }\n\n public boolean isEmpty() {\n return size(root) == 0;\n }\n\n private boolean isRed(Node node) {\n if (node == null) {\n return false;\n }\n\n return node.color == RED;\n }\n\n private Node rotateLeft(Node node) {\n if (node == null || node.right == null) {\n return node;\n }\n\n Node newRoot = node.right;\n\n node.right = newRoot.left;\n newRoot.left = node;\n\n newRoot.color = node.color;\n node.color = RED;\n\n newRoot.size = node.size;\n node.size = size(node.left) + 1 + size(node.right);\n\n return newRoot;\n }\n\n private Node rotateRight(Node node) {\n if (node == null || node.left == null) {\n return node;\n }\n\n Node newRoot = node.left;\n\n node.left = newRoot.right;\n newRoot.right = node;\n\n newRoot.color = node.color;\n node.color = RED;\n\n newRoot.size = node.size;\n node.size = size(node.left) + 1 + size(node.right);\n\n return newRoot;\n }\n\n private void flipColors(Node node) {\n if (node == null || node.left == null || node.right == null) {\n return;\n }\n\n // The root must have opposite color of its two children\n if ((isRed(node) && !isRed(node.left) && !isRed(node.right))\n || (!isRed(node) && isRed(node.left) && isRed(node.right))) {\n node.color = !node.color;\n node.left.color = !node.left.color;\n node.right.color = !node.right.color;\n }\n }\n\n public void put(Key key, Value value) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n if (value == null) {\n delete(key);\n return;\n }\n\n root = put(root, key, value);\n root.color = BLACK;\n }\n\n private Node put(Node node, Key key, Value value) {\n if (node == null) {\n return new Node(key, value, 1, RED);\n }\n\n int compare = key.compareTo(node.key);\n\n // If it is a duplicate key, put it on the left subtree\n // It is important to notice that since we have rotations,\n // the duplicate keys may be on the left or right subtrees later\n if (compare <= 0) {\n node.left = put(node.left, key, value);\n } else if (compare > 0) {\n node.right = put(node.right, key, value);\n }\n\n if (isRed(node.right) && !isRed(node.left)) {\n node = rotateLeft(node);\n }\n if (isRed(node.left) && isRed(node.left.left)) {\n node = rotateRight(node);\n }\n if (isRed(node.left) && isRed(node.right)) {\n flipColors(node);\n }\n\n node.size = size(node.left) + 1 + size(node.right);\n return node;\n }\n\n public Value get(Key key) {\n if (key == null) {\n return null;\n }\n\n return get(root, key);\n }\n\n private Value get(Node node, Key key) {\n if (node == null) {\n return null;\n }\n\n int compare = key.compareTo(node.key);\n if (compare < 0) {\n return get(node.left, key);\n } else if (compare > 0) {\n return get(node.right, key);\n } else {\n return node.value;\n }\n }\n\n public boolean contains(Key key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Argument to contains() cannot be null\");\n }\n return get(key) != null;\n }\n\n public Key min() {\n if (root == null) {\n throw new NoSuchElementException(\"Empty binary search tree\");\n }\n\n return min(root).key;\n }\n\n private Node min(Node node) {\n if (node.left == null) {\n return node;\n }\n\n return min(node.left);\n }\n\n public Key max() {\n if (root == null) {\n throw new NoSuchElementException(\"Empty binary search tree\");\n }\n\n return max(root).key;\n }\n\n private Node max(Node node) {\n if (node.right == null) {\n return node;\n }\n\n return max(node.right);\n }\n\n // Returns the highest key in the symbol table smaller than or equal to key.\n public Key floor(Key key) {\n Node node = floor(root, key);\n if (node == null) {\n return null;\n }\n\n return node.key;\n }\n\n private Node floor(Node node, Key key) {\n if (node == null) {\n return null;\n }\n\n int compare = key.compareTo(node.key);\n\n if (compare == 0) {\n return node;\n } else if (compare < 0) {\n return floor(node.left, key);\n } else {\n Node rightNode = floor(node.right, key);\n if (rightNode != null) {\n return rightNode;\n } else {\n return node;\n }\n }\n }\n\n // Returns the smallest key in the symbol table greater than or equal to key.\n public Key ceiling(Key key) {\n Node node = ceiling(root, key);\n if (node == null) {\n return null;\n }\n\n return node.key;\n }\n\n private Node ceiling(Node node, Key key) {\n if (node == null) {\n return null;\n }\n\n int compare = key.compareTo(node.key);\n\n if (compare == 0) {\n return node;\n } else if (compare > 0) {\n return ceiling(node.right, key);\n } else {\n Node leftNode = ceiling(node.left, key);\n if (leftNode != null) {\n return leftNode;\n } else {\n return node;\n }\n }\n }\n\n public Key select(int index) {\n if (index >= size()) {\n throw new IllegalArgumentException(\"Index is higher than tree size\");\n }\n\n return select(root, index).key;\n }\n\n private Node select(Node node, int index) {\n int leftSubtreeSize = size(node.left);\n\n if (leftSubtreeSize == index) {\n return node;\n } else if (leftSubtreeSize > index) {\n return select(node.left, index);\n } else {\n return select(node.right, index - leftSubtreeSize - 1);\n }\n }\n\n public int rankFirst(Key key) {\n return rankFirst(root, key);\n }\n\n private int rankFirst(Node node, Key key) {\n if (node == null) {\n return 0;\n }\n\n // Returns the number of keys less than node.key in the subtree rooted at node\n int compare = key.compareTo(node.key);\n if (compare < 0) {\n return rankFirst(node.left, key);\n } else if (compare > 0) {\n return size(node.left) + 1 + rankFirst(node.right, key);\n } else {\n boolean hasDuplicateOnLeftSubtree = false;\n\n if (node.left != null && max(node.left).key.compareTo(key) == 0) {\n hasDuplicateOnLeftSubtree = true;\n }\n\n if (hasDuplicateOnLeftSubtree) {\n return rankFirst(node.left, key);\n } else {\n return size(node.left);\n }\n }\n }\n\n public int rankLast(Key key) {\n return rankLast(root, key);\n }\n\n private int rankLast(Node node, Key key) {\n if (node == null) {\n return 0;\n }\n\n // Returns the number of keys less than node.key in the subtree rooted at node\n int compare = key.compareTo(node.key);\n if (compare < 0) {\n return rankLast(node.left, key);\n } else if (compare > 0) {\n return size(node.left) + 1 + rankLast(node.right, key);\n } else {\n boolean hasDuplicateOnRightSubtree = false;\n\n if (node.right != null && min(node.right).key.compareTo(key) == 0) {\n hasDuplicateOnRightSubtree = true;\n }\n\n if (hasDuplicateOnRightSubtree) {\n return size(node.left) + 1 + rankLast(node.right, key);\n } else {\n return size(node.left);\n }\n }\n }\n\n // In the case of duplicates, return the rank of the rightmost key\n public int rank(Key key) {\n return rankLast(key);\n }\n\n // O(n lg n) since we are removing all duplicate min keys\n public void deleteMin() {\n if (isEmpty()) {\n return;\n }\n\n Key minKey = min();\n\n while (contains(minKey)) {\n if (!isRed(root.left) && !isRed(root.right)) {\n root.color = RED;\n }\n\n root = deleteMin(root);\n\n if (!isEmpty()) {\n root.color = BLACK;\n }\n }\n }\n\n private Node deleteMin(Node node) {\n if (node.left == null) {\n return null;\n }\n\n if (!isRed(node.left) && !isRed(node.left.left)) {\n node = moveRedLeft(node);\n }\n\n node.left = deleteMin(node.left);\n return balance(node);\n }\n\n // O(n lg n) since we are removing all duplicate max keys\n public void deleteMax() {\n if (isEmpty()) {\n return;\n }\n\n Key maxKey = max();\n\n while (contains(maxKey)) {\n if (!isRed(root.left) && !isRed(root.right)) {\n root.color = RED;\n }\n\n root = deleteMax(root);\n\n if (!isEmpty()) {\n root.color = BLACK;\n }\n }\n }\n\n private Node deleteMax(Node node) {\n if (isRed(node.left)) {\n node = rotateRight(node);\n }\n\n if (node.right == null) {\n return null;\n }\n\n if (!isRed(node.right) && !isRed(node.right.left)) {\n node = moveRedRight(node);\n }\n\n node.right = deleteMax(node.right);\n return balance(node);\n }\n\n // O(n lg n) since we are removing all duplicate keys\n public void delete(Key key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n if (isEmpty() || !contains(key)) {\n return;\n }\n\n while (contains(key)) {\n if (!isRed(root.left) && !isRed(root.right)) {\n root.color = RED;\n }\n\n root = delete(root, key);\n\n if (!isEmpty()) {\n root.color = BLACK;\n }\n }\n }\n\n private Node delete(Node node, Key key) {\n if (node == null) {\n return null;\n }\n\n if (key.compareTo(node.key) < 0) {\n if (!isRed(node.left) && node.left != null && !isRed(node.left.left)) {\n node = moveRedLeft(node);\n }\n\n node.left = delete(node.left, key);\n } else {\n if (isRed(node.left)) {\n node = rotateRight(node);\n }\n\n if (key.compareTo(node.key) == 0 && node.right == null) {\n return null;\n }\n\n if (!isRed(node.right) && node.right != null && !isRed(node.right.left)) {\n node = moveRedRight(node);\n }\n\n if (key.compareTo(node.key) == 0) {\n Node aux = min(node.right);\n node.key = aux.key;\n node.value = aux.value;\n node.right = deleteMin(node.right);\n } else {\n node.right = delete(node.right, key);\n }\n }\n\n return balance(node);\n }\n\n private Node moveRedLeft(Node node) {\n // Assuming that node is red and both node.left and node.left.left are black,\n // make node.left or one of its children red\n flipColors(node);\n\n if (node.right != null && isRed(node.right.left)) {\n node.right = rotateRight(node.right);\n node = rotateLeft(node);\n flipColors(node);\n }\n\n return node;\n }\n\n private Node moveRedRight(Node node) {\n // Assuming that node is red and both node.right and node.right.left are black,\n // make node.right or one of its children red\n flipColors(node);\n\n if (node.left != null && isRed(node.left.left)) {\n node = rotateRight(node);\n flipColors(node);\n }\n\n return node;\n }\n\n private Node balance(Node node) {\n if (node == null) {\n return null;\n }\n\n if (isRed(node.right)) {\n node = rotateLeft(node);\n }\n\n if (isRed(node.left) && isRed(node.left.left)) {\n node = rotateRight(node);\n }\n\n if (isRed(node.left) && isRed(node.right)) {\n flipColors(node);\n }\n\n node.size = size(node.left) + 1 + size(node.right);\n\n return node;\n }\n\n public Iterable keys() {\n return keys(min(), max());\n }\n\n public Iterable keys(Key low, Key high) {\n if (low == null) {\n throw new IllegalArgumentException(\"First argument to keys() cannot be null\");\n }\n if (high == null) {\n throw new IllegalArgumentException(\"Second argument to keys() cannot be null\");\n }\n\n Queue queue = new Queue<>();\n keys(root, queue, low, high);\n return queue;\n }\n\n private void keys(Node node, Queue queue, Key low, Key high) {\n if (node == null) {\n return;\n }\n\n int compareLow = low.compareTo(node.key);\n int compareHigh = high.compareTo(node.key);\n\n if (compareLow <= 0) {\n keys(node.left, queue, low, high);\n }\n\n if (compareLow <= 0 && compareHigh >= 0) {\n queue.enqueue(node.key);\n }\n\n if (compareHigh >= 0) {\n keys(node.right, queue, low, high);\n }\n }\n\n public int size(Key low, Key high) {\n if (low == null) {\n throw new IllegalArgumentException(\"First argument to size() cannot be null\");\n }\n if (high == null) {\n throw new IllegalArgumentException(\"Second argument to size() cannot be null\");\n }\n\n if (low.compareTo(high) > 0) {\n return 0;\n }\n\n if (contains(high)) {\n return rankLast(high) - rankFirst(low) + 1;\n } else {\n return rankLast(high) - rankFirst(low);\n }\n }\n }\n\n public static void main(String[] args) {\n Exercise10 exercise10 = new Exercise10();\n RedBlackBSTDuplicateKeys redBlackBSTDuplicateKeys = exercise10.new RedBlackBSTDuplicateKeys<>();\n\n // Test put()\n redBlackBSTDuplicateKeys.put(0, 0);\n redBlackBSTDuplicateKeys.put(0, 1);\n redBlackBSTDuplicateKeys.put(0, 2);\n redBlackBSTDuplicateKeys.put(0, 3);\n\n redBlackBSTDuplicateKeys.put(5, 7);\n redBlackBSTDuplicateKeys.put(5, 8);\n\n redBlackBSTDuplicateKeys.put(8, 9);\n redBlackBSTDuplicateKeys.put(8, 10);\n\n redBlackBSTDuplicateKeys.put(20, 11);\n redBlackBSTDuplicateKeys.put(20, 12);\n redBlackBSTDuplicateKeys.put(20, 13);\n redBlackBSTDuplicateKeys.put(20, 14);\n\n redBlackBSTDuplicateKeys.put(21, 15);\n redBlackBSTDuplicateKeys.put(22, 16);\n redBlackBSTDuplicateKeys.put(23, 17);\n redBlackBSTDuplicateKeys.put(24, 18);\n\n StdOut.println(\"Keys() test\");\n for (Integer key : redBlackBSTDuplicateKeys.keys()) {\n StdOut.println(\"Key \" + key + \": \" + redBlackBSTDuplicateKeys.get(key));\n }\n StdOut.println(\"\\nExpected:\");\n StdOut.println(\"Key 0: {0, 1, 2 or 3}\");\n StdOut.println(\"Key 0: {0, 1, 2 or 3}\");\n StdOut.println(\"Key 0: {0, 1, 2 or 3}\");\n StdOut.println(\"Key 0: {0, 1, 2 or 3}\");\n StdOut.println(\"Key 5: {7 or 8}\");\n StdOut.println(\"Key 5: {7 or 8}\");\n StdOut.println(\"Key 8: {9 or 10}\");\n StdOut.println(\"Key 8: {9 or 10}\");\n StdOut.println(\"Key 20: {11, 12, 13 or 14}\");\n StdOut.println(\"Key 20: {11, 12, 13 or 14}\");\n StdOut.println(\"Key 20: {11, 12, 13 or 14}\");\n StdOut.println(\"Key 20: {11, 12, 13 or 14}\");\n StdOut.println(\"Key 21: 15\");\n StdOut.println(\"Key 22: 16\");\n StdOut.println(\"Key 23: 17\");\n StdOut.println(\"Key 24: 18\");\n\n // Test size()\n StdOut.println(\"Keys size: \" + redBlackBSTDuplicateKeys.size() + \" Expected: 16\");\n\n // Test size() with range\n StdOut.println(\"Keys size [0, 20]: \" + redBlackBSTDuplicateKeys.size(0, 20) + \" Expected: 12\");\n\n // Test contains()\n StdOut.println(\"\\nContains 8: \" + redBlackBSTDuplicateKeys.contains(8) + \" Expected: true\");\n StdOut.println(\"Contains 9: \" + redBlackBSTDuplicateKeys.contains(9) + \" Expected: false\");\n\n // Test min()\n StdOut.println(\"\\nMin key: \" + redBlackBSTDuplicateKeys.min() + \" Expected: 0\");\n\n // Test max()\n StdOut.println(\"Max key: \" + redBlackBSTDuplicateKeys.max() + \" Expected: 24\");\n\n // Test floor()\n StdOut.println(\"Floor of 5: \" + redBlackBSTDuplicateKeys.floor(5) + \" Expected: 5\");\n StdOut.println(\"Floor of 15: \" + redBlackBSTDuplicateKeys.floor(15) + \" Expected: 8\");\n\n // Test ceiling()\n StdOut.println(\"Ceiling of 5: \" + redBlackBSTDuplicateKeys.ceiling(5) + \" Expected: 5\");\n StdOut.println(\"Ceiling of 15: \" + redBlackBSTDuplicateKeys.ceiling(15) + \" Expected: 20\");\n\n // Test select()\n StdOut.println(\"Select key of rank 3: \" + redBlackBSTDuplicateKeys.select(3) + \" Expected: 0\");\n StdOut.println(\"Select key of rank 4: \" + redBlackBSTDuplicateKeys.select(4) + \" Expected: 5\");\n\n // Test rank()\n // Note that the expected rank of key 8 is 7 and not 6, because we are assuming that rank returns the index\n // of the rightmost key when there are duplicates\n StdOut.println(\"Rank of key 8: \" + redBlackBSTDuplicateKeys.rank(8) + \" Expected: 7\");\n StdOut.println(\"Rank of key 9: \" + redBlackBSTDuplicateKeys.rank(9) + \" Expected: 8\");\n\n // Test delete()\n StdOut.println(\"\\nDelete key 20\");\n redBlackBSTDuplicateKeys.delete(20);\n\n for (Integer key : redBlackBSTDuplicateKeys.keys()) {\n StdOut.println(\"Key \" + key + \": \" + redBlackBSTDuplicateKeys.get(key));\n }\n StdOut.println(\"Keys size: \" + redBlackBSTDuplicateKeys.size() + \" Expected: 12\");\n\n StdOut.println(\"\\nDelete key 5\");\n redBlackBSTDuplicateKeys.delete(5);\n\n for (Integer key : redBlackBSTDuplicateKeys.keys()) {\n StdOut.println(\"Key \" + key + \": \" + redBlackBSTDuplicateKeys.get(key));\n }\n StdOut.println(\"Keys size: \" + redBlackBSTDuplicateKeys.size() + \" Expected: 10\");\n\n // Test deleteMin()\n StdOut.println(\"\\nDelete min (key 0)\");\n redBlackBSTDuplicateKeys.deleteMin();\n\n for (Integer key : redBlackBSTDuplicateKeys.keys()) {\n StdOut.println(\"Key \" + key + \": \" + redBlackBSTDuplicateKeys.get(key));\n }\n StdOut.println(\"Keys size: \" + redBlackBSTDuplicateKeys.size() + \" Expected: 6\");\n\n // Test deleteMax()\n StdOut.println(\"\\nDelete max (key 24)\");\n redBlackBSTDuplicateKeys.deleteMax();\n\n for (Integer key : redBlackBSTDuplicateKeys.keys()) {\n StdOut.println(\"Key \" + key + \": \" + redBlackBSTDuplicateKeys.get(key));\n }\n StdOut.println(\"Keys size: \" + redBlackBSTDuplicateKeys.size() + \" Expected: 5\");\n\n // Test keys() with range\n StdOut.println(\"\\nKeys in range [2, 10]\");\n for (Integer key : redBlackBSTDuplicateKeys.keys(2, 10)) {\n StdOut.println(\"Key \" + key + \": \" + redBlackBSTDuplicateKeys.get(key));\n }\n\n StdOut.println(\"\\nKeys in range [20, 22]\");\n for (Integer key : redBlackBSTDuplicateKeys.keys(20, 22)) {\n StdOut.println(\"Key \" + key + \": \" + redBlackBSTDuplicateKeys.get(key));\n }\n\n // Delete all\n StdOut.println(\"\\nDelete all\");\n while (redBlackBSTDuplicateKeys.size() > 0) {\n for (Integer key : redBlackBSTDuplicateKeys.keys()) {\n StdOut.println(\"Key \" + key + \": \" + redBlackBSTDuplicateKeys.get(key));\n }\n // redBlackBSTDuplicateKeys.delete(redBlackBSTDuplicateKeys.select(0));\n redBlackBSTDuplicateKeys.delete(redBlackBSTDuplicateKeys.select(redBlackBSTDuplicateKeys.size() - 1));\n StdOut.println();\n }\n }\n}\n", "support_files": [], "metadata": {"number": "3.5.10", "chapter": 3, "chapter_title": "Searching", "section": 3.5, "section_title": "Applications", "type": "Exercise", "code_execution": false}} {"question": "Develop a MultiSET class that is like SET, but allows equal keys and thus implements a mathematical multiset.", "answer": "package chapter3.section5;\n\nimport edu.princeton.cs.algs4.Queue;\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.NoSuchElementException;\n\n/**\n * Created by Rene Argento on 06/08/17.\n */\npublic class Exercise11 {\n\n /**\n * This tree has the following property:\n *\n * Let x be a node in the red-black binary search tree.\n * If y is a node in the left subtree of x, then y:key <= x:key.\n * If y is a node in the right subtree of x, then y:key >= x:key.\n */\n private class MultiSET> {\n\n private static final boolean RED = true;\n private static final boolean BLACK = false;\n\n private class Node {\n Key key;\n Node left, right;\n\n boolean color;\n int size;\n\n Node(Key key, int size, boolean color) {\n this.key = key;\n this.size = size;\n this.color = color;\n }\n }\n\n private Node root;\n\n public int size() {\n return size(root);\n }\n\n private int size(Node node) {\n if (node == null) {\n return 0;\n }\n\n return node.size;\n }\n\n public boolean isEmpty() {\n return size(root) == 0;\n }\n\n private boolean isRed(Node node) {\n if (node == null) {\n return false;\n }\n\n return node.color == RED;\n }\n\n private Node rotateLeft(Node node) {\n if (node == null || node.right == null) {\n return node;\n }\n\n Node newRoot = node.right;\n\n node.right = newRoot.left;\n newRoot.left = node;\n\n newRoot.color = node.color;\n node.color = RED;\n\n newRoot.size = node.size;\n node.size = size(node.left) + 1 + size(node.right);\n\n return newRoot;\n }\n\n private Node rotateRight(Node node) {\n if (node == null || node.left == null) {\n return node;\n }\n\n Node newRoot = node.left;\n\n node.left = newRoot.right;\n newRoot.right = node;\n\n newRoot.color = node.color;\n node.color = RED;\n\n newRoot.size = node.size;\n node.size = size(node.left) + 1 + size(node.right);\n\n return newRoot;\n }\n\n private void flipColors(Node node) {\n if (node == null || node.left == null || node.right == null) {\n return;\n }\n\n //The root must have opposite color of its two children\n if ((isRed(node) && !isRed(node.left) && !isRed(node.right))\n || (!isRed(node) && isRed(node.left) && isRed(node.right))) {\n node.color = !node.color;\n node.left.color = !node.left.color;\n node.right.color = !node.right.color;\n }\n }\n\n public void add(Key key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n root = add(root, key);\n root.color = BLACK;\n }\n\n private Node add(Node node, Key key) {\n if (node == null) {\n return new Node(key, 1, RED);\n }\n\n int compare = key.compareTo(node.key);\n\n //If it is a duplicate key, put it on the left subtree\n //It is important to notice that since we have rotations,\n // the duplicate keys may be on the left or right subtrees later\n if (compare <= 0) {\n node.left = add(node.left, key);\n } else if (compare > 0) {\n node.right = add(node.right, key);\n }\n\n if (isRed(node.right) && !isRed(node.left)) {\n node = rotateLeft(node);\n }\n if (isRed(node.left) && isRed(node.left.left)) {\n node = rotateRight(node);\n }\n if (isRed(node.left) && isRed(node.right)) {\n flipColors(node);\n }\n\n node.size = size(node.left) + 1 + size(node.right);\n return node;\n }\n\n public boolean contains(Key key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Argument to contains() cannot be null\");\n }\n\n Node currentNode = root;\n\n while (currentNode != null) {\n int compare = key.compareTo(currentNode.key);\n\n if (compare < 0) {\n currentNode = currentNode.left;\n } else if (compare > 0) {\n currentNode = currentNode.right;\n } else {\n return true;\n }\n }\n\n return false;\n }\n\n public Key min() {\n if (root == null) {\n throw new NoSuchElementException(\"Empty binary search tree\");\n }\n\n return min(root).key;\n }\n\n private Node min(Node node) {\n if (node.left == null) {\n return node;\n }\n\n return min(node.left);\n }\n\n public Key max() {\n if (root == null) {\n throw new NoSuchElementException(\"Empty binary search tree\");\n }\n\n return max(root).key;\n }\n\n private Node max(Node node) {\n if (node.right == null) {\n return node;\n }\n\n return max(node.right);\n }\n\n //Returns the highest key in the symbol table smaller than or equal to key.\n public Key floor(Key key) {\n Node node = floor(root, key);\n if (node == null) {\n return null;\n }\n\n return node.key;\n }\n\n private Node floor(Node node, Key key) {\n if (node == null) {\n return null;\n }\n\n int compare = key.compareTo(node.key);\n\n if (compare == 0) {\n return node;\n } else if (compare < 0) {\n return floor(node.left, key);\n } else {\n Node rightNode = floor(node.right, key);\n if (rightNode != null) {\n return rightNode;\n } else {\n return node;\n }\n }\n }\n\n //Returns the smallest key in the symbol table greater than or equal to key.\n public Key ceiling(Key key) {\n Node node = ceiling(root, key);\n if (node == null) {\n return null;\n }\n\n return node.key;\n }\n\n private Node ceiling(Node node, Key key) {\n if (node == null) {\n return null;\n }\n\n int compare = key.compareTo(node.key);\n\n if (compare == 0) {\n return node;\n } else if (compare > 0) {\n return ceiling(node.right, key);\n } else {\n Node leftNode = ceiling(node.left, key);\n if (leftNode != null) {\n return leftNode;\n } else {\n return node;\n }\n }\n }\n\n public Key select(int index) {\n if (index >= size()) {\n throw new IllegalArgumentException(\"Index is higher than tree size\");\n }\n\n return select(root, index).key;\n }\n\n private Node select(Node node, int index) {\n int leftSubtreeSize = size(node.left);\n\n if (leftSubtreeSize == index) {\n return node;\n } else if (leftSubtreeSize > index) {\n return select(node.left, index);\n } else {\n return select(node.right, index - leftSubtreeSize - 1);\n }\n }\n\n public int rankFirst(Key key) {\n return rankFirst(root, key);\n }\n\n private int rankFirst(Node node, Key key) {\n if (node == null) {\n return 0;\n }\n\n //Returns the number of keys less than node.key in the subtree rooted at node\n int compare = key.compareTo(node.key);\n if (compare < 0) {\n return rankFirst(node.left, key);\n } else if (compare > 0) {\n return size(node.left) + 1 + rankFirst(node.right, key);\n } else {\n boolean hasDuplicateOnLeftSubtree = false;\n\n if (node.left != null && max(node.left).key.compareTo(key) == 0) {\n hasDuplicateOnLeftSubtree = true;\n }\n\n if (hasDuplicateOnLeftSubtree) {\n return rankFirst(node.left, key);\n } else {\n return size(node.left);\n }\n }\n }\n\n public int rankLast(Key key) {\n return rankLast(root, key);\n }\n\n private int rankLast(Node node, Key key) {\n if (node == null) {\n return 0;\n }\n\n //Returns the number of keys less than node.key in the subtree rooted at node\n int compare = key.compareTo(node.key);\n if (compare < 0) {\n return rankLast(node.left, key);\n } else if (compare > 0) {\n return size(node.left) + 1 + rankLast(node.right, key);\n } else {\n boolean hasDuplicateOnRightSubtree = false;\n\n if (node.right != null && min(node.right).key.compareTo(key) == 0) {\n hasDuplicateOnRightSubtree = true;\n }\n\n if (hasDuplicateOnRightSubtree) {\n return size(node.left) + 1 + rankLast(node.right, key);\n } else {\n return size(node.left);\n }\n }\n }\n\n //In the case of duplicates, return the rank of the rightmost key\n public int rank(Key key) {\n return rankLast(key);\n }\n\n //O(n lg n) since we are removing all duplicate min keys\n public void deleteMin() {\n if (isEmpty()) {\n return;\n }\n\n Key minKey = min();\n\n while (contains(minKey)) {\n if (!isRed(root.left) && !isRed(root.right)) {\n root.color = RED;\n }\n\n root = deleteMin(root);\n\n if (!isEmpty()) {\n root.color = BLACK;\n }\n }\n }\n\n private Node deleteMin(Node node) {\n if (node.left == null) {\n return null;\n }\n\n if (!isRed(node.left) && !isRed(node.left.left)) {\n node = moveRedLeft(node);\n }\n\n node.left = deleteMin(node.left);\n return balance(node);\n }\n\n //O(n lg n) since we are removing all duplicate max keys\n public void deleteMax() {\n if (isEmpty()) {\n return;\n }\n\n Key maxKey = max();\n\n while (contains(maxKey)) {\n if (!isRed(root.left) && !isRed(root.right)) {\n root.color = RED;\n }\n\n root = deleteMax(root);\n\n if (!isEmpty()) {\n root.color = BLACK;\n }\n }\n }\n\n private Node deleteMax(Node node) {\n if (isRed(node.left)) {\n node = rotateRight(node);\n }\n\n if (node.right == null) {\n return null;\n }\n\n if (!isRed(node.right) && !isRed(node.right.left)) {\n node = moveRedRight(node);\n }\n\n node.right = deleteMax(node.right);\n return balance(node);\n }\n\n //O(n lg n) since we are removing all duplicate keys\n public void delete(Key key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n if (isEmpty() || !contains(key)) {\n return;\n }\n\n while (contains(key)) {\n if (!isRed(root.left) && !isRed(root.right)) {\n root.color = RED;\n }\n\n root = delete(root, key);\n\n if (!isEmpty()) {\n root.color = BLACK;\n }\n }\n }\n\n private Node delete(Node node, Key key) {\n if (node == null) {\n return null;\n }\n\n if (key.compareTo(node.key) < 0) {\n if (!isRed(node.left) && node.left != null && !isRed(node.left.left)) {\n node = moveRedLeft(node);\n }\n\n node.left = delete(node.left, key);\n } else {\n if (isRed(node.left)) {\n node = rotateRight(node);\n }\n\n if (key.compareTo(node.key) == 0 && node.right == null) {\n return null;\n }\n\n if (!isRed(node.right) && node.right != null && !isRed(node.right.left)) {\n node = moveRedRight(node);\n }\n\n if (key.compareTo(node.key) == 0) {\n Node aux = min(node.right);\n node.key = aux.key;\n node.right = deleteMin(node.right);\n } else {\n node.right = delete(node.right, key);\n }\n }\n\n return balance(node);\n }\n\n private Node moveRedLeft(Node node) {\n //Assuming that node is red and both node.left and node.left.left are black,\n // make node.left or one of its children red\n flipColors(node);\n\n if (node.right != null && isRed(node.right.left)) {\n node.right = rotateRight(node.right);\n node = rotateLeft(node);\n flipColors(node);\n }\n\n return node;\n }\n\n private Node moveRedRight(Node node) {\n //Assuming that node is red and both node.right and node.right.left are black,\n // make node.right or one of its children red\n flipColors(node);\n\n if (node.left != null && isRed(node.left.left)) {\n node = rotateRight(node);\n flipColors(node);\n }\n\n return node;\n }\n\n private Node balance(Node node) {\n if (node == null) {\n return null;\n }\n\n if (isRed(node.right)) {\n node = rotateLeft(node);\n }\n\n if (isRed(node.left) && isRed(node.left.left)) {\n node = rotateRight(node);\n }\n\n if (isRed(node.left) && isRed(node.right)) {\n flipColors(node);\n }\n\n node.size = size(node.left) + 1 + size(node.right);\n\n return node;\n }\n\n public Iterable keys() {\n return keys(min(), max());\n }\n\n public Iterable keys(Key low, Key high) {\n if (low == null) {\n throw new IllegalArgumentException(\"First argument to keys() cannot be null\");\n }\n if (high == null) {\n throw new IllegalArgumentException(\"Second argument to keys() cannot be null\");\n }\n\n Queue queue = new Queue<>();\n keys(root, queue, low, high);\n return queue;\n }\n\n private void keys(Node node, Queue queue, Key low, Key high) {\n if (node == null) {\n return;\n }\n\n int compareLow = low.compareTo(node.key);\n int compareHigh = high.compareTo(node.key);\n\n if (compareLow <= 0) {\n keys(node.left, queue, low, high);\n }\n\n if (compareLow <= 0 && compareHigh >= 0) {\n queue.enqueue(node.key);\n }\n\n if (compareHigh >= 0) {\n keys(node.right, queue, low, high);\n }\n }\n\n public int size(Key low, Key high) {\n if (low == null) {\n throw new IllegalArgumentException(\"First argument to size() cannot be null\");\n }\n if (high == null) {\n throw new IllegalArgumentException(\"Second argument to size() cannot be null\");\n }\n\n if (low.compareTo(high) > 0) {\n return 0;\n }\n\n if (contains(high)) {\n return rankLast(high) - rankFirst(low) + 1;\n } else {\n return rankLast(high) - rankFirst(low);\n }\n }\n }\n\n public static void main(String[] args) {\n Exercise11 exercise11 = new Exercise11();\n MultiSET multiset = exercise11.new MultiSET<>();\n\n //Test add()\n multiset.add(0);\n multiset.add(0);\n multiset.add(0);\n multiset.add(0);\n\n multiset.add(5);\n multiset.add(5);\n\n multiset.add(8);\n multiset.add(8);\n\n multiset.add(20);\n multiset.add(20);\n multiset.add(20);\n multiset.add(20);\n\n multiset.add(21);\n multiset.add(22);\n multiset.add(23);\n multiset.add(24);\n\n StdOut.println(\"Keys() test\");\n for (Integer key : multiset.keys()) {\n StdOut.print(key + \" \");\n }\n StdOut.println(\"\\nExpected: 0 0 0 0 5 5 8 8 20 20 20 20 21 22 23 24\");\n\n // Test size()\n StdOut.println(\"Keys size: \" + multiset.size() + \" Expected: 16\");\n\n // Test size() with range\n StdOut.println(\"Keys size [0, 20]: \" + multiset.size(0, 20) + \" Expected: 12\");\n\n // Test contains()\n StdOut.println(\"\\nContains 8: \" + multiset.contains(8) + \" Expected: true\");\n StdOut.println(\"Contains 9: \" + multiset.contains(9) + \" Expected: false\");\n\n // Test min()\n StdOut.println(\"\\nMin key: \" + multiset.min() + \" Expected: 0\");\n\n // Test max()\n StdOut.println(\"Max key: \" + multiset.max() + \" Expected: 24\");\n\n // Test floor()\n StdOut.println(\"Floor of 5: \" + multiset.floor(5) + \" Expected: 5\");\n StdOut.println(\"Floor of 15: \" + multiset.floor(15) + \" Expected: 8\");\n\n // Test ceiling()\n StdOut.println(\"Ceiling of 5: \" + multiset.ceiling(5) + \" Expected: 5\");\n StdOut.println(\"Ceiling of 15: \" + multiset.ceiling(15) + \" Expected: 20\");\n\n // Test select()\n StdOut.println(\"Select key of rank 3: \" + multiset.select(3) + \" Expected: 0\");\n StdOut.println(\"Select key of rank 4: \" + multiset.select(4) + \" Expected: 5\");\n\n // Test rank()\n // Note that the expected rank of key 8 is 7 and not 6, because we are assuming that rank returns the index\n // of the rightmost key when there are duplicates\n StdOut.println(\"Rank of key 8: \" + multiset.rank(8) + \" Expected: 7\");\n StdOut.println(\"Rank of key 9: \" + multiset.rank(9) + \" Expected: 8\");\n\n // Test delete()\n StdOut.println(\"\\nDelete key 20\");\n multiset.delete(20);\n\n for (Integer key : multiset.keys()) {\n StdOut.print(key + \" \");\n }\n StdOut.println(\"\\nKeys size: \" + multiset.size() + \" Expected: 12\");\n\n StdOut.println(\"\\nDelete key 5\");\n multiset.delete(5);\n\n for (Integer key : multiset.keys()) {\n StdOut.print(key + \" \");\n }\n StdOut.println(\"\\nKeys size: \" + multiset.size() + \" Expected: 10\");\n\n // Test deleteMin()\n StdOut.println(\"\\nDelete min (key 0)\");\n multiset.deleteMin();\n\n for (Integer key : multiset.keys()) {\n StdOut.print(key + \" \");\n }\n StdOut.println(\"\\nKeys size: \" + multiset.size() + \" Expected: 6\");\n\n // Test deleteMax()\n StdOut.println(\"\\nDelete max (key 24)\");\n multiset.deleteMax();\n\n for (Integer key : multiset.keys()) {\n StdOut.print(key + \" \");\n }\n StdOut.println(\"\\nKeys size: \" + multiset.size() + \" Expected: 5\");\n\n // Test keys() with range\n StdOut.println(\"\\nKeys in range [2, 10]\");\n for (Integer key : multiset.keys(2, 10)) {\n StdOut.print(key + \" \");\n }\n\n StdOut.println(\"\\n\\nKeys in range [20, 22]\");\n for (Integer key : multiset.keys(20, 22)) {\n StdOut.print(key + \" \");\n }\n\n // Delete all\n StdOut.println(\"\\n\\nDelete all\");\n while (multiset.size() > 0) {\n for (Integer key : multiset.keys()) {\n StdOut.print(key + \" \");\n }\n // multiset.delete(multiset.select(0));\n multiset.delete(multiset.select(multiset.size() - 1));\n StdOut.println();\n }\n }\n}\n", "support_files": [], "metadata": {"number": "3.5.11", "chapter": 3, "chapter_title": "Searching", "section": 3.5, "section_title": "Applications", "type": "Exercise", "code_execution": false}} {"question": "Modify LookupCSV to make a program RangeLookupCSV that takes two key values from the standard input and prints all key-value pairs in the .csv file such that the key falls within the range specified.", "answer": "package chapter3.section5;\n\nimport chapter3.section3.RedBlackBST;\nimport edu.princeton.cs.algs4.In;\nimport edu.princeton.cs.algs4.StdIn;\nimport edu.princeton.cs.algs4.StdOut;\nimport util.Constants;\n\n/**\n * Created by Rene Argento on 06/08/17.\n */\npublic class RangeLookupCSV {\n\n // Parameters example: 0: csv_file.txt\n // 1: 0\n // 2: 1\n\n // Queries: arnold fzkey\n // rachel wrong\n\n // Output expected:\n // arnold 200\n // dijkstra 10\n // dwayne 201\n // fenwick 202\n //\n // rene 5\n // sedgewick 9\n // wayne 10\n\n private void rangeLookupCSV(String[] args) {\n String filePath = Constants.FILES_PATH + args[0];\n\n In in = new In(filePath);\n int keyField = Integer.parseInt(args[1]);\n int valueField = Integer.parseInt(args[2]);\n\n RedBlackBST symbolTable = new RedBlackBST<>();\n\n while (in.hasNextLine()) {\n String line = in.readLine();\n String[] tokens = line.split(\",\");\n String key = tokens[keyField];\n String value = tokens[valueField];\n\n symbolTable.put(key, value);\n }\n\n while (!StdIn.isEmpty()) {\n String queryKey1 = StdIn.readString();\n String queryKey2 = StdIn.readString();\n\n for (String key : symbolTable.keys(queryKey1, queryKey2)) {\n StdOut.println(key + \" \" + symbolTable.get(key));\n }\n StdOut.println();\n }\n }\n\n public static void main(String[] args) {\n new Exercise13().rangeLookupCSV(args);\n }\n}\n", "support_files": [], "metadata": {"number": "3.5.13", "chapter": 3, "chapter_title": "Searching", "section": 3.5, "section_title": "Applications", "type": "Exercise", "code_execution": false}} {"question": "Develop and test a static method invert() that takes as argument an ST> and produces as return value the inverse of the given symbol table (a symbol table of the same type).", "answer": "package chapter3.section5;\n\nimport chapter1.section3.Bag;\nimport chapter3.section3.RedBlackBST;\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 06/08/17.\n */\npublic class Exercise14 {\n\n private static RedBlackBST> invert(RedBlackBST> symbolTable) {\n RedBlackBST> inverseSymbolTable = new RedBlackBST<>();\n\n for (String key : symbolTable.keys()) {\n Bag values = symbolTable.get(key);\n\n for (String newKey : values) {\n if (!inverseSymbolTable.contains(newKey)) {\n inverseSymbolTable.put(newKey, new Bag<>());\n }\n inverseSymbolTable.get(newKey).add(key);\n }\n }\n\n return inverseSymbolTable;\n }\n\n public static void main(String[] args) {\n RedBlackBST> redBlackBST = new RedBlackBST<>();\n Bag colorsBag = new Bag<>();\n colorsBag.add(\"red\");\n colorsBag.add(\"green\");\n colorsBag.add(\"blue\");\n redBlackBST.put(\"Colors\", colorsBag);\n\n Bag sortsBag = new Bag<>();\n sortsBag.add(\"mergesort\");\n sortsBag.add(\"quicksort\");\n sortsBag.add(\"heapsort\");\n redBlackBST.put(\"Sorts\", sortsBag);\n\n Bag mixedBag = new Bag<>();\n mixedBag.add(\"mergesort\");\n mixedBag.add(\"blue\");\n mixedBag.add(\"algorithms\");\n redBlackBST.put(\"Mixed Bag\", mixedBag);\n\n RedBlackBST> inverseSymbolTable = Exercise14.invert(redBlackBST);\n for (String key : inverseSymbolTable.keys()) {\n StdOut.println(key);\n\n for (String value : inverseSymbolTable.get(key)) {\n StdOut.println(\" \" + value);\n }\n }\n\n // Test\n StdOut.println(\"\\nTests\");\n StdOut.println(\"\\nred key\");\n for (String value : inverseSymbolTable.get(\"red\")) {\n StdOut.println(value);\n }\n StdOut.println(\"Expected: \\nColors\");\n\n StdOut.println(\"\\nblue key\");\n for (String value : inverseSymbolTable.get(\"blue\")) {\n StdOut.println(value);\n }\n StdOut.println(\"Expected: \\nMixed Bag\\nColors\");\n\n StdOut.println(\"\\nquicksort key\");\n for (String value : inverseSymbolTable.get(\"quicksort\")) {\n StdOut.println(value);\n }\n StdOut.println(\"Expected: \\nSorts\");\n\n StdOut.println(\"\\nmergesort key\");\n for (String value : inverseSymbolTable.get(\"mergesort\")) {\n StdOut.println(value);\n }\n StdOut.println(\"Expected: \\nSorts\\nMixed Bag\");\n }\n}\n", "support_files": [], "metadata": {"number": "3.5.14", "chapter": 3, "chapter_title": "Searching", "section": 3.5, "section_title": "Applications", "type": "Exercise", "code_execution": false}} {"question": "Write a program that takes a string on standard input and an integer k as command-line argument and puts on standard output a sorted list of the k-grams found in the string, each followed by its index in the string.", "answer": "Use a symbol table from each k-gram to all positions where it appears; a plain `ST` loses duplicate k-grams.\n\n```java\nimport edu.princeton.cs.algs4.Queue;\nimport edu.princeton.cs.algs4.RedBlackBST;\nimport edu.princeton.cs.algs4.StdIn;\nimport edu.princeton.cs.algs4.StdOut;\n\npublic class KGrams {\n public static void main(String[] args) {\n int k = Integer.parseInt(args[0]);\n String s = StdIn.readAll();\n RedBlackBST> st = new RedBlackBST<>();\n\n for (int i = 0; i <= s.length() - k; i++) {\n String gram = s.substring(i, i + k);\n if (!st.contains(gram)) st.put(gram, new Queue());\n st.get(gram).enqueue(i);\n }\n\n for (String gram : st.keys()) {\n for (int index : st.get(gram)) {\n StdOut.println(gram + \" \" + index);\n }\n }\n }\n}\n```", "support_files": [], "metadata": {"number": "3.5.15", "chapter": 3, "chapter_title": "Searching", "section": 3.5, "section_title": "Applications", "type": "Exercise", "code_execution": false}} {"question": "Multisets. After referring to Exercises 3.5.2 and 3.5.3 and the previous exercise, develop APIs MultiHashSET and MultiSET for multisets (sets that can have equal keys) and implementations SeparateChainingMultiSET and BinarySearchMultiSET for multisets and ordered multisets, respectively.", "answer": "package chapter3.section5;\n\nimport edu.princeton.cs.algs4.Queue;\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.NoSuchElementException;\n\n/**\n * Created by Rene Argento on 07/08/17.\n */\n@SuppressWarnings(\"unchecked\")\npublic class Exercise18_Multisets {\n\n /**\n * API for MultiHashSET\n *\n * public class MultiHashSET\n * MultiHashSET() create an empty set\n * void add(Key key) add key into the set\n * void delete(Key key) remove all keys equal to key from the set\n * boolean contains(Key key) is key in the set?\n * boolean isEmpty() is the set empty?\n * int size() number of keys in the set\n * Iterable keys() all the keys in the set\n * String toString() string representation of the set\n */\n\n private interface MultiHashSET {\n void add(Key key);\n void delete(Key key);\n boolean contains(Key key);\n boolean isEmpty();\n int size();\n Iterable keys();\n String toString();\n }\n\n /**\n * API for MultiSET\n *\n * public class MultiSET\n * MultiSET() create an empty set\n * void add(Key key) add key into the set\n * void delete(Key key) remove all keys equal to key from the set\n * boolean contains(Key key) is key in the set?\n * boolean isEmpty() is the set empty?\n * int size() number of keys in the set\n * Key min() smallest key\n * Key max() largest key\n * Key floor(Key key) largest key less than or equal to key\n * Key ceiling(Key key) smallest key greater than or equal to key\n * int rankFirst(Key key) number of keys less than key (or less than the first key, in case of duplicates)\n * int rankLast(Key key) number of keys less than key (or less than the last key, in case of duplicates)\n * Key select(int k) key of rank k\n * void deleteMin() delete all keys equal to the smallest key\n * void deleteMax() delete all keys equal to the largest key\n * int size(Key low, Key high) number of keys in [low..high] (includes all duplicates)\n * Iterable keys(Key low, Key high) keys in [low..high], in sorted order\n * Iterable keys() all the keys in the set, in sorted order\n * String toString() string representation of the set\n */\n\n private interface MultiSET {\n void add(Key key);\n void delete(Key key);\n boolean contains(Key key);\n boolean isEmpty();\n int size();\n Key min();\n Key max();\n Key floor(Key key);\n Key ceiling(Key key);\n int rankFirst(Key key);\n int rankLast(Key key);\n Key select(int k);\n void deleteMin();\n void deleteMax();\n int size(Key low, Key high);\n Iterable keys(Key low, Key high);\n Iterable keys();\n String toString();\n }\n\n public class SeparateChainingMultiSET implements MultiHashSET {\n\n private class SequentialSearchSymbolTable {\n\n private class Node {\n Key key;\n Node next;\n\n public Node(Key key, Node next) {\n this.key = key;\n this.next = next;\n }\n }\n\n private Node first;\n private int size;\n\n public int size() {\n return size;\n }\n\n public boolean isEmpty() {\n return size == 0;\n }\n\n public boolean contains(Key key) {\n for (Node node = first; node != null; node = node.next) {\n if (key.equals(node.key)) {\n return true;\n }\n }\n\n return false;\n }\n\n public void add(Key key) {\n first = new Node(key, first);\n size++;\n }\n\n public void delete(Key key) {\n if (first.key.equals(key)) {\n first = first.next;\n size--;\n return;\n }\n\n for (Node node = first; node != null; node = node.next) {\n if (node.next != null && node.next.key.equals(key)) {\n node.next = node.next.next;\n size--;\n return;\n }\n }\n }\n\n public Iterable keys() {\n Queue keys = new Queue<>();\n\n for (Node node = first; node != null; node = node.next) {\n keys.enqueue(node.key);\n }\n\n return keys;\n }\n\n }\n\n private int averageListSize;\n\n private int size;\n private int keysSize;\n private SequentialSearchSymbolTable[] symbolTable;\n\n private static final int DEFAULT_HASH_TABLE_SIZE = 997;\n private static final int DEFAULT_AVERAGE_LIST_SIZE = 5;\n\n // The largest prime <= 2^i for i = 1 to 31\n // Used to distribute keys uniformly in the hash table after resizes\n // PRIMES[n] = 2^k - Ak where k is the power of 2 and Ak is the value to subtract to reach the previous prime number\n private final int[] PRIMES = {\n 1, 1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381,\n 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301,\n 8388593, 16777213, 33554393, 67108859, 134217689, 268435399,\n 536870909, 1073741789, 2147483647\n };\n\n // The lg of the hash table size\n // Used in combination with PRIMES[] to distribute keys uniformly in the hash function after resizes\n private int lgM;\n\n public SeparateChainingMultiSET() {\n this(DEFAULT_HASH_TABLE_SIZE, DEFAULT_AVERAGE_LIST_SIZE);\n }\n\n public SeparateChainingMultiSET(int initialSize, int averageListSize) {\n this.size = initialSize;\n this.averageListSize = averageListSize;\n symbolTable = new SequentialSearchSymbolTable[size];\n\n for (int i = 0; i < size; i++) {\n symbolTable[i] = new SequentialSearchSymbolTable<>();\n }\n\n lgM = (int) (Math.log(size) / Math.log(2));\n }\n\n public int size() {\n return keysSize;\n }\n\n public boolean isEmpty() {\n return keysSize == 0;\n }\n\n private int hash(Key key) {\n int hash = key.hashCode() & 0x7fffffff;\n\n if (lgM < 26) {\n hash = hash % PRIMES[lgM + 5];\n }\n return hash % size;\n }\n\n private double getLoadFactor() {\n return ((double) keysSize) / (double) size;\n }\n\n public boolean contains(Key key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Argument to contains() cannot be null\");\n }\n return symbolTable[hash(key)].contains(key);\n }\n\n private void resize(int newSize) {\n SeparateChainingMultiSET separateChainingMultiSET = new SeparateChainingMultiSET<>(newSize, averageListSize);\n\n for (Key key : keys()) {\n separateChainingMultiSET.add(key);\n }\n symbolTable = separateChainingMultiSET.symbolTable;\n size = separateChainingMultiSET.size;\n }\n\n public void add(Key key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n int hashIndex = hash(key);\n symbolTable[hashIndex].add(key);\n keysSize++;\n\n if (getLoadFactor() > averageListSize) {\n resize(size * 2);\n lgM++;\n }\n }\n\n public void delete(Key key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Argument to delete() cannot be null\");\n }\n\n if (isEmpty() || !contains(key)) {\n return;\n }\n\n while (contains(key)) {\n symbolTable[hash(key)].delete(key);\n keysSize--;\n\n if (size > 1 && getLoadFactor() <= averageListSize / (double) 4) {\n resize(size / 2);\n lgM--;\n }\n }\n }\n\n public Iterable keys() {\n Queue keys = new Queue<>();\n\n for (SequentialSearchSymbolTable sequentialSearchST : symbolTable) {\n for (Key key : sequentialSearchST.keys()) {\n keys.enqueue(key);\n }\n }\n return keys;\n }\n\n @Override\n public String toString() {\n if (isEmpty()) {\n return \"{ }\";\n }\n\n StringBuilder stringBuilder = new StringBuilder(\"{\");\n\n boolean isFirstKey = true;\n for (Key key : keys()) {\n if (isFirstKey) {\n isFirstKey = false;\n } else {\n stringBuilder.append(\",\");\n }\n\n stringBuilder.append(\" \").append(key);\n }\n\n stringBuilder.append(\" }\");\n return stringBuilder.toString();\n }\n }\n\n public class BinarySearchMultiSET> implements MultiSET {\n private Key[] keys;\n private int size;\n\n private static final int DEFAULT_INITIAL_CAPACITY = 2;\n\n public BinarySearchMultiSET() {\n keys = (Key[]) new Comparable[DEFAULT_INITIAL_CAPACITY];\n }\n\n public BinarySearchMultiSET(int capacity) {\n keys = (Key[]) new Comparable[capacity];\n }\n\n public int size() {\n return size;\n }\n\n public boolean isEmpty() {\n return size == 0;\n }\n\n public boolean contains(Key key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Argument to contains() cannot be null\");\n }\n\n if (isEmpty()) {\n return false;\n }\n\n int rank = rankLast(key);\n if (rank < size && keys[rank].compareTo(key) == 0) {\n return true;\n } else {\n return false;\n }\n }\n\n public int rankFirst(Key key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n int low = 0;\n int high = size - 1;\n\n int rankFound = -1;\n\n while (low <= high) {\n int middle = low + (high - low) / 2;\n\n int comparison = key.compareTo(keys[middle]);\n if (comparison < 0) {\n high = middle - 1;\n } else if (comparison > 0) {\n low = middle + 1;\n } else {\n rankFound = middle;\n high = middle - 1;\n }\n }\n\n if (rankFound != -1) {\n return rankFound;\n } else {\n return low;\n }\n }\n\n public int rankLast(Key key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n int low = 0;\n int high = size - 1;\n\n int rankFound = -1;\n\n while (low <= high) {\n int middle = low + (high - low) / 2;\n\n int comparison = key.compareTo(keys[middle]);\n if (comparison < 0) {\n high = middle - 1;\n } else if (comparison > 0) {\n low = middle + 1;\n } else {\n rankFound = middle;\n low = middle + 1;\n }\n }\n\n if (rankFound != -1) {\n return rankFound;\n } else {\n return low;\n }\n }\n\n public void add(Key key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n if (size == keys.length) {\n resize(keys.length * 2);\n }\n\n int rank = rankLast(key);\n\n for (int i = size; i > rank; i--) {\n keys[i] = keys[i - 1];\n }\n keys[rank] = key;\n size++;\n }\n\n public void delete(Key key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Argument to delete() cannot be null\");\n }\n\n if (isEmpty() || !contains(key)) {\n return;\n }\n\n while (contains(key)) {\n int rank = rankLast(key);\n for (int i = rank; i < size - 1; i++) {\n keys[i] = keys[i + 1];\n }\n\n keys[size - 1] = null;\n size--;\n\n if (size > 1 && size == keys.length / 4) {\n resize(keys.length / 2);\n }\n }\n }\n\n public Key min() {\n if (isEmpty()) {\n throw new NoSuchElementException(\"Empty symbol table\");\n }\n return keys[0];\n }\n\n public Key max() {\n if (isEmpty()) {\n throw new NoSuchElementException(\"Empty symbol table\");\n }\n return keys[size - 1];\n }\n\n public Key select(int k) {\n if (isEmpty() || k >= size) {\n throw new IllegalArgumentException(\"Index \" + k + \" is higher than size\");\n }\n return keys[k];\n }\n\n public Key ceiling(Key key) {\n int rank = rankLast(key);\n\n if (rank == size) {\n return null;\n }\n return keys[rank];\n }\n\n public Key floor(Key key) {\n if (contains(key)) {\n return key;\n }\n\n int rank = rankLast(key);\n\n if (rank == 0) {\n return null;\n }\n return keys[rank - 1];\n }\n\n public void deleteMin() {\n if (isEmpty()) {\n throw new NoSuchElementException(\"Multiset is empty\");\n }\n\n Key minKey = min();\n\n while (contains(minKey)) {\n delete(minKey);\n }\n }\n\n public void deleteMax() {\n if (isEmpty()) {\n throw new NoSuchElementException(\"Multiset is empty\");\n }\n\n Key maxKey = max();\n\n while (contains(maxKey)) {\n delete(maxKey);\n }\n }\n\n public int size(Key low, Key high) {\n if (low == null || high == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n if (high.compareTo(low) < 0) {\n return 0;\n } else if (contains(high)) {\n return rankLast(high) - rankFirst(low) + 1;\n } else {\n return rankLast(high) - rankFirst(low);\n }\n }\n\n public Iterable keys(Key low, Key high) {\n if (low == null || high == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n Queue queue = new Queue<>();\n\n for (int i = rankFirst(low); i < rankLast(high); i++) {\n queue.enqueue(keys[i]);\n }\n\n if (contains(high)) {\n queue.enqueue(keys[rankLast(high)]);\n }\n return queue;\n }\n\n public Iterable keys() {\n return keys(min(), max());\n }\n\n private void resize(int newSize) {\n Key[] tempKeys = (Key[]) new Comparable[newSize];\n System.arraycopy(keys, 0, tempKeys, 0, size);\n keys = tempKeys;\n }\n\n @Override\n public String toString() {\n if (isEmpty()) {\n return \"{ }\";\n }\n\n StringBuilder stringBuilder = new StringBuilder(\"{\");\n\n boolean isFirstKey = true;\n for (Key key : keys()) {\n if (isFirstKey) {\n isFirstKey = false;\n } else {\n stringBuilder.append(\",\");\n }\n\n stringBuilder.append(\" \").append(key);\n }\n\n stringBuilder.append(\" }\");\n return stringBuilder.toString();\n }\n }\n\n public static void main(String[] args) {\n Exercise18_Multisets multisets = new Exercise18_Multisets();\n multisets.testSeparateChainingMultiSET();\n multisets.testBinarySearchMultiSET();\n }\n\n private void testSeparateChainingMultiSET() {\n StdOut.println(\"*********** SeparateChainingMultiSET tests ***********\");\n MultiHashSET separateChainingMultiSET = new SeparateChainingMultiSET<>();\n\n // Test isEmpty()\n StdOut.println(\"\\nIsEmpty: \" + separateChainingMultiSET.isEmpty() + \" Expected: true\");\n\n // Test add()\n separateChainingMultiSET.add(0);\n separateChainingMultiSET.add(0);\n separateChainingMultiSET.add(0);\n separateChainingMultiSET.add(0);\n\n separateChainingMultiSET.add(5);\n separateChainingMultiSET.add(5);\n\n separateChainingMultiSET.add(8);\n separateChainingMultiSET.add(8);\n\n separateChainingMultiSET.add(20);\n separateChainingMultiSET.add(20);\n separateChainingMultiSET.add(20);\n separateChainingMultiSET.add(20);\n\n separateChainingMultiSET.add(21);\n separateChainingMultiSET.add(22);\n separateChainingMultiSET.add(23);\n separateChainingMultiSET.add(24);\n\n // Test keys()\n StdOut.println(\"\\nKeys() test\");\n\n for (Integer key : separateChainingMultiSET.keys()) {\n StdOut.print(key + \" \");\n }\n StdOut.println(\"\\nExpected: 0 0 0 0 5 5 8 8 20 20 20 20 21 22 23 24 - Not necessarily in this order\");\n\n // Test size()\n StdOut.println(\"\\nKeys size: \" + separateChainingMultiSET.size() + \" Expected: 16\");\n\n StdOut.println(\"\\ntoString() test: \" + separateChainingMultiSET);\n\n // Test contains()\n StdOut.println(\"\\nContains 0: \" + separateChainingMultiSET.contains(0) + \" Expected: true\");\n StdOut.println(\"Contains 100: \" + separateChainingMultiSET.contains(100) + \" Expected: false\");\n\n // Test delete()\n StdOut.println(\"\\nDelete key 5\");\n separateChainingMultiSET.delete(5);\n StdOut.println(separateChainingMultiSET);\n\n StdOut.println(\"\\nDelete key 24\");\n separateChainingMultiSET.delete(24);\n StdOut.println(separateChainingMultiSET);\n\n StdOut.println(\"\\nDelete key 0\");\n separateChainingMultiSET.delete(0);\n StdOut.println(separateChainingMultiSET);\n\n StdOut.println(\"\\nKeys size: \" + separateChainingMultiSET.size() + \" Expected: 9\");\n StdOut.println(\"\\nIsEmpty: \" + separateChainingMultiSET.isEmpty() + \" Expected: false\");\n }\n\n private void testBinarySearchMultiSET() {\n StdOut.println(\"\\n\\n*********** BinarySearchMultiSET tests ***********\");\n MultiSET binarySearchMultiSET = new BinarySearchMultiSET<>();\n\n // Test isEmpty()\n StdOut.println(\"\\nIsEmpty: \" + binarySearchMultiSET.isEmpty() + \" Expected: true\");\n\n // Test add()\n binarySearchMultiSET.add(0);\n binarySearchMultiSET.add(0);\n binarySearchMultiSET.add(0);\n binarySearchMultiSET.add(0);\n\n binarySearchMultiSET.add(5);\n binarySearchMultiSET.add(5);\n\n binarySearchMultiSET.add(8);\n binarySearchMultiSET.add(8);\n\n binarySearchMultiSET.add(20);\n binarySearchMultiSET.add(20);\n binarySearchMultiSET.add(20);\n binarySearchMultiSET.add(20);\n\n binarySearchMultiSET.add(21);\n binarySearchMultiSET.add(22);\n binarySearchMultiSET.add(23);\n binarySearchMultiSET.add(24);\n\n // Test keys()\n StdOut.println(\"\\nKeys() test\");\n for (Integer key : binarySearchMultiSET.keys()) {\n StdOut.print(key + \" \");\n }\n StdOut.println(\"\\nExpected: 0 0 0 0 5 5 8 8 20 20 20 20 21 22 23 24\");\n\n // Test size()\n StdOut.println(\"\\nKeys size: \" + binarySearchMultiSET.size() + \" Expected: 16\");\n\n // Test size() with range\n StdOut.println(\"Keys size [0, 20]: \" + binarySearchMultiSET.size(0, 20) + \" Expected: 12\");\n\n // Test contains()\n StdOut.println(\"\\nContains 8: \" + binarySearchMultiSET.contains(8) + \" Expected: true\");\n StdOut.println(\"Contains 9: \" + binarySearchMultiSET.contains(9) + \" Expected: false\");\n\n // Test min()\n StdOut.println(\"\\nMin key: \" + binarySearchMultiSET.min() + \" Expected: 0\");\n\n // Test max()\n StdOut.println(\"Max key: \" + binarySearchMultiSET.max() + \" Expected: 24\");\n\n // Test floor()\n StdOut.println(\"Floor of 5: \" + binarySearchMultiSET.floor(5) + \" Expected: 5\");\n StdOut.println(\"Floor of 15: \" + binarySearchMultiSET.floor(15) + \" Expected: 8\");\n\n // Test ceiling()\n StdOut.println(\"Ceiling of 5: \" + binarySearchMultiSET.ceiling(5) + \" Expected: 5\");\n StdOut.println(\"Ceiling of 15: \" + binarySearchMultiSET.ceiling(15) + \" Expected: 20\");\n\n // Test select()\n StdOut.println(\"Select key of rank 3: \" + binarySearchMultiSET.select(3) + \" Expected: 0\");\n StdOut.println(\"Select key of rank 4: \" + binarySearchMultiSET.select(4) + \" Expected: 5\");\n\n // Test rank()\n StdOut.println(\"RankFirst of key 8: \" + binarySearchMultiSET.rankFirst(8) + \" Expected: 6\");\n StdOut.println(\"RankFirst of key 9: \" + binarySearchMultiSET.rankFirst(9) + \" Expected: 8\");\n StdOut.println(\"RankLast of key 9: \" + binarySearchMultiSET.rankLast(9) + \" Expected: 8\");\n StdOut.println(\"RankFirst of key 20: \" + binarySearchMultiSET.rankFirst(20) + \" Expected: 8\");\n StdOut.println(\"RankLast of key 20: \" + binarySearchMultiSET.rankLast(20) + \" Expected: 11\");\n\n // Test delete()\n StdOut.println(\"\\nDelete key 20\");\n binarySearchMultiSET.delete(20);\n\n // Test toString()\n StdOut.println(binarySearchMultiSET);\n StdOut.println(\"\\nKeys size: \" + binarySearchMultiSET.size() + \" Expected: 12\");\n\n StdOut.println(\"\\nDelete key 5\");\n binarySearchMultiSET.delete(5);\n\n StdOut.println(binarySearchMultiSET);\n StdOut.println(\"\\nKeys size: \" + binarySearchMultiSET.size() + \" Expected: 10\");\n\n // Test deleteMin()\n StdOut.println(\"\\nDelete min (key 0)\");\n binarySearchMultiSET.deleteMin();\n\n StdOut.println(binarySearchMultiSET);\n StdOut.println(\"\\nKeys size: \" + binarySearchMultiSET.size() + \" Expected: 6\");\n\n // Test deleteMax()\n StdOut.println(\"\\nDelete max (key 24)\");\n binarySearchMultiSET.deleteMax();\n\n StdOut.println(binarySearchMultiSET);\n StdOut.println(\"\\nKeys size: \" + binarySearchMultiSET.size() + \" Expected: 5\");\n\n // Test keys() with range\n StdOut.println(\"\\nKeys in range [2, 10]\");\n for (Integer key : binarySearchMultiSET.keys(2, 10)) {\n StdOut.print(key + \" \");\n }\n\n StdOut.println(\"\\n\\nKeys in range [20, 22]\");\n for (Integer key : binarySearchMultiSET.keys(20, 22)) {\n StdOut.print(key + \" \");\n }\n\n StdOut.println(\"\\n\\nIsEmpty: \" + binarySearchMultiSET.isEmpty() + \" Expected: false\");\n\n // Delete all\n StdOut.println(\"\\nDelete all\");\n while (binarySearchMultiSET.size() > 0) {\n StdOut.println(binarySearchMultiSET);\n // binarySearchMultiSET.delete(binarySearchMultiSET.select(0));\n binarySearchMultiSET.delete(binarySearchMultiSET.select(binarySearchMultiSET.size() - 1));\n }\n StdOut.println(binarySearchMultiSET);\n }\n}\n", "support_files": [], "metadata": {"number": "3.5.18", "chapter": 3, "chapter_title": "Searching", "section": 3.5, "section_title": "Applications", "type": "Creative Problem", "code_execution": false}} {"question": "Concordance. Write an ST client Concordance that puts on standard output a concordance of the strings in the standard input stream (see page 498).", "answer": "package chapter3.section5;\n\nimport edu.princeton.cs.algs4.StdIn;\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\n/**\n * Created by Rene Argento on 08/08/17.\n */\npublic class Concordance {\n\n private class Concordance {\n\n private Map> readInputAndBuildConcordance() {\n int wordIndex = 0;\n Map> concordanceMap = new HashMap<>();\n\n while (StdIn.hasNextLine()) {\n String wordLine = StdIn.readLine();\n String[] words = wordLine.split(\" \");\n\n for (String word : words) {\n if (!concordanceMap.containsKey(word)) {\n concordanceMap.put(word, new ArrayList<>());\n }\n concordanceMap.get(word).add(wordIndex);\n\n wordIndex++;\n }\n }\n return concordanceMap;\n }\n\n private void outputConcordance(Map> concordance) {\n for (String word : concordance.keySet()) {\n StdOut.print(word);\n boolean isFirstValue = true;\n\n for (Integer positionInText : concordance.get(word)) {\n if (isFirstValue) {\n isFirstValue = false;\n } else {\n StdOut.print(\",\");\n }\n\n StdOut.print(\" \" + positionInText);\n }\n StdOut.println();\n }\n }\n }\n\n public static void main(String[] args) {\n // Test\n // This is a text to test a concordance.\n // The text has many words. This is a good test.\n //\n // Expected output (not necessarily in this order)\n // This 0, 13\n // is 1, 14\n // a 2, 6, 15\n // text 3, 9\n // to 4\n // test 5\n // concordance. 7\n // The 8\n // has 10\n // many 11\n // words. 12\n // good 16\n // test. 17\n\n Exercise20_Concordance exercise20_concordance = new Exercise20_Concordance();\n Concordance concordance = exercise20_concordance.new Concordance();\n Map> concordanceMap = concordance.readInputAndBuildConcordance();\n concordance.outputConcordance(concordanceMap);\n }\n}\n", "support_files": [], "metadata": {"number": "3.5.20", "chapter": 3, "chapter_title": "Searching", "section": 3.5, "section_title": "Applications", "type": "Creative Problem", "code_execution": false}} {"question": "Inverted concordance. Write a program InvertedConcordance that takes a concordance on standard input and puts the original string on standard output stream. Note: This computation is associated with a famous story having to do with the Dead Sea Scrolls. The team that discovered the original tablets enforced a secrecy rule that essentially resulted in their making public only a concordance. After a while, other researchers figured out how to invert the concordance, and the full text was eventually made public.", "answer": "package chapter3.section5;\n\nimport edu.princeton.cs.algs4.StdIn;\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\n/**\n * Created by Rene Argento on 08/08/17.\n */\npublic class InvertedConcordance {\n\n private class InvertedConcordance {\n\n int numberOfWords = 0;\n\n private Map> readConcordanceFromInput() {\n Map> concordanceMap = new HashMap<>();\n\n while (StdIn.hasNextLine()) {\n String concordanceLine = StdIn.readLine();\n String[] concordanceInformation = concordanceLine.split(\" \");\n\n String key = concordanceInformation[0];\n concordanceMap.put(key, new ArrayList<>());\n\n for (int i = 1; i < concordanceInformation.length; i++) {\n String noCommaValue = concordanceInformation[i];\n\n if (noCommaValue.charAt(noCommaValue.length() - 1) == ',') {\n noCommaValue = noCommaValue.substring(0, noCommaValue.length() - 1);\n }\n\n int position = Integer.parseInt(noCommaValue);\n concordanceMap.get(key).add(position);\n\n if (position > numberOfWords) {\n numberOfWords = position;\n }\n }\n }\n\n return concordanceMap;\n }\n\n private String buildTextFromConcordance(Map> concordance) {\n String[] wordsInText = new String[numberOfWords + 1];\n\n for (String word : concordance.keySet()) {\n for (int position : concordance.get(word)) {\n wordsInText[position] = word;\n }\n }\n\n StringBuilder text = new StringBuilder();\n boolean isFirstWord = true;\n\n for (String word : wordsInText) {\n if (isFirstWord) {\n isFirstWord = false;\n } else {\n text.append(\" \");\n }\n\n text.append(word);\n }\n\n return text.toString();\n }\n\n }\n\n public static void main(String[] args) {\n // Test\n // This 0, 13\n // is 1, 14\n // a 2, 6, 15\n // text 3, 9\n // to 4\n // test 5\n // concordance. 7\n // The 8\n // has 10\n // many 11\n // words. 12\n // good 16\n // test. 17\n //\n // Expected output\n // This is a text to test a concordance. The text has many words. This is a good test.\n\n Exercise21_InvertedConcordance exercise21_invertedConcordance = new Exercise21_InvertedConcordance();\n InvertedConcordance invertedConcordance = exercise21_invertedConcordance.new InvertedConcordance();\n\n Map> concordance = invertedConcordance.readConcordanceFromInput();\n String text = invertedConcordance.buildTextFromConcordance(concordance);\n StdOut.println(text);\n }\n}\n", "support_files": [], "metadata": {"number": "3.5.21", "chapter": 3, "chapter_title": "Searching", "section": 3.5, "section_title": "Applications", "type": "Creative Problem", "code_execution": false}} {"question": "Sparse matrices. Develop an API and an implementation for sparse 2D matrices. Support matrix addition and matrix multiplication. Include constructors for row and column vectors.", "answer": "package chapter3.section5;\n\nimport chapter3.section4.SeparateChainingHashTable;\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 15/08/17.\n */\npublic class Exercise23_SparseMatrices {\n\n private interface SparseMatrixAPI {\n SparseMatrix sum(SparseMatrix sparseMatrix);\n SparseMatrix dot(SparseMatrix sparseMatrix);\n void put(int row, int column, double value);\n double get(int row, int column);\n void delete(int row, int column);\n }\n\n public class SparseVector {\n\n private int dimension;\n private SeparateChainingHashTable hashTable;\n\n public SparseVector(int dimension) {\n hashTable = new SeparateChainingHashTable<>();\n this.dimension = dimension;\n }\n\n public int size() {\n return hashTable.size();\n }\n\n public void put(int key, double value) {\n hashTable.put(key, value);\n }\n\n public double get(int key) {\n if (!hashTable.contains(key)) {\n return 0;\n } else {\n return hashTable.get(key);\n }\n }\n\n public void delete(int key) {\n hashTable.delete(key);\n }\n\n public SparseVector plus(SparseVector sparseVector) {\n if (dimension != sparseVector.dimension) {\n throw new IllegalArgumentException(\"Sparse vector dimensions must be the same.\");\n }\n\n SparseVector result = new SparseVector(dimension);\n\n // Copy values\n for (int key : hashTable.keys()) {\n result.put(key, get(key));\n }\n // Sum values\n for (int key : sparseVector.hashTable.keys()) {\n double sum = get(key) + sparseVector.get(key);\n\n if (sum != 0) {\n result.put(key, sum);\n } else {\n result.delete(key);\n }\n }\n\n return result;\n }\n\n public double dot(SparseVector sparseVector) {\n if (dimension != sparseVector.dimension) {\n throw new IllegalArgumentException(\"Sparse vector dimensions must be the same.\");\n }\n\n double sum = 0;\n\n // Iterate over the vector with the fewest nonzeros\n if (size() <= sparseVector.size()) {\n for (int key : hashTable.keys()) {\n if (sparseVector.hashTable.contains(key)) {\n sum += get(key) * sparseVector.get(key);\n }\n }\n } else {\n for (int key : sparseVector.hashTable.keys()) {\n if (hashTable.contains(key)) {\n sum += get(key) * sparseVector.get(key);\n }\n }\n }\n\n return sum;\n }\n\n public double dot(double[] that) {\n double sum = 0.0;\n\n for (int key : hashTable.keys()) {\n sum += this.get(key) * that[key];\n }\n\n return sum;\n }\n\n public String toString() {\n StringBuilder stringBuilder = new StringBuilder();\n\n for (int key : hashTable.keys()) {\n stringBuilder.append(\"(\").append(key).append(\", \").append(get(key)).append(\") \");\n }\n\n return stringBuilder.toString();\n }\n }\n\n public class SparseMatrix implements SparseMatrixAPI {\n\n private int rowSize;\n private int columnSize;\n private SparseVector[] rows;\n private SparseVector[] columns;\n\n SparseMatrix(SparseVector[] rows, SparseVector[] columns, int rowSize, int columnSize) {\n this.rows = rows;\n this.columns = columns;\n\n this.rowSize = rowSize;\n this.columnSize = columnSize;\n }\n\n SparseMatrix(int rowSize, int columnSize) {\n this.rowSize = rowSize;\n this.columnSize = columnSize;\n\n rows = new SparseVector[rowSize];\n for (int i = 0; i < rows.length; i++) {\n rows[i] = new SparseVector(columnSize);\n }\n\n columns = new SparseVector[columnSize];\n for (int i = 0; i < columns.length; i++) {\n columns[i] = new SparseVector(rowSize);\n }\n }\n\n @Override\n public double get(int row, int column) {\n if (row < 0 || row >= rowSize) {\n throw new IllegalArgumentException(\"Invalid row index\");\n }\n if (column < 0 || column >= columnSize) {\n throw new IllegalArgumentException(\"Invalid column index\");\n }\n\n return rows[row].get(column);\n }\n\n @Override\n public void put(int row, int column, double value) {\n if (row < 0 || row >= rowSize) {\n throw new IllegalArgumentException(\"Invalid row index\");\n }\n if (column < 0 || column >= columnSize) {\n throw new IllegalArgumentException(\"Invalid column index\");\n }\n\n if (value == 0) {\n delete(row, column);\n return;\n }\n\n rows[row].put(column, value);\n columns[column].put(row, value);\n }\n\n @Override\n public void delete(int row, int column) {\n if (row < 0 || row >= rowSize) {\n throw new IllegalArgumentException(\"Invalid row index\");\n }\n if (column < 0 || column >= columnSize) {\n throw new IllegalArgumentException(\"Invalid column index\");\n }\n\n rows[row].delete(column);\n columns[column].delete(row);\n }\n\n @Override\n public SparseMatrix sum(SparseMatrix sparseMatrix) {\n if (rowSize != sparseMatrix.rowSize || columnSize != sparseMatrix.columnSize) {\n throw new IllegalArgumentException(\"Matrix A rows and columns number and Matrix B rows and columns \" +\n \"number must match\");\n }\n\n SparseMatrix result = new SparseMatrix(rowSize, columnSize);\n\n for (int i = 0; i < result.rowSize; i++) {\n result.rows[i] = rows[i].plus(sparseMatrix.rows[i]);\n for (int column : result.rows[i].hashTable.keys()) {\n result.columns[column].put(i, result.rows[i].get(column));\n }\n }\n\n return result;\n }\n\n @Override\n public SparseMatrix dot(SparseMatrix sparseMatrix) {\n if (columnSize != sparseMatrix.rowSize) {\n throw new IllegalArgumentException(\"Matrix A columns number and Matrix B rows number must match\");\n }\n\n SparseMatrix result = new SparseMatrix(rowSize, sparseMatrix.columnSize);\n\n for (int i = 0; i < rows.length; i++) {\n for (int j = 0; j < sparseMatrix.columnSize; j++) {\n double dot = rows[i].dot(sparseMatrix.columns[j]);\n\n if (dot != 0) {\n result.put(i, j, dot);\n }\n }\n }\n\n return result;\n }\n\n public String toString() {\n StringBuilder stringBuilder = new StringBuilder(\"rows = \" + rowSize + \", columns = \" + columnSize + \"\\n\");\n\n for (int row = 0; row < rowSize; row++) {\n stringBuilder.append(row).append(\": \").append(rows[row]).append(\"\\n\");\n }\n return stringBuilder.toString();\n }\n }\n\n public static void main(String[] args) {\n Exercise23_SparseMatrices sparseMatrices = new Exercise23_SparseMatrices();\n\n //Matrix A\n // 1 0\n // 7 2\n\n //Matrix B\n // -4 -5\n // 2 1\n\n //Matrix C\n // 3 4 2\n // 1 0 3\n\n //Matrix D\n // 0 0 0\n // 0 2 0\n\n //Matrix A + Matrix B\n // -3 -5\n // 9 3\n\n //Matrix A x Matrix C\n // 3 4 2\n // 23 28 20\n\n //Matrix B x Matrix C\n // -17 -16 -23\n // 7 8 7\n\n //Matrix C + Matrix D\n // 3 4 2\n // 1 2 3\n\n //Matrix A x Matrix D\n // 0 0 0\n // 0 4 0\n\n //Matrix B x Matrix D\n // 0 -10 0\n // 0 2 0\n\n SparseMatrix sparseMatrixA = sparseMatrices.new SparseMatrix(2, 2);\n SparseMatrix sparseMatrixB = sparseMatrices.new SparseMatrix(2, 2);\n SparseMatrix sparseMatrixC = sparseMatrices.new SparseMatrix(2, 3);\n SparseMatrix sparseMatrixD = sparseMatrices.new SparseMatrix(2, 3);\n\n sparseMatrixA.put(0, 0, 1);\n sparseMatrixA.put(1, 0, 7);\n sparseMatrixA.put(1, 1, 2);\n\n sparseMatrixB.put(0, 0, -4);\n sparseMatrixB.put(0, 1, -5);\n sparseMatrixB.put(1, 0, 2);\n sparseMatrixB.put(1, 1, 1);\n\n sparseMatrixC.put(0, 0, 3);\n sparseMatrixC.put(0, 1, 4);\n sparseMatrixC.put(0, 2, 2);\n sparseMatrixC.put(1, 0, 1);\n sparseMatrixC.put(1, 2, 3);\n\n sparseMatrixD.put(1, 1, 2);\n\n StdOut.println(\"Matrix A + Matrix B\");\n SparseMatrix sparseMatrixAPlusB = sparseMatrixA.sum(sparseMatrixB);\n StdOut.println(sparseMatrixAPlusB);\n StdOut.println(\"Expected:\\n\" +\n \"rows = 2, columns = 2\\n\" +\n \"0: (0, -3.0) (1, -5.0) \\n\" +\n \"1: (0, 9.0) (1, 3.0) \\n\");\n\n StdOut.println(\"Matrix A x Matrix C\");\n SparseMatrix sparseMatrixADotC = sparseMatrixA.dot(sparseMatrixC);\n StdOut.println(sparseMatrixADotC);\n StdOut.println(\"Expected:\\n\" +\n \"rows = 2, columns = 3\\n\" +\n \"0: (0, 3.0) (1, 4.0) (2, 2.0) \\n\" +\n \"1: (0, 23.0) (1, 28.0) (2, 20.0) \\n\");\n\n StdOut.println(\"Matrix B x Matrix C\");\n SparseMatrix sparseMatrixBDotC = sparseMatrixB.dot(sparseMatrixC);\n StdOut.println(sparseMatrixBDotC);\n StdOut.println(\"Expected:\\n\" +\n \"rows = 2, columns = 3\\n\" +\n \"0: (0, -17.0) (1, -16.0) (2, -23.0) \\n\" +\n \"1: (0, 7.0) (1, 8.0) (2, 7.0) \\n\");\n\n StdOut.println(\"Matrix C + Matrix D\");\n SparseMatrix sparseMatrixCPlusD = sparseMatrixC.sum(sparseMatrixD);\n StdOut.println(sparseMatrixCPlusD);\n StdOut.println(\"Expected:\\n\" +\n \"rows = 2, columns = 3\\n\" +\n \"0: (0, 3.0) (1, 4.0) (2, 2.0) \\n\" +\n \"1: (0, 1.0) (1, 2.0) (2, 3.0) \\n\");\n\n StdOut.println(\"Matrix A x Matrix D\");\n SparseMatrix sparseMatrixADotD = sparseMatrixA.dot(sparseMatrixD);\n StdOut.println(sparseMatrixADotD);\n StdOut.println(\"Expected:\\n\" +\n \"rows = 2, columns = 3\\n\" +\n \"0: \\n\" +\n \"1: (1, 4.0) \\n\");\n\n StdOut.println(\"Matrix B x Matrix D\");\n SparseMatrix sparseMatrixBDotD = sparseMatrixB.dot(sparseMatrixD);\n StdOut.println(sparseMatrixBDotD);\n StdOut.println(\"Expected:\\n\" +\n \"rows = 2, columns = 3\\n\" +\n \"0: (1, -10.0) \\n\" +\n \"1: (1, 2.0)\");\n }\n}\n", "support_files": [], "metadata": {"number": "3.5.23", "chapter": 3, "chapter_title": "Searching", "section": 3.5, "section_title": "Applications", "type": "Creative Problem", "code_execution": false}} {"question": "List. Develop an implementation of the following API:\npublic class List implements Iterable\n List() create a list\n void addFront(Item item) add item to the front\n void addBack(Item item) add item to the back\n Item deleteFront() remove from the front\n Item deleteBack() remove from the back\n void delete(Item item) remove item from the list\n void add(int i, Item item) add item as the ith in the list\n Item delete(int i) remove the ith item from the list\n boolean contains(Item item) is key in the list?\n boolean isEmpty() is the list empty?\n int size() number of items in the list\nHint: Use two symbol tables, one to find the ith item in the list efficiently, and the other to efficiently search by item. (Java’s java.util.List interface contains methods like these but does not supply any implementation that efficiently supports all operations.)", "answer": "package chapter3.section5;\n\nimport chapter3.section3.RedBlackBST;\nimport chapter3.section4.SeparateChainingHashTable;\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.Queue;\n\n/**\n * Created by Rene Argento on 17/08/17.\n */\npublic class Exercise27_List {\n\n public class List implements Iterable {\n\n private RedBlackBST itemsBST;\n private SeparateChainingHashTable itemsPositions;\n\n private static final double INITIAL_VALUE = 50000;\n private static final double OFFSET = 0.0001;;\n\n List() {\n itemsBST = new RedBlackBST<>();\n itemsPositions = new SeparateChainingHashTable<>();\n }\n\n //O(lg n)\n public void addFront(Item item) {\n if (item == null) {\n throw new IllegalArgumentException(\"Item cannot be null\");\n }\n\n if (contains(item)) {\n delete(item);\n }\n\n double minKey;\n\n if (isEmpty()) {\n minKey = INITIAL_VALUE;\n } else {\n minKey = itemsBST.min();\n }\n\n double newMinKey = minKey - OFFSET;\n\n itemsBST.put(newMinKey, item);\n itemsPositions.put(item, newMinKey);\n }\n\n //O(lg n)\n public void addBack(Item item) {\n if (item == null) {\n throw new IllegalArgumentException(\"Item cannot be null\");\n }\n\n if (contains(item)) {\n delete(item);\n }\n\n double maxKey;\n\n if (isEmpty()) {\n maxKey = INITIAL_VALUE;\n } else {\n maxKey = itemsBST.max();\n }\n\n double newMaxKey = maxKey + OFFSET;\n\n itemsBST.put(newMaxKey, item);\n itemsPositions.put(item, newMaxKey);\n }\n\n //O(lg n)\n public Item deleteFront() {\n if (isEmpty()) {\n return null;\n }\n\n Item firstItem = itemsBST.get(itemsBST.min());\n\n itemsBST.deleteMin();\n itemsPositions.delete(firstItem);\n\n return firstItem;\n }\n\n //O(lg n)\n public Item deleteBack() {\n if (isEmpty()) {\n return null;\n }\n\n Item lastItem = itemsBST.get(itemsBST.max());\n\n itemsBST.deleteMax();\n itemsPositions.delete(lastItem);\n\n return lastItem;\n }\n\n //O(lg n)\n public void delete(Item item) {\n if (item == null) {\n throw new IllegalArgumentException(\"Item cannot be null\");\n }\n\n if (!contains(item)) {\n return;\n }\n\n double itemPosition = itemsPositions.get(item);\n itemsBST.delete(itemPosition);\n itemsPositions.delete(item);\n }\n\n //O(lg n)\n public void add(int index, Item item) {\n if (item == null) {\n throw new IllegalArgumentException(\"Item cannot be null\");\n }\n\n if (index < 0 || index > size()\n || (index == size() && contains(item))) {\n throw new IllegalArgumentException(\"Invalid index\");\n }\n\n if (contains(item)) {\n delete(item);\n }\n\n double previousItemIndex = 0;\n double nextItemIndex = size() - 1;\n\n if (index > 0) {\n previousItemIndex = itemsBST.select(index - 1);\n } else if (index == 0) {\n previousItemIndex = itemsBST.min() - OFFSET;\n }\n\n if (index < size()) {\n nextItemIndex = itemsBST.select(index);\n } else if (index == size()) {\n nextItemIndex = itemsBST.max() + OFFSET;\n }\n\n double medianKey = (previousItemIndex + nextItemIndex) / 2;\n\n itemsBST.put(medianKey, item);\n itemsPositions.put(item, medianKey);\n }\n\n //O(lg n)\n public Item delete(int index) {\n if (index < 0 || index >= size()) {\n throw new IllegalArgumentException(\"Invalid index\");\n }\n\n Item deletedItem = itemsBST.get(itemsBST.select(index));\n delete(deletedItem);\n return deletedItem;\n }\n\n //O(1)\n public boolean contains(Item item) {\n return itemsPositions.contains(item);\n }\n\n //O(1)\n public boolean isEmpty() {\n return size() == 0;\n }\n\n //O(1)\n public int size() {\n return itemsPositions.size();\n }\n\n @Override\n public Iterator iterator() {\n return new ListIterator();\n }\n\n //O(n)\n private class ListIterator implements Iterator {\n\n Queue keys;\n\n ListIterator() {\n keys = new LinkedList<>();\n\n for (Double key : itemsBST.keys()) {\n keys.add(key);\n }\n }\n\n @Override\n public boolean hasNext() {\n return keys.size() > 0;\n }\n\n @Override\n public Item next() {\n return itemsBST.get(keys.poll());\n }\n }\n\n }\n\n public static void main(String[] args) {\n Exercise27_List exercise27_list = new Exercise27_List();\n List list = exercise27_list.new List<>();\n\n StdOut.println(\"Add item 1 to the front of the list\");\n //Test addFront() and addBack()\n list.addFront(1);\n StdOut.println(\"Add item 0 to the front of the list\");\n list.addFront(0);\n StdOut.println(\"Add item 10 to the back of the list\");\n list.addBack(10);\n StdOut.println(\"Add item 11 to the back of the list\");\n list.addBack(11);\n\n //Test size()\n StdOut.println(\"\\nSize: \" + list.size() + \" Expected: 4\");\n\n //Test isEmpty()\n StdOut.println(\"isEmpty: \" + list.isEmpty() + \" Expected: false\\n\");\n\n //Test iterator\n for (int item : list) {\n StdOut.print(item + \" \");\n }\n StdOut.println(\"\\nExpected: 0 1 10 11\");\n\n //Test add()\n StdOut.println(\"\\nAdd item 9 on index 2\");\n list.add(2, 9);\n\n for (int item : list) {\n StdOut.print(item + \" \");\n }\n StdOut.println(\"\\nExpected: 0 1 9 10 11\");\n\n StdOut.println(\"\\nAdd item -1 on index 0\");\n list.add(0, -1);\n\n for (int item : list) {\n StdOut.print(item + \" \");\n }\n StdOut.println(\"\\nExpected: -1 0 1 9 10 11\");\n\n //Test deleteFront()\n StdOut.println(\"\\nDelete front\");\n list.deleteFront();\n\n for (int item : list) {\n StdOut.print(item + \" \");\n }\n StdOut.println(\"\\nExpected: 0 1 9 10 11\");\n\n //Test deleteBack()\n StdOut.println(\"\\nDelete back\");\n list.deleteBack();\n\n for (int item : list) {\n StdOut.print(item + \" \");\n }\n StdOut.println(\"\\nExpected: 0 1 9 10\");\n\n //Test delete(int index)\n StdOut.println(\"\\nDelete item on index 2\");\n list.delete(2);\n\n for (int item : list) {\n StdOut.print(item + \" \");\n }\n StdOut.println(\"\\nExpected: 0 1 10\");\n\n StdOut.println(\"\\nDelete item on index 0\");\n list.delete(0);\n\n for (int item : list) {\n StdOut.print(item + \" \");\n }\n StdOut.println(\"\\nExpected: 1 10\");\n\n //Test delete(Item item)\n StdOut.println(\"\\nDelete item 5\");\n list.delete(new Integer(5));\n\n for (int item : list) {\n StdOut.print(item + \" \");\n }\n StdOut.println(\"\\nExpected: 1 10\");\n\n StdOut.println(\"\\nDelete item 10\");\n list.delete(new Integer(10));\n\n for (int item : list) {\n StdOut.print(item + \" \");\n }\n StdOut.println(\"\\nExpected: 1\");\n\n StdOut.println(\"\\nDelete front\");\n list.deleteFront();\n StdOut.println(\"isEmpty: \" + list.isEmpty() + \" Expected: true\");\n }\n}\n", "support_files": [], "metadata": {"number": "3.5.27", "chapter": 3, "chapter_title": "Searching", "section": 3.5, "section_title": "Applications", "type": "Creative Problem", "code_execution": false}} {"question": "What is the maximum number of edges in a graph with V vertices and no parallel edges? What is the minimum number of edges in a graph with V vertices, none of which are isolated?", "answer": "The maximum number of edges in a simple undirected graph with `V` vertices is\n\n`V(V - 1) / 2`.\n\nIf no vertex may be isolated, the minimum number of edges is `ceil(V / 2)`, not `V - 1`: pair up vertices with one edge per pair, and when `V` is odd use two edges to connect the last three vertices as a path.", "support_files": [], "metadata": {"number": "4.1.1", "chapter": 4, "chapter_title": "Graphs", "section": 4.1, "section_title": "Undirected Graphs", "type": "Exercise", "code_execution": false}} {"question": "Draw, in the style of the figure in the text (page 524), the adjacency lists built by Graph’s input stream constructor for the file tinyGex2.txt depicted at left.", "answer": "4.1.2\n\nadj[]\n 0 -> 5 -> 2 -> 6\n 1 -> 4 -> 8 -> 11\n 2 -> 5 -> 6 -> 0 -> 3\n 3 -> 10 -> 6 -> 2\n 4 -> 1 -> 8\n 5 -> 0 -> 10 -> 2\n 6 -> 2 -> 3 -> 0\n 7 -> 8 -> 11\n 8 -> 1 -> 11 -> 7 -> 4\n 9 -> \n 10 -> 5 -> 3\n 11 -> 8 -> 7 -> 1\n", "support_files": [], "metadata": {"number": "4.1.2", "chapter": 4, "chapter_title": "Graphs", "section": 4.1, "section_title": "Undirected Graphs", "type": "Exercise", "code_execution": false}} {"question": "Consider the four-vertex graph with edges 0-1, 1-2, 2-3, and 3-0. Draw an array of adjacency-lists that could not have been built calling addEdge() for these edges no matter what order.", "answer": "4.1.6\n\nThe edges form a cycle, so changing the connection order of one of the vertices' adjacency list creates an impossible sequence of connections.\n\nadj[]\n 0 -> 1 -> 3 (the original was 0 -> 3 -> 1)\n 1 -> 2 -> 0\n 2 -> 3 -> 1\n 3 -> 0 -> 2\n", "support_files": [], "metadata": {"number": "4.1.6", "chapter": 4, "chapter_title": "Graphs", "section": 4.1, "section_title": "Undirected Graphs", "type": "Exercise", "code_execution": false}} {"question": "Show, in the style of the figure on page 533, a detailed trace of the call dfs(0) for the graph built by Graph’s input stream constructor for the file tinyGex2.txt (see Exercise 4.1.2). Also, draw the tree represented by edgeTo[].", "answer": "4.1.9\n marked[] adj[]\ndfs (0) 0 T 0 5 2 6\n 1 1 4 8 11\n 2 2 5 6 0 3\n 3 3 10 6 2 \n 4 4 1 8 \n 5 5 0 10 2\n 6 6 2 3 0\n 7 7 8 11\n 8 8 1 11 7 4\n 9 9 \n 10 10 5 3\n 11 11 8 7 1\n\n dfs (5) 0 T 0 5 2 6\n check 0 1 1 4 8 11\n 2 2 5 6 0 3\n 3 3 10 6 2 \n 4 4 1 8 \n 5 T 5 0 10 2\n 6 6 2 3 0\n 7 7 8 11\n 8 8 1 11 7 4\n 9 9 \n 10 10 5 3\n 11 11 8 7 1\n\n dfs (10) 0 T 0 5 2 6\n check 5 1 1 4 8 11\n 2 2 5 6 0 3\n 3 3 10 6 2 \n 4 4 1 8 \n 5 T 5 0 10 2\n 6 6 2 3 0\n 7 7 8 11\n 8 8 1 11 7 4\n 9 9 \n 10 T 10 5 3\n 11 11 8 7 1\n\n dfs (3) 0 T 0 5 2 6\n check 10 1 1 4 8 11\n 2 2 5 6 0 3\n 3 T 3 10 6 2 \n 4 4 1 8 \n 5 T 5 0 10 2\n 6 6 2 3 0\n 7 7 8 11\n 8 8 1 11 7 4\n 9 9 \n 10 T 10 5 3\n 11 11 8 7 1\n\n dfs (6) 0 T 0 5 2 6\n 1 1 4 8 11\n 2 2 5 6 0 3\n 3 T 3 10 6 2 \n 4 4 1 8 \n 5 T 5 0 10 2\n 6 T 6 2 3 0\n 7 7 8 11\n 8 8 1 11 7 4\n 9 9 \n 10 T 10 5 3\n 11 11 8 7 1\n\n dfs (2) 0 T 0 5 2 6\n check 5 1 1 4 8 11\n check 6 2 T 2 5 6 0 3\n check 0 3 T 3 10 6 2 \n check 3 4 4 1 8 \n 2 done 5 T 5 0 10 2\n 6 T 6 2 3 0\n 7 7 8 11\n 8 8 1 11 7 4\n 9 9 \n 10 T 10 5 3\n 11 11 8 7 1\n check 3\n check 0\n 6 done\n check 2\n 3 done\n 10 done\n check 2\n 5 done\n check 2\n check 6\n0 done\n\nedgeTo[] tree\n \n 0\n 5\n 10\n 3\n 6\n 2\n", "support_files": [], "metadata": {"number": "4.1.9", "chapter": 4, "chapter_title": "Graphs", "section": 4.1, "section_title": "Undirected Graphs", "type": "Exercise", "code_execution": false}} {"question": "Prove that every connected graph has a vertex whose removal (including all adjacent edges) will not disconnect the graph, and write a DFS method that finds such a vertex. Hint: Consider a vertex whose adjacent vertices are all marked.", "answer": "Every connected graph has at least one vertex whose removal does not disconnect the graph: take any DFS tree and choose a leaf of that DFS tree. Removing a leaf from a tree leaves the tree connected on the remaining vertices; since the original graph contains at least the DFS-tree edges, the original graph with that leaf removed is also connected.\n\nA DFS method can record the last vertex discovered. The last discovered vertex has no unmarked adjacent vertex when its call finishes, so it is a DFS-tree leaf and can be removed.\n\n```java\nprivate boolean[] marked;\nprivate int removable;\n\npublic int removableVertex(Graph g) {\n marked = new boolean[g.V()];\n removable = 0;\n dfs(g, 0);\n return removable;\n}\n\nprivate void dfs(Graph g, int v) {\n marked[v] = true;\n removable = v;\n for (int w : g.adj(v)) {\n if (!marked[w]) dfs(g, w);\n }\n}\n```", "support_files": [], "metadata": {"number": "4.1.10", "chapter": 4, "chapter_title": "Graphs", "section": 4.1, "section_title": "Undirected Graphs", "type": "Exercise", "code_execution": false}} {"question": "Draw the tree represented by edgeTo[] after the call bfs(G, 0) in ALGORITHM 4.2 for the graph built by Graph’s input stream constructor for the file tinyGex2.txt (see Exercise 4.1.2).", "answer": "4.1.11\n\nTree represented by edgeTo[] after call to bfs(G, 0):\n\n 0\n 5 2 6\n 10 3\n", "support_files": [], "metadata": {"number": "4.1.11", "chapter": 4, "chapter_title": "Graphs", "section": 4.1, "section_title": "Undirected Graphs", "type": "Exercise", "code_execution": false}} {"question": "What does the BFS tree tell us about the distance from v to w when neither is at the root?", "answer": "The BFS tree gives exact shortest-path distances only from the root to every vertex. If neither `v` nor `w` is the root, the distance between them in the BFS tree is just the length of one particular `v-w` path, hence an upper bound on their true graph distance. The graph may contain a shorter path using edges that are not in the BFS tree.", "support_files": [], "metadata": {"number": "4.1.12", "chapter": 4, "chapter_title": "Graphs", "section": 4.1, "section_title": "Undirected Graphs", "type": "Exercise", "code_execution": false}} {"question": "Suppose you use a stack instead of a queue when running breadth-first search. Does it still compute shortest paths?", "answer": "4.1.14\n\nIf we use a stack instead of a queue when running breadth-first search, it may not compute shortest paths.\nThis can be seen in the following graph:\n\n 0 (source)\n / \\\n1 - 2\n| |\n4 - 3\n\nIf the edge 0 - 2 is inserted before the edge 0 - 1:\nUsing a stack, the distance from 0 to 4 will be 3.\nUsing a queue, the distance from 0 to 4 will be 2.\n\nIf the edge 0 - 1 is inserted before the edge 0 - 2:\nUsing a stack, the distance from 0 to 3 will be 3.\nUsing a queue, the distance from 0 to 3 will be 2.\n\nThanks to lemonadeseason (https://github.com/lemonadeseason) for correcting the example in this exercise.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/24\n", "support_files": [], "metadata": {"number": "4.1.14", "chapter": 4, "chapter_title": "Graphs", "section": 4.1, "section_title": "Undirected Graphs", "type": "Exercise", "code_execution": false}} {"question": "Show, in the style of the figure on page 545, a detailed trace of CC for finding the connected components in the graph built by Graph’s input stream constructor for the file tinyGex2.txt (see EXERCISE 4.1.2).", "answer": "4.1.19\n count marked[] id[]\n 0 1 2 3 4 5 6 7 8 9 10 11 0 1 2 3 4 5 6 7 8 9 10 11\ndfs(0) 0 T 0\n dfs(5) 0 T T 0 0\n check 0\n dfs(10) 0 T T T 0 0 0\n check 5\n dfs(3) 0 T T T T 0 0 0 0\n check 10\n dfs(6) 0 T T T T T 0 0 0 0 0\n dfs(2) 0 T T T T T T 0 0 0 0 0 0\n check 5\n check 6\n check 0\n check 3\n 2 done\n check 3\n check 0\n 6 done\n check 2\n 3 done\n 10 done\n check 2\n 5 done\n check 2\n check 6\n0 done\ndfs(1) 1 T T T T T T T 0 1 0 0 0 0 0\n dfs(4) 1 T T T T T T T T 0 1 0 0 1 0 0 0\n check 1\n dfs(8) 1 T T T T T T T T T 0 1 0 0 1 0 0 1 0\n check 1\n dfs(11) 1 T T T T T T T T T T 0 1 0 0 1 0 0 1 0 1\n check 8\n dfs(7) 1 T T T T T T T T T T T 0 1 0 0 1 0 0 1 1 0 1\n check 8\n check 11\n 7 done\n check 1\n 11 done\n check 7\n check 4\n 8 done\n 4 done\n check 8\n check 11\n1 done\ndfs(9) 2 T T T T T T T T T T T T 0 1 0 0 1 0 0 1 1 2 0 1\n9 done\n", "support_files": [], "metadata": {"number": "4.1.19", "chapter": 4, "chapter_title": "Graphs", "section": 4.1, "section_title": "Undirected Graphs", "type": "Exercise", "code_execution": false}} {"question": "Show, in the style of the figures in this section, a detailed trace of Cycle for finding a cycle in the graph built by Graph’s input stream constructor for the file tinyGex2.txt (see EXERCISE 4.1.2). What is the order of growth of the running time of the Cycle constructor, in the worst case?", "answer": "4.1.20\n Has Cycle? marked[] \n F 0 1 2 3 4 5 6 7 8 9 10 11 \ndfs(0) T \n dfs(5) T T \n check 0 F\n dfs(10) T T T \n check 5 F\n dfs(3) T T T T \n check 10 F\n dfs(6) T T T T T \n dfs(2) T T T T T T \n check 5 T (cycle found here)\n check 6 T\n check 0 T\n check 3 T\n 2 done\n check 3 T\n check 0 T\n 6 done\n check 2 T\n 3 done\n 10 done\n check 2 T\n 5 done\n check 2 T\n check 6 T\n0 done\ndfs(1) T T T T T T T \n dfs(4) T T T T T T T T \n check 1 T\n dfs(8) T T T T T T T T T \n check 1 T\n dfs(11) T T T T T T T T T T \n check 8 T\n dfs(7) T T T T T T T T T T T \n check 8 T\n check 11 T\n 7 done\n check 1 T\n 11 done\n check 7 T\n check 4 T\n 8 done\n 4 done\n check 8 T\n check 11 T\n1 done\ndfs(9) T T T T T T T T T T T T\n9 done\n\nThe order of growth of the running time of the Cycle constructor, in the worst case is O(V + E).\nEach adjacency-list entry is examined exactly once, and there are 2 * E such entries (two for each edge); initializing the marked[] array takes time proportional to V.\n", "support_files": [], "metadata": {"number": "4.1.20", "chapter": 4, "chapter_title": "Graphs", "section": 4.1, "section_title": "Undirected Graphs", "type": "Exercise", "code_execution": false}} {"question": "Show, in the style of the figures in this section, a detailed trace of TwoColor for finding a two-coloring of the graph built by Graph’s input stream constructor for the file tinyGex2.txt (see EXERCISE 4.1.2). What is the order of growth of the running time of the TwoColor constructor, in the worst case?", "answer": "4.1.21\n Is 2-colorable? marked[] color[]\n T 0 1 2 3 4 5 6 7 8 9 10 11 0 1 2 3 4 5 6 7 8 9 10 11\ndfs(0) T F F F F F F F F F F F F\n dfs(5) T T F F F F F T F F F F F F\n check 0 T\n dfs(10) T T T F F F F F T F F F F F F\n check 5 T\n dfs(3) T T T T F F F T F T F F F F F F\n check 10 T\n dfs(6) T T T T T F F F T F T F F F F F F\n dfs(2) T T T T T T F F T T F T F F F F F F\n check 5 F\n check 6 F\n check 0 F\n check 3 F\n 2 done\n check 3 F\n check 0 F\n 6 done\n check 2 F\n 3 done\n 10 done\n check 2 F\n 5 done\n check 2 F\n check 6 F\n0 done\ndfs(1) T T T T T T T F F T T F T F F F F F F\n dfs(4) T T T T T T T T F F T T T T F F F F F F\n check 1 F\n dfs(8) T T T T T T T T T F F T T F T F F F F F F\n check 1 F\n dfs(11) T T T T T T T T T T F F T T F T F F F F F T\n check 8 F\n dfs(7) T T T T T T T T T T T F F T T F T F F F F F F\n check 8 F\n check 11 F\n 7 done\n check 1 F\n 11 done\n check 7 F\n check 4 F\n 8 done\n 4 done\n check 8 F\n check 11 F\n1 done\ndfs(9) T T T T T T T T T T T T F F T T F T F F F F F F\n9 done\n\nThe order of growth of the running time of the TwoColor constructor, in the worst case is O(V + E).\nEach adjacency-list entry is examined exactly once, and there are 2 * E such entries (two for each edge); initializing the marked[] and color[] arrays takes time proportional to V.\n", "support_files": [], "metadata": {"number": "4.1.21", "chapter": 4, "chapter_title": "Graphs", "section": 4.1, "section_title": "Undirected Graphs", "type": "Exercise", "code_execution": false}} {"question": "Compute the number of connected components in movies.txt, the size of the largest component, and the number of components of size less than 10. Find the eccentricity, diameter, radius, a center, and the girth of the largest component in the graph. Does it contain Kevin Bacon?", "answer": "4.1.24\n\nNumber of connected components: 33\nSize of the largest component: 118774\nNumber of components of size less than 10: 5\nDoes the largest component contain Kevin Bacon: Yes\n\nEccentricity, diameter, radius, center and girth:\n\nThe strategy for computing the eccentricity, diameter, radius, center and girth of the largest component was the following:\nThe algorithm required for these exact computations has complexity of O(V * E) (running breadth-first search from all vertices). V is ~= 10^5, which means the algorithm required for these exact computation has complexity ~= 10^10.\n\nIn order to reduce the complexity of the computations (and to be able to compute them), domain knowledge was used to compute approximate results.\nBased on the Kevin Bacon game, we know that Kevin Bacon has been on several movies and that he is closely connected to most of the actors and actresses in the graph. Therefore, he has a high probability of being the center of the graph.\n\nUsing Kevin Bacon as the center, we compute his vertex eccentricity to get the graph radius.\nA breadth-first search using Kevin Bacon as the source computes the vertices that are furthest from the center. Computing the eccentricities of these vertices we can find the diameter of the graph.\n\nThe eccentricities of the center and of the vertices furthest from it are shown in the results. The range of the eccentricities is [10, 18]. Computing the eccentricities of all vertices would bring us back to the original problem of =~ 10^10 operations.\n\nFinally, for the girth, we know that there is a very high probability that two actors have worked together on two different movies. This gives a girth of 4, which is the minimum girth possible for the movies graph:\nActor -- Movie -- Actor\n \\ /\n \\ Movie /\nTo validate this theory we run the algorithm to compute the girth of the graph but stop once we find a cycle of length 4, since it is the shortest cycle possible.\n\n\nEccentricities of Kevin Bacon and of vertices furthest from the center in the largest component:\nEccentricity of vertex 22970: 16\nEccentricity of vertex 22971: 16\nEccentricity of vertex 22972: 16\nEccentricity of vertex 22973: 16\nEccentricity of vertex 22974: 16\nEccentricity of vertex 22976: 16\nEccentricity of vertex 22977: 16\nEccentricity of vertex 22978: 16\nEccentricity of vertex 22979: 16\nEccentricity of vertex 22980: 16\nEccentricity of vertex 51437: 18\nEccentricity of vertex 51438: 18\nEccentricity of vertex 51439: 18\nEccentricity of vertex 51440: 18\nEccentricity of vertex 51441: 18\nEccentricity of vertex 51442: 18\nEccentricity of vertex 51443: 18\nEccentricity of vertex 51444: 18\nEccentricity of vertex 51445: 18\nEccentricity of vertex 51446: 18\nEccentricity of vertex 51447: 18\nEccentricity of vertex 51448: 18\nEccentricity of vertex 51449: 18\nEccentricity of vertex 51450: 18\nEccentricity of vertex 51451: 18\nEccentricity of vertex 51452: 18\nEccentricity of vertex 51453: 18\nEccentricity of vertex 51454: 18\nEccentricity of vertex 51455: 18\nEccentricity of vertex 51456: 18\nEccentricity of vertex 51457: 18\nEccentricity of vertex 51458: 18\nEccentricity of vertex 51459: 18\nEccentricity of vertex 51460: 18\nEccentricity of vertex 51461: 18\nEccentricity of vertex 51462: 18\nEccentricity of vertex 51463: 18\nEccentricity of vertex 51464: 18\nEccentricity of vertex 51465: 18\nEccentricity of vertex 51466: 18\nEccentricity of vertex 51467: 18\nEccentricity of vertex 51468: 18\nEccentricity of vertex 51469: 18\nEccentricity of vertex 51470: 18\nEccentricity of vertex 51471: 18\nEccentricity of vertex 51472: 18\nEccentricity of vertex 51473: 18\nEccentricity of vertex 51474: 18\nEccentricity of vertex 51475: 18\nEccentricity of vertex 51476: 18\nEccentricity of vertex 51477: 18\nEccentricity of vertex 51478: 18\nEccentricity of vertex 51479: 18\nEccentricity of vertex 51480: 18\nEccentricity of vertex 51481: 18\nEccentricity of vertex 51482: 18\nEccentricity of vertex 51483: 18\nEccentricity of vertex 51484: 18\nEccentricity of vertex 51485: 18\nEccentricity of vertex 51486: 18\nEccentricity of vertex 51487: 18\nEccentricity of vertex 51488: 18\nEccentricity of vertex 51489: 18\nEccentricity of vertex 51490: 18\nEccentricity of vertex 51491: 18\nEccentricity of vertex 51492: 18\nEccentricity of vertex 51493: 18\nEccentricity of vertex 51494: 18\nEccentricity of vertex 51495: 18\nEccentricity of vertex 51496: 18\nEccentricity of vertex 51497: 18\nEccentricity of vertex 51498: 18\nEccentricity of vertex 51499: 18\nEccentricity of vertex 51500: 18\nEccentricity of vertex 51501: 18\nEccentricity of vertex 51502: 18\nEccentricity of vertex 51503: 18\nEccentricity of vertex 51504: 18\nEccentricity of vertex 51505: 18\nEccentricity of vertex 51506: 18\nEccentricity of vertex 51507: 18\nEccentricity of vertex 51508: 18\nEccentricity of vertex 51509: 18\nEccentricity of vertex 51510: 18\nEccentricity of vertex 51511: 18\nEccentricity of vertex 51512: 18\nEccentricity of vertex 51513: 18\nEccentricity of vertex 51514: 18\nEccentricity of vertex 51515: 18\nEccentricity of vertex 51516: 18\nEccentricity of vertex 51517: 18\nEccentricity of vertex 51518: 18\nEccentricity of vertex 51519: 18\nEccentricity of vertex 51520: 18\nEccentricity of vertex 86241: 16\nEccentricity of vertex 86242: 16\nEccentricity of vertex 86243: 16\nEccentricity of vertex 86244: 16\nEccentricity of vertex 86245: 16\nEccentricity of vertex 86246: 16\nEccentricity of vertex 86247: 16\nEccentricity of vertex 86248: 16\nEccentricity of vertex 86249: 16\nEccentricity of vertex 86250: 16\nEccentricity of vertex 86251: 16\nEccentricity of vertex 86252: 16\nEccentricity of vertex 86253: 16\nEccentricity of vertex 86254: 16\nEccentricity of vertex 86255: 16\nEccentricity of vertex 86256: 16\nEccentricity of vertex 86257: 16\nEccentricity of vertex 86258: 16\nEccentricity of vertex 86259: 16\nEccentricity of vertex 118353: 18\nEccentricity of vertex 118354: 18\nEccentricity of vertex 118355: 18\nEccentricity of vertex 118356: 18\nEccentricity of vertex 118357: 18\nEccentricity of vertex 118358: 18\nEccentricity of vertex 118359: 18\nEccentricity of vertex 118360: 18\nEccentricity of vertex 118361: 18\nEccentricity of vertex 118362: 18\nEccentricity of vertex 118363: 18\nEccentricity of vertex 118364: 18\nEccentricity of vertex 9145: 10\n\nDiameter of largest component: 18\nRadius of largest component: 10\nCenter of largest component: 9145\nGirth of largest component: 4\n", "support_files": [], "metadata": {"number": "4.1.24", "chapter": 4, "chapter_title": "Graphs", "section": 4.1, "section_title": "Undirected Graphs", "type": "Exercise", "code_execution": false}} {"question": "Determine the amount of memory used by Graph to represent a graph with V vertices and E edges, using the memory-cost model of SECTION 1.4.", "answer": "4.1.27\n\nInteger\n* object overhead -> 16 bytes\n* int value -> 4 bytes\n* padding -> 4 bytes\nAmount of memory needed: 16 + 4 + 4 = 24 bytes\n\nNode\n* object overhead -> 16 bytes\n* extra overhead for reference to the enclosing instance -> 8 bytes\n* Item reference (item) -> 8 bytes\n* Node reference (next) -> 8 bytes\nAmount of memory needed: 16 + 8 + 8 + 8 = 40 bytes\n\nBag\n* object overhead -> 16 bytes\n* Node reference (first) -> 8 bytes\n* int value (size) -> 4 bytes\n* padding -> 4 bytes\n* N Nodes -> 40N bytes\n* Integer (item) -> 24N bytes\nAmount of memory needed: 16 + 8 + 4 + 4 + 40N + 24N = 64N + 32 bytes\n\nGraph\n* object overhead -> 16 bytes\n* int value (V) -> 4 bytes\n* int value (E) -> 4 bytes\n* Bag[] reference (adj) -> 8 bytes\n* Bag[] (adj)\n object overhead -> 16 bytes\n int value (length) -> 4 bytes\n padding -> 4 bytes\n Bag references -> 8V\n Bag -> 64E + 32 bytes -> There are V Bags and in total, they have 2E nodes -> 128E + 32V\nAmount of memory needed: 16 + 4 + 4 + 8 + 16 + 4 + 4 + 8V + 128E + 32V = 128E + 40V + 56 bytes\n", "support_files": [], "metadata": {"number": "4.1.27", "chapter": 4, "chapter_title": "Graphs", "section": 4.1, "section_title": "Undirected Graphs", "type": "Exercise", "code_execution": false}} {"question": "Two graphs are isomorphic if there is a way to rename the vertices of one to make it identical to the other. Draw all the nonisomorphic graphs with two, three, four, and five vertices.", "answer": "4.1.28\n\nNon-isomorphic graphs:\n\nThere are 2 non-isomorphic graphs with 2 vertices:\no o\n\no-o\n\nThere are 4 non-isomorphic graphs with 3 vertices:\n o\no o\n\n o\no-o\n\no-o-o\n\n o\n/ \\\no-o\n\nThere are 11 non-isomorphic graphs with 4 vertices:\no o o o\n\no-o o o\n\no-o-o o\n\no-o-o-o\n\no-o o-o\n\n o\n |\n o\n / \\\no o\n\n o\n / \\\no---o o\n\no-o\n| |\no-o\n\n o\n | \n o\n / \\\no---o\n\n o\n / \\\no---o\n \\ /\n o\n\n o\n /|\\\n / o \\\n/ / \\ \\\no------o\n\nThere are 34 non-isomorphic graphs with 5 vertices:\n o\no o\n o o\n\n o\no o\n o-o\n\n o\no o\n /\n o-o\n\n o\no o\n \\ /\n o o\n\n o\n / | \\\no o o \n o\n\n o\n / \\\no o \n o-o\n\n o\n / \\\no o \n \\\n o o\n\n o\n / \\\no----o\n o o\n\n o\n /|\\\\\no o oo\n\no-o\n| |\no-o o\n\no\n|\no-o\n| |\no o\n\n o\n |\n o\n / \\\no---o o\n\no-o-o-o-o\n\n o o\n /| |\no | |\n \\| |\n o o\n\no--o\n| |\no--o\n|\no\n\no o\n| |\no---o\n \\ /\n o\n\n o--o\n \\/\no--o--o\n\n o\n / \\\no o \n \\ /\n o-o\n\n o (This is a complete graph, where all vertices have degree = 4)\n / / \\\\\no------o\n\\ /\\ /\\/\n \\|/\\ |/\n o---o\n\n o\n / / \\\\\no------o\n\\ /\\ /\\/\n \\|/\\ |/\n o o\n\no---o\n|\\ /|\\\n| X | o\n|/ \\|/\no---o\n\no---o\n|\\ /|\n| o |\n|/ \\|\no---o\n\no---o\n|\\ /|\\\n| X | o\n|/ \\|\no---o\n\n o\n // \\\no-o o\n \\/\n o\n\no-o-o-o\n \\| | /\n o\n\n o\n /\\\n / \\\n / \\\no------o\n\\ \\ / /\n \\ /\\ /\n o o\n\no---o\n| X | o\no---o\n\no o\n|\\ /|\n| o |\n|/ \\|\no o\n\n o\n /|\\\no--o | o\n \\|/\n o\n\n o\n |\n o\n /|\\\no | o\n \\|/\n o\n\n o\n / \\\no---o\n| |\no---o\n\no---o\n| /|\n| o |\n|/ |\no---o\n\n o\n |\n o\n |\n o\n / \\\no---o\n\no---o\n| \\ |\no---o o\n\nBased on: http://www.graphclasses.org/smallgraphs.html\n", "support_files": [], "metadata": {"number": "4.1.28", "chapter": 4, "chapter_title": "Graphs", "section": 4.1, "section_title": "Undirected Graphs", "type": "Exercise", "code_execution": false}} {"question": "Eulerian and Hamiltonian cycles. Consider the graphs defined by the following four sets of edges:\n0-1 0-2 0-3 1-3 1-4 2-5 2-9 3-6 4-7 4-8 5-8 5-9 6-7 6-9 7-8\n0-1 0-2 0-3 1-3 0-3 2-5 5-6 3-6 4-7 4-8 5-8 5-9 6-7 6-9 8-8\n0-1 1-2 1-3 0-3 0-4 2-5 2-9 3-6 4-7 4-8 5-8 5-9 6-7 6-9 7-8\n4-1 7-9 6-2 7-3 5-0 0-2 0-8 1-6 3-9 6-3 2-8 1-5 9-8 4-5 4-7\nWhich of these graphs have Euler cycles (cycles that visit each edge exactly once)? Which of them have Hamilton cycles (cycles that visit each vertex exactly once)?", "answer": "4.1.30 - Eulerian and Hamiltonian cycles\n\nAn Eulerian cycle (or Eulerian circuit) is a path which starts and ends at the same vertex and includes every edge exactly once.\nA Hamiltonian cycle is a path which starts and ends at the same vertex and includes every vertex exactly once (except for the source, which is visited twice).\n\nAccording to Euler theorems a graph has an Eulerian cycle/circuit if and only if it does not have any vertices of odd degree.\n\nFirst graph:\n0-1 0-2 0-3 1-3 1-4 2-5 2-9 3-6 4-7 4-8 5-8 5-9 6-7 6-9 7-8\n\nIt does not have an Eulerian cycle because it has vertices of odd degree (0, 1, 2, 3, 4, 5, 6, 7, 8 and 9).\nIt has a Hamiltonian cycle: 1-4 4-8 8-7 7-6 6-9 9-5 5-2 2-0 0-3 3-1\n\nSecond graph:\n0-1 0-2 0-3 1-3 0-3 2-5 5-6 3-6 4-7 4-8 5-8 5-9 6-7 6-9 8-8\n\nIt has an Eulerian cycle (all the vertices have even degrees):\n0-3 3-0 0-2 2-5 5-9 9-6 6-5 5-8 8-8 8-4 4-7 7-6 6-3 3-1 1-0\nThere is no Hamiltonian cycle.\n\nThird graph:\n0-1 1-2 1-3 0-3 0-4 2-5 2-9 3-6 4-7 4-8 5-8 5-9 6-7 6-9 7-8\n\nIt does not have an Eulerian cycle because it has vertices of odd degree (0, 1, 2, 3, 4, 5, 6, 7, 8, 9).\nIt has a Hamiltonian cycle: 4-8 8-7 7-6 6-9 9-5 5-2 2-1 1-3 3-0 0-4\n\nFourth graph:\n4-1 7-9 6-2 7-3 5-0 0-2 0-8 1-6 3-9 6-3 2-8 1-5 9-8 4-5 4-7\n\nIt does not have an Eulerian cycle because it has vertices of odd degree (0, 1, 2, 3, 4, 5, 6, 7, 8, 9).\nIt has a Hamiltonian cycle: 0-5 5-4 4-1 1-6 6-3 3-7 7-9 9-8 8-2 2-0\n", "support_files": [], "metadata": {"number": "4.1.30", "chapter": 4, "chapter_title": "Graphs", "section": 4.1, "section_title": "Undirected Graphs", "type": "Creative Problem", "code_execution": false}} {"question": "Graph enumeration. How many different undirected graphs are there with V vertices and E edges (and no parallel edges)?", "answer": "For an undirected graph with V labeled vertices and no parallel edges, each possible edge is determined by an unordered pair of vertices.\n\nIf self-loops are not allowed, there are binomial(V, 2) possible edges, so the number of graphs with exactly E edges is\n\n binomial(binomial(V, 2), E)\n\nIf self-loops are allowed, there are binomial(V, 2) ordinary edges plus V possible self-loops, for V(V + 1) / 2 possible edges total. In that model the count is\n\n binomial(V(V + 1) / 2, E)\n", "support_files": [], "metadata": {"number": "4.1.31", "chapter": 4, "chapter_title": "Graphs", "section": 4.1, "section_title": "Undirected Graphs", "type": "Creative Problem", "code_execution": false}} {"question": "Odd cycles. Prove that a graph is two-colorable (bipartite) if and only if it contains no odd-length cycle.", "answer": "4.1.33 - Odd cycles\n\nA graph is two-colorable (bipartite) if and only if it contains no odd-length cycle.\n\nProof:\n1- Proving that a graph with an odd-length cycle cannot be bipartite:\nIf a graph G is bipartite with vertex sets V1 and V2, every step along a walk takes you either from V1 to V2 or from V2 to V1. To end up where you started, therefore, you must take an even number of steps.\n\n2- Proving that a graph with only even-length cycles is bipartite:\nConsider G to be a graph with only even-length cycles. Let v0 be any vertex. For each vertex v in the same component C0 as v0 let d(v) be the length of the shortest path from v0 to v. Color red every vertex in C0 whose distance from v0 is even, and color the other vertices of C0 blue. Do the same for each component of G. Check that if G had any edge between two red vertices or between two blue vertices, it would have an odd cycle. Thus, G is bipartite, the red vertices and the blue vertices being the two parts.\n\nReference: \nhttps://math.stackexchange.com/questions/311665/proof-a-graph-is-bipartite-if-and-only-if-it-contains-no-odd-cycles\n", "support_files": [], "metadata": {"number": "4.1.33", "chapter": 4, "chapter_title": "Graphs", "section": 4.1, "section_title": "Undirected Graphs", "type": "Creative Problem", "code_execution": false}} {"question": "Biconnectedness. A graph is biconnected if every pair of vertices is connected by two disjoint paths. An articulation point in a connected graph is a vertex that would disconnect the graph if it (and its adjacent edges) were removed. Prove that any graph with no articulation points is biconnected. Hint: Given a pair of vertices s and t and a path connecting them, use the fact that none of the vertices on the path are articulation points to construct two disjoint paths connecting s and t.", "answer": "Assume the connected graph has no articulation point. For any two vertices `s` and `t`, take a simple path `P` from `s` to `t`. If an internal vertex `v` of `P` were present on every `s-t` path, then removing `v` would separate `s` from `t`, making `v` an articulation point. Since there are no articulation points, no internal vertex of `P` can be unavoidable.\n\nEquivalently by Menger's theorem for vertices, if two vertices are not connected by two internally vertex-disjoint paths, then there is a single vertex whose removal separates them. That vertex would be an articulation point. Therefore every pair of vertices has two internally disjoint paths, so the graph is biconnected.", "support_files": [], "metadata": {"number": "4.1.35", "chapter": 4, "chapter_title": "Graphs", "section": 4.1, "section_title": "Undirected Graphs", "type": "Creative Problem", "code_execution": false}} {"question": "What is the maximum number of edges in a digraph with V vertices and no parallel edges? What is the minimum number of edges in a digraph with V vertices, none of which are isolated?", "answer": "The maximum number of edges in a simple digraph with `V` vertices and no parallel edges is\n\n`V(V - 1)`,\n\nbecause each ordered pair of distinct vertices may appear once.\n\nIf \"not isolated\" means every vertex has total degree at least 1, the minimum number of directed edges is `ceil(V / 2)`: one directed edge covers two vertices, and for odd `V` the final three vertices can be covered by two directed edges. If instead the requirement were positive indegree and positive outdegree for every vertex, the minimum would be `V`, using one directed cycle through all vertices.", "support_files": [], "metadata": {"number": "4.2.1", "chapter": 4, "chapter_title": "Graphs", "section": 4.2, "section_title": "Directed Graphs", "type": "Exercise", "code_execution": false}} {"question": "Draw, in the style of the figure in the text (page 524), the adjacency lists built by Digraph’s input stream constructor for the file tinyDGex2.txt depicted at left.", "answer": "4.2.2\n\nadj[]\n 0 -> 6 -> 5\n 1 -> \n 2 -> 0 -> 3\n 3 -> 10 -> 6\n 4 -> 1\n 5 -> 10 -> 2\n 6 -> 2\n 7 -> 8 -> 11\n 8 -> 1 -> 4\n 9 -> \n 10 -> 3\n 11 -> 8\n", "support_files": [], "metadata": {"number": "4.2.2", "chapter": 4, "chapter_title": "Graphs", "section": 4.2, "section_title": "Directed Graphs", "type": "Exercise", "code_execution": false}} {"question": "Develop a test client for Digraph.", "answer": "package chapter4.section2;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 19/10/17.\n */\npublic class Exercise6 {\n\n public static void main(String[] args) {\n\n Digraph digraph = new Digraph(5);\n digraph.addEdge(0, 1);\n digraph.addEdge(0, 2);\n digraph.addEdge(0, 3);\n digraph.addEdge(1, 2);\n digraph.addEdge(1, 4);\n digraph.addEdge(2, 3);\n\n StdOut.println(\"Vertices in digraph: \" + digraph.vertices() + \" Expected: 5\");\n StdOut.println(\"Edges in digraph: \" + digraph.edges() + \" Expected: 6\");\n\n digraph.addEdge(0, 4);\n StdOut.println(\"Edges in digraph after addEdge(): \" + digraph.edges() + \" Expected: 7\");\n\n StdOut.println(\"\\nDigraph: \");\n StdOut.println(digraph);\n\n StdOut.println(\"Expected:\\n\" +\n \"0: 4 3 2 1\\n\" +\n \"1: 4 2\\n\" +\n \"2: 3\\n\" +\n \"3: \\n\" +\n \"4: \");\n\n StdOut.println(\"\\nReverse digraph: \");\n Digraph reverseDigraph = digraph.reverse();\n StdOut.println(reverseDigraph);\n\n StdOut.println(\"Expected:\\n\" +\n \"0: \\n\" +\n \"1: 0\\n\" +\n \"2: 1 0\\n\" +\n \"3: 2 0\\n\" +\n \"4: 1 0\");\n }\n\n}\n", "support_files": [], "metadata": {"number": "4.2.6", "chapter": 4, "chapter_title": "Graphs", "section": 4.2, "section_title": "Directed Graphs", "type": "Exercise", "code_execution": false}} {"question": "Write a method that checks whether or not a given permutation of a DAG’s vertices is a topological order of that DAG.", "answer": "package chapter4.section2;\n\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Created by Rene Argento on 21/10/17.\n */\n// Thanks to dragon-dreamer (https://github.com/dragon-dreamer) for suggesting a more efficient solution:\n// https://github.com/reneargento/algorithms-sedgewick-wayne/issues/142\npublic class Exercise9 {\n\n private class CheckTopologicalOrder {\n\n public boolean isTopologicalOrder(Digraph digraph, List topologicalOrder) {\n DirectedCycle directedCycle = new DirectedCycle(digraph);\n if (directedCycle.hasCycle()) {\n throw new IllegalArgumentException(\"Digraph is not a DAG\");\n }\n\n if (topologicalOrder.size() != digraph.vertices()) {\n return false;\n }\n\n boolean[] visited = new boolean[digraph.vertices()];\n for (int i = topologicalOrder.size() - 1; i >= 0; i--) {\n int vertex = topologicalOrder.get(i);\n if (visited[vertex]) {\n return false;\n }\n\n visited[vertex] = true;\n\n for (int neighbor : digraph.adjacent(vertex)) {\n if (!visited[neighbor]) {\n return false;\n }\n }\n }\n return true;\n }\n }\n\n public static void main(String[] args) {\n CheckTopologicalOrder checkTopologicalOrder = new Exercise9().new CheckTopologicalOrder();\n\n Digraph digraph1 = new Digraph(3);\n digraph1.addEdge(0, 1);\n digraph1.addEdge(0, 2);\n digraph1.addEdge(1, 2);\n\n List topologicalOrder1 = new ArrayList<>();\n topologicalOrder1.add(0);\n topologicalOrder1.add(1);\n topologicalOrder1.add(2);\n boolean isTopologicalOrder1 = checkTopologicalOrder.isTopologicalOrder(digraph1, topologicalOrder1);\n\n StdOut.println(\"Is topological order: \" + isTopologicalOrder1 + \" Expected: true\");\n\n List topologicalOrder2 = new ArrayList<>();\n topologicalOrder2.add(1);\n topologicalOrder2.add(0);\n topologicalOrder2.add(2);\n boolean isTopologicalOrder2 = checkTopologicalOrder.isTopologicalOrder(digraph1, topologicalOrder2);\n\n StdOut.println(\"Is topological order: \" + isTopologicalOrder2 + \" Expected: false\");\n\n Digraph digraph2 = new Digraph(6);\n digraph2.addEdge(0, 1);\n digraph2.addEdge(1, 2);\n digraph2.addEdge(2, 3);\n digraph2.addEdge(4, 5);\n\n List topologicalOrder3 = new ArrayList<>();\n topologicalOrder3.add(0);\n topologicalOrder3.add(4);\n topologicalOrder3.add(1);\n topologicalOrder3.add(2);\n topologicalOrder3.add(5);\n topologicalOrder3.add(3);\n boolean isTopologicalOrder3 = checkTopologicalOrder.isTopologicalOrder(digraph2, topologicalOrder3);\n\n StdOut.println(\"Is topological order: \" + isTopologicalOrder3 + \" Expected: true\");\n }\n\n}\n", "support_files": [], "metadata": {"number": "4.2.9", "chapter": 4, "chapter_title": "Graphs", "section": 4.2, "section_title": "Directed Graphs", "type": "Exercise", "code_execution": false}} {"question": "Given a DAG, does there exist a topological order that cannot result from applying a DFS-based algorithm, no matter in what order the vertices adjacent to each vertex are chosen? Prove your answer.", "answer": "No. Every topological order of a DAG can be produced as the reverse postorder of DFS for a suitable choice of the order in which DFS starts vertices.\n\nLet `v1, v2, ..., vV` be any topological order. Run the outer DFS loop in the reverse order `vV, ..., v2, v1`. In a DAG, every edge goes from an earlier vertex in the topological order to a later vertex. Therefore, when DFS is started from a later vertex, it cannot reach any earlier unmarked vertex. Vertices finish in the reverse of the desired order, so reverse postorder is exactly `v1, v2, ..., vV`.", "support_files": [], "metadata": {"number": "4.2.10", "chapter": 4, "chapter_title": "Graphs", "section": 4.2, "section_title": "Directed Graphs", "type": "Exercise", "code_execution": false}} {"question": "Describe a family of sparse digraphs whose number of directed cycles grows exponentially in the number of vertices.", "answer": "4.2.11\n\nA family of sparse digraphs whose number of directed cycles grows exponentially in the number of vertices is the following:\n\nTake an n-cycle and make every edge a parallel edge. Now there are 2^n cycles.\nExample: \n\no -> o\n^ |\n| v\no <- o\n\nbecomes\n\no -> o\n^^->||\n|| ||\n||<-vv\no <- o\n\nAnother possibility, to avoid parallel edges, is to double each edge in a crossing way, leading to 2^(n/2) cycles.\nExample: \n\no -> o\n^ |\n| v\no <- o\n\nbecomes\n\no -> o\n^\\ ^|\n| \\ /|\n| X |\n| / \\|\n|/ vv\no <- o\n\nThe graphs are sparse, since there are just two edges per vertex in the first graph, or 1.5 edges per vertex on the second graph.\nEvery vertex added in this graph family will grow the number of directed cycles exponentially.\n\nBased on: \nhttps://stackoverflow.com/questions/32650192/what-is-a-family-of-digraphs-whose-number-of-directed-cycles-grows-exponentially\n", "support_files": [], "metadata": {"number": "4.2.11", "chapter": 4, "chapter_title": "Graphs", "section": 4.2, "section_title": "Directed Graphs", "type": "Exercise", "code_execution": false}} {"question": "How many edges are there in the transitive closure of a digraph that is a simple directed path with V vertices and V–1 edges?", "answer": "In a simple directed path with vertices v0 -> v1 -> ... -> v(V-1), vertex vi can reach exactly the vertices vj with j > i.\n\nThe transitive closure therefore has one directed edge vi -> vj for every ordered pair with i < j. The number of such pairs is\n\n (V - 1) + (V - 2) + ... + 1 = V(V - 1) / 2\n\nSo the transitive closure contains V(V - 1) / 2 edges.\n", "support_files": [], "metadata": {"number": "4.2.12", "chapter": 4, "chapter_title": "Graphs", "section": 4.2, "section_title": "Directed Graphs", "type": "Exercise", "code_execution": false}} {"question": "Prove that the strong components in G^R are the same as in G.", "answer": "4.2.14\n\nThe strong components in Gr are the same as in G.\n\nProof:\nFor each strong component in G, every pair of vertices u and v has a path that can go from vertex u to vertex v and another path that can go from vertex v to vertex u.\nReversing each edge direction in Gr maintains these paths, since the only modification is in the direction of the edges and there are no added or removed edges or added or removed vertices.\n\nProof by contradiction:\nSuppose that there is a new strong component in Gr or that a strong component in G no longer exists in Gr.\nThis would imply that not only the edge directions were reversed, but also that there is a new edge connecting a vertex that was not part of the original strong component (if there is a new strong component in Gr) or that an edge connecting two vertices in the original strong component was removed (if there is a strong component in G that no longer exists in Gr). Both cases are not possible.\n\nThe main difference in Gr is that source vertices become sink vertices and sink vertices become source vertices, but this does not affect the strong components.\n\nExample:\nG graph\nA -> B -> C -> D\n ^ /\n \\ v\n E\n \nG reverse (Gr)\nA <- B <- C <- D\n \\ ^\n v /\n E\n \nAs we can see in graphs G and Gr, the strongly connected components are the same.\nIn this case, the strongly connected component is composed of the vertices B, C and E.\n", "support_files": [], "metadata": {"number": "4.2.14", "chapter": 4, "chapter_title": "Graphs", "section": 4.2, "section_title": "Directed Graphs", "type": "Exercise", "code_execution": false}} {"question": "Topological sort and BFS. Explain why the following algorithm does not necessarily produce a topological order: Run BFS, and label the vertices by increasing distance to their respective source.", "answer": "4.2.19 - Topological sort and BFS\n\nThe algorithm does not necessarily produce a topological order because some vertices closer to the source may be preceded by vertices further from the source in a topological order.\n\nExample:\nConsider the graph:\n0 -> 1 -> 2 -> 3 -> 4 -> 5\n | /\n v /\n 6 <----------\n\nThe algorithm running BFS would produce the following topological order: 0 1 2 6 3 4 5\nSuch order is invalid because 6 should be preceded by 5 in a topological order.", "support_files": [], "metadata": {"number": "4.2.19", "chapter": 4, "chapter_title": "Graphs", "section": 4.2, "section_title": "Directed Graphs", "type": "Creative Problem", "code_execution": false}} {"question": "Directed Eulerian cycle. An Eulerian cycle is a directed cycle that contains each edge exactly once. Write a graph client Euler that finds an Eulerian cycle or reports that no such tour exists. Hint: Prove that a digraph G has a directed Eulerian cycle if and only if G is connected and each vertex has its indegree equal to its outdegree.", "answer": "package chapter4.section2;\n\nimport chapter1.section3.Stack;\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.Iterator;\n\n/**\n * Created by Rene Argento on 23/10/17.\n */\n//Based on https://algs4.cs.princeton.edu/42digraph/DirectedEulerianCycle.java.html\n@SuppressWarnings(\"unchecked\")\npublic class Euler {\n\n private class DirectedEulerianCycle {\n\n public Stack getDirectedEulerianCycle(Digraph digraph) {\n // A graph with no edges is considered to have an Eulerian cycle\n if (digraph.edges() == 0) {\n return new Stack<>();\n }\n\n // Check if all vertices have indegree equal to their outdegree\n // If any vertex does not, the algorithm may return an Eulerian path instead\n for (int vertex = 0; vertex < digraph.vertices(); vertex++) {\n if (digraph.indegree(vertex) != digraph.outdegree(vertex)) {\n return null;\n }\n }\n\n // Create local view of adjacency lists, to iterate one vertex at a time\n Iterator[] adjacent = (Iterator[]) new Iterator[digraph.vertices()];\n for (int vertex = 0; vertex < digraph.vertices(); vertex++) {\n adjacent[vertex] = digraph.adjacent(vertex).iterator();\n }\n\n // Start the cycle with a non-isolated vertex\n int nonIsolatedVertex = nonIsolatedVertex(digraph);\n Stack dfsStack = new Stack<>();\n dfsStack.push(nonIsolatedVertex);\n\n Stack eulerCycle = new Stack<>();\n\n while (!dfsStack.isEmpty()) {\n int vertex = dfsStack.pop();\n\n while (adjacent[vertex].hasNext()) {\n dfsStack.push(vertex);\n vertex = adjacent[vertex].next();\n }\n\n // Push vertex with no more leaving edges to the Euler cycle\n eulerCycle.push(vertex);\n }\n\n // For each edge visited, we visited a vertex. Add 1 because the first and last vertices are the same.\n if (eulerCycle.size() == digraph.edges() + 1) {\n return eulerCycle;\n } else {\n return null;\n }\n }\n\n private int nonIsolatedVertex(Digraph digraph) {\n int nonIsolatedVertex = -1;\n\n for (int vertex = 0; vertex < digraph.vertices(); vertex++) {\n if (digraph.outdegree(vertex) > 0) {\n nonIsolatedVertex = vertex;\n }\n }\n\n return nonIsolatedVertex;\n }\n }\n\n public static void main(String[] args) {\n Euler exercise28 = new Euler();\n DirectedEulerianCycle directedEulerianCycle = exercise28.new DirectedEulerianCycle();\n\n Digraph digraphWithDirectedEulerPath1 = new Digraph(4);\n digraphWithDirectedEulerPath1.addEdge(0, 1);\n digraphWithDirectedEulerPath1.addEdge(1, 2);\n digraphWithDirectedEulerPath1.addEdge(2, 3);\n digraphWithDirectedEulerPath1.addEdge(3, 0);\n digraphWithDirectedEulerPath1.addEdge(3, 2);\n\n Stack eulerCycle1 = directedEulerianCycle.getDirectedEulerianCycle(digraphWithDirectedEulerPath1);\n\n if (eulerCycle1 != null) {\n exercise28.printCycle(eulerCycle1);\n } else {\n StdOut.println(\"There is no directed Eulerian cycle\");\n }\n StdOut.println(\"Expected: There is no directed Eulerian cycle\\n\");\n\n Digraph digraphWithDirectedEulerCycle1 = new Digraph(4);\n digraphWithDirectedEulerCycle1.addEdge(0, 1);\n digraphWithDirectedEulerCycle1.addEdge(1, 2);\n digraphWithDirectedEulerCycle1.addEdge(2, 3);\n digraphWithDirectedEulerCycle1.addEdge(3, 0);\n\n Stack eulerCycle2 = directedEulerianCycle.getDirectedEulerianCycle(digraphWithDirectedEulerCycle1);\n\n if (eulerCycle2 != null) {\n exercise28.printCycle(eulerCycle2);\n } else {\n StdOut.println(\"There is no directed Eulerian cycle\");\n }\n StdOut.println(\"Expected: 3->0 0->1 1->2 2->3\\n\");\n\n //Note that vertex 5 is an isolated vertex\n Digraph digraphWithDirectedEulerCycle2 = new Digraph(6);\n digraphWithDirectedEulerCycle2.addEdge(0, 1);\n digraphWithDirectedEulerCycle2.addEdge(1, 2);\n digraphWithDirectedEulerCycle2.addEdge(2, 0);\n digraphWithDirectedEulerCycle2.addEdge(1, 3);\n digraphWithDirectedEulerCycle2.addEdge(3, 1);\n digraphWithDirectedEulerCycle2.addEdge(3, 2);\n digraphWithDirectedEulerCycle2.addEdge(2, 4);\n digraphWithDirectedEulerCycle2.addEdge(4, 3);\n\n Stack eulerCycle3 = directedEulerianCycle.getDirectedEulerianCycle(digraphWithDirectedEulerCycle2);\n\n if (eulerCycle3 != null) {\n exercise28.printCycle(eulerCycle3);\n } else {\n StdOut.println(\"There is no directed Eulerian cycle\");\n }\n StdOut.println(\"Expected: 4->3 3->2 2->0 0->1 1->3 3->1 1->2 2->4\\n\");\n\n Digraph digraphWithDirectedEulerPath2 = new Digraph(4);\n digraphWithDirectedEulerPath2.addEdge(0, 1);\n digraphWithDirectedEulerPath2.addEdge(1, 2);\n digraphWithDirectedEulerPath2.addEdge(2, 3);\n digraphWithDirectedEulerPath2.addEdge(3, 0);\n digraphWithDirectedEulerPath2.addEdge(3, 1);\n\n Stack eulerCycle4 = directedEulerianCycle.getDirectedEulerianCycle(digraphWithDirectedEulerPath2);\n\n if (eulerCycle4 != null) {\n exercise28.printCycle(eulerCycle4);\n } else {\n StdOut.println(\"There is no directed Eulerian cycle\");\n }\n StdOut.println(\"Expected: There is no directed Eulerian cycle\");\n }\n\n private void printCycle(Stack eulerCycle) {\n StdOut.println(\"Euler cycle:\");\n\n while (!eulerCycle.isEmpty()) {\n int vertex = eulerCycle.pop();\n\n if (!eulerCycle.isEmpty()) {\n StdOut.print(vertex + \"->\" + eulerCycle.peek());\n\n if (eulerCycle.size() > 1) {\n StdOut.print(\" \");\n }\n }\n }\n StdOut.println();\n }\n}\n", "support_files": [], "metadata": {"number": "4.2.20", "chapter": 4, "chapter_title": "Graphs", "section": 4.2, "section_title": "Directed Graphs", "type": "Creative Problem", "code_execution": false}} {"question": "LCA of a DAG. Given a DAG and two vertices v and w, find the lowest common ancestor (LCA) of v and w. The LCA of v and w is an ancestor of v and w that has no descendants that are also ancestors of v and w. Computing the LCA is useful in multiple inheritance in programming languages, analysis of genealogical data (find degree of inbreeding in a pedigree graph), and other applications. Hint: Define the height of a vertex v in a DAG to be the length of the longest path from a root to v. Among vertices that are ancestors of both v and w, the one with the greatest height is an LCA of v and w.", "answer": "package chapter4.section2;\n\nimport chapter1.section3.Queue;\nimport chapter3.section5.HashSet;\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.Arrays;\n\n/**\n * Created by Rene Argento on 24/10/17.\n */\n// Thanks to pharrukh (https://github.com/pharrukh) for suggesting to move part of the sources computing to the Digraph\n// class:\n// https://github.com/reneargento/algorithms-sedgewick-wayne/issues/302\npublic class Exercise29_LCAInDAG {\n\n private final Digraph digraph;\n private final int[] maxDistances;\n\n //Preprocess to\n // 1- Find all sources in the digraph\n // 2- Compute the height of all vertices (max distance from any source)\n // O(S * (V + E)) where S is the number of sources = O(VE)\n public Exercise29_LCAInDAG(Digraph digraph) {\n this.digraph = digraph;\n maxDistances = new int[digraph.vertices()];\n HashSet sources = computeSources(digraph);\n\n // 2- Find the height of all vertices (the length of the longest distance from a source)\n Arrays.fill(maxDistances, -1);\n\n for (int source : sources.keys()) {\n int[] distanceFromCurrentSource = new int[digraph.vertices()];\n Arrays.fill(distanceFromCurrentSource, Integer.MAX_VALUE);\n\n Queue sourceDistanceQueue = new Queue<>();\n sourceDistanceQueue.enqueue(source);\n distanceFromCurrentSource[source] = 0;\n\n if (distanceFromCurrentSource[source] > maxDistances[source]) {\n maxDistances[source] = distanceFromCurrentSource[source];\n }\n\n while (!sourceDistanceQueue.isEmpty()) {\n int currentVertex = sourceDistanceQueue.dequeue();\n\n for (int neighbor : digraph.adjacent(currentVertex)) {\n distanceFromCurrentSource[neighbor] = distanceFromCurrentSource[currentVertex] + 1;\n sourceDistanceQueue.enqueue(neighbor);\n\n if (distanceFromCurrentSource[neighbor] > maxDistances[neighbor]) {\n maxDistances[neighbor] = distanceFromCurrentSource[neighbor];\n }\n }\n }\n }\n }\n\n private static HashSet computeSources(Digraph digraph) {\n HashSet sources = new HashSet<>();\n\n for (int vertex = 0; vertex < digraph.vertices(); vertex++) {\n if (digraph.indegree(vertex) == 0) {\n sources.add(vertex);\n }\n }\n return sources;\n }\n\n //O(V + E)\n public int getLCA(int vertex1, int vertex2) {\n DirectedCycle directedCycle = new DirectedCycle(digraph);\n if (directedCycle.hasCycle()) {\n throw new IllegalArgumentException(\"Digraph is not a DAG\");\n }\n\n // 1- Reverse graph\n Digraph reverseDigraph = digraph.reverse();\n\n // 2- Do a BFS from vertex1 to find all its ancestors\n HashSet vertex1Ancestors = new HashSet<>();\n\n Queue queue = new Queue<>();\n queue.enqueue(vertex1);\n\n while (!queue.isEmpty()) {\n int currentVertex = queue.dequeue();\n vertex1Ancestors.add(currentVertex);\n\n for (int neighbor : reverseDigraph.adjacent(currentVertex)) {\n queue.enqueue(neighbor);\n }\n }\n\n // 3- Do a BFS from vertex2 to find all its ancestors and see which ones are common ancestors to vertex1\n HashSet commonAncestors = new HashSet<>();\n\n queue.enqueue(vertex2);\n\n while (!queue.isEmpty()) {\n int currentVertex = queue.dequeue();\n\n if (vertex1Ancestors.contains(currentVertex)) {\n commonAncestors.add(currentVertex);\n }\n\n for (int neighbor : reverseDigraph.adjacent(currentVertex)) {\n queue.enqueue(neighbor);\n }\n }\n\n // 4- Find the height of all common ancestors (the length of the longest distance from a source)\n // The common ancestor with greatest height is an LCA of vertex1 and vertex2\n int maxDistance = -1;\n int lowestCommonAncestor = -1;\n\n for (int commonAncestor : commonAncestors.keys()) {\n if (maxDistances[commonAncestor] > maxDistance) {\n maxDistance = maxDistances[commonAncestor];\n lowestCommonAncestor = commonAncestor;\n }\n }\n return lowestCommonAncestor;\n }\n\n public static void main(String[] args) {\n Digraph digraph1 = new Digraph(5);\n digraph1.addEdge(0, 1);\n digraph1.addEdge(1, 2);\n digraph1.addEdge(0, 3);\n digraph1.addEdge(3, 4);\n\n Exercise29_LCAInDAG lcaInDAG1 = new Exercise29_LCAInDAG(digraph1);\n int lca1 = lcaInDAG1.getLCA(2, 4);\n if (lca1 == -1) {\n StdOut.print(\"LCA in digraph 1: There is no LCA in this DAG\");\n } else {\n StdOut.print(\"LCA in digraph 1: \" + lca1);\n }\n StdOut.println(\" Expected: 0\");\n\n Digraph digraph2 = new Digraph(5);\n digraph2.addEdge(0, 1);\n digraph2.addEdge(0, 2);\n digraph2.addEdge(2, 3);\n digraph2.addEdge(2, 4);\n\n Exercise29_LCAInDAG lcaInDAG2 = new Exercise29_LCAInDAG(digraph2);\n int lca2 = lcaInDAG2.getLCA(3, 4);\n if (lca2 == -1) {\n StdOut.print(\"LCA in digraph 2: There is no LCA in this DAG\");\n } else {\n StdOut.print(\"LCA in digraph 2: \" + lca2);\n }\n StdOut.println(\" Expected: 2\");\n\n\n Digraph digraph3 = new Digraph(9);\n digraph3.addEdge(0, 1);\n digraph3.addEdge(1, 2);\n digraph3.addEdge(1, 3);\n\n digraph3.addEdge(4, 5);\n digraph3.addEdge(5, 6);\n digraph3.addEdge(6, 8);\n digraph3.addEdge(6, 7);\n digraph3.addEdge(7, 2);\n digraph3.addEdge(8, 3);\n\n Exercise29_LCAInDAG lcaInDAG3 = new Exercise29_LCAInDAG(digraph3);\n int lca3 = lcaInDAG3.getLCA(2, 3);\n if (lca3 == -1) {\n StdOut.print(\"LCA in digraph 3: There is no LCA in this DAG\");\n } else {\n StdOut.print(\"LCA in digraph 3: \" + lca3);\n }\n StdOut.println(\" Expected: 6\");\n\n\n Digraph digraph4 = new Digraph(9);\n digraph4.addEdge(0, 1);\n digraph4.addEdge(1, 3);\n digraph4.addEdge(1, 4);\n digraph4.addEdge(4, 5);\n digraph4.addEdge(5, 6);\n digraph4.addEdge(6, 2);\n\n digraph4.addEdge(7, 8);\n digraph4.addEdge(8, 3);\n digraph4.addEdge(7, 2);\n\n Exercise29_LCAInDAG lcaInDAG4 = new Exercise29_LCAInDAG(digraph4);\n int lca4 = lcaInDAG4.getLCA(2, 3);\n if (lca4 == -1) {\n StdOut.print(\"LCA in digraph 4: There is no LCA in this DAG\");\n } else {\n StdOut.print(\"LCA in digraph 4: \" + lca4);\n }\n StdOut.println(\" Expected: 1\");\n\n\n Digraph digraph5 = new Digraph(4);\n digraph5.addEdge(0, 1);\n digraph5.addEdge(1, 2);\n\n Exercise29_LCAInDAG lcaInDAG5 = new Exercise29_LCAInDAG(digraph5);\n int lca5 = lcaInDAG5.getLCA(2, 3);\n if (lca5 == -1) {\n StdOut.print(\"LCA in digraph 5: There is no LCA in this DAG\");\n } else {\n StdOut.print(\"LCA in digraph 5: \" + lca5);\n }\n StdOut.println(\" Expected: There is no LCA in this DAG\");\n }\n}\n", "support_files": [], "metadata": {"number": "4.2.21", "chapter": 4, "chapter_title": "Graphs", "section": 4.2, "section_title": "Directed Graphs", "type": "Creative Problem", "code_execution": false}} {"question": "Hamiltonian path in DAGs. Given a DAG, design a linear-time algorithm to determine whether there is a directed path that visits each vertex exactly once.", "answer": "package chapter4.section2;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 25/10/17.\n */\npublic class Exercise32_HamiltonianPathInDAGs {\n\n // A DAG has a Hamiltonian path if and only if there is a directed edge between each pair of consecutive vertices\n // in its topological order\n public boolean hasHamiltonianPath(Digraph digraph) {\n DirectedCycle directedCycle = new DirectedCycle(digraph);\n if (directedCycle.hasCycle()) {\n throw new IllegalArgumentException(\"Digraph is not a DAG\");\n }\n\n Topological topological = new Topological(digraph);\n int[] topologicalOrder = new int[digraph.vertices()];\n int arrayIndex = 0;\n\n for (int vertex : topological.order()) {\n topologicalOrder[arrayIndex++] = vertex;\n }\n\n for (int i = 0; i < topologicalOrder.length - 1; i++) {\n boolean hasEdgeToNextVertex = false;\n\n for (int neighbor : digraph.adjacent(topologicalOrder[i])) {\n if (neighbor == topologicalOrder[i + 1]) {\n hasEdgeToNextVertex = true;\n break;\n }\n }\n\n if (!hasEdgeToNextVertex) {\n return false;\n }\n }\n return true;\n }\n\n public static void main(String[] args) {\n Exercise32_HamiltonianPathInDAGs hamiltonianPathInDAGs = new Exercise32_HamiltonianPathInDAGs();\n\n Digraph digraph1 = new Digraph(5);\n digraph1.addEdge(0, 1);\n digraph1.addEdge(0, 2);\n digraph1.addEdge(1, 2);\n digraph1.addEdge(2, 3);\n digraph1.addEdge(3, 4);\n StdOut.println(\"Has Hamiltonian path: \" + hamiltonianPathInDAGs.hasHamiltonianPath(digraph1) + \" Expected: true\");\n\n Digraph digraph2 = new Digraph(6);\n digraph2.addEdge(0, 1);\n digraph2.addEdge(1, 2);\n digraph2.addEdge(3, 4);\n digraph2.addEdge(4, 5);\n StdOut.println(\"Has Hamiltonian path: \" + hamiltonianPathInDAGs.hasHamiltonianPath(digraph2) + \" Expected: false\");\n\n Digraph digraph3 = new Digraph(9);\n digraph3.addEdge(0, 1);\n digraph3.addEdge(1, 2);\n digraph3.addEdge(1, 3);\n\n digraph3.addEdge(4, 5);\n digraph3.addEdge(5, 6);\n digraph3.addEdge(6, 8);\n digraph3.addEdge(6, 7);\n digraph3.addEdge(7, 2);\n digraph3.addEdge(8, 3);\n StdOut.println(\"Has Hamiltonian path: \" + hamiltonianPathInDAGs.hasHamiltonianPath(digraph3) + \" Expected: false\");\n\n Digraph digraph4 = new Digraph(5);\n digraph4.addEdge(0, 2);\n digraph4.addEdge(1, 2);\n digraph4.addEdge(1, 3);\n digraph4.addEdge(2, 4);\n digraph4.addEdge(3, 4);\n StdOut.println(\"Has Hamiltonian path: \" + hamiltonianPathInDAGs.hasHamiltonianPath(digraph4) + \" Expected: false\");\n }\n}\n", "support_files": [], "metadata": {"number": "4.2.24", "chapter": 4, "chapter_title": "Graphs", "section": 4.2, "section_title": "Directed Graphs", "type": "Creative Problem", "code_execution": false}} {"question": "Digraph enumeration. Show that the number of different V-vertex digraphs with no parallel edges is 2^(V^2). (How many digraphs are there that contain V vertices and E edges?) Then compute an upper bound on the percentage of 20-vertex digraphs that could ever be examined by any computer, under the assumptions that every electron in the universe examines a digraph every nanosecond, that the universe has fewer than 10^80 electrons, and that the age of the universe will be less than 10^20 years.", "answer": "With V labeled vertices and no parallel edges, there are V^2 possible directed edges if self-loops are allowed: one possible edge (v, w) for each ordered pair of vertices.\n\nEach possible edge is either present or absent, so the number of V-vertex digraphs is\n\n```text\n2^(V^2)\n```\n\nIf the digraph must contain exactly E edges, choose which E of the V^2 possible directed edges are present:\n\n```text\nbinomial(V^2, E)\n```\n\nFor V = 20, the number of digraphs is 2^400. If 10^80 electrons each examine one digraph per nanosecond for 10^20 years, and one year is about 3.154 * 10^16 nanoseconds, then at most about 3.154 * 10^116 digraphs can be examined. Since 2^400 is about 2.582 * 10^120, the examined fraction is about 1.221 * 10^-4, which is about 0.0122%.\n\nIf self-loops are disallowed, replace V^2 by V(V - 1).", "support_files": [], "metadata": {"number": "4.2.27", "chapter": 4, "chapter_title": "Graphs", "section": 4.2, "section_title": "Directed Graphs", "type": "Creative Problem", "code_execution": false}} {"question": "DAG enumeration. Give a formula for the number of V-vertex DAGs with E edges.", "answer": "For a fixed topological order of the V vertices, only edges that point forward in that order are allowed. There are V(V - 1) / 2 such possible edges, so the fixed-order count is:\n\n```text\nbinomial(V(V - 1) / 2, E)\n```\n\nFor labeled DAGs where the topological order is not fixed, that expression is not exact because a DAG can have more than one topological order. An exact recurrence is obtained by inclusion-exclusion on the nonempty set of sources. Let A(n, m) be the number of labeled DAGs with n vertices and m edges, with A(0, 0) = 1 and A(0, m) = 0 for m != 0.\n\n```text\nA(n, m) = sum_{k=1..n} (-1)^(k+1) binomial(n, k)\n sum_{j=0..min(m, k(n-k))} binomial(k(n-k), j) A(n-k, m-j)\n```\n\nHere k is the number of chosen sources, j is the number of edges from those sources to the remaining n-k vertices, and the alternating sum corrects for DAGs with multiple sources being counted more than once.", "support_files": [], "metadata": {"number": "4.2.28", "chapter": 4, "chapter_title": "Graphs", "section": 4.2, "section_title": "Directed Graphs", "type": "Creative Problem", "code_execution": false}} {"question": "Queue-based topological sort. Develop a topological sort implementation that maintains a vertex-indexed array that keeps track of the indegree of each vertex. Initialize the array and a queue of sources in a single pass through all the edges, as in EXERCISE 4.2.7. Then, perform the following operations until the source queue is empty:\n■ Remove a source from the queue and label it.\n■ Decrement the entries in the indegree array corresponding to the destination vertex of each of the removed vertex’s edges.\n■ If decrementing any entry causes it to become 0, insert the corresponding vertex onto the source queue.", "answer": "package chapter4.section2;\n\nimport chapter1.section3.Queue;\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 27/10/17.\n */\npublic class Exercise39_QueueBasedTopologicalSort {\n\n private int[] ranks;\n\n // O(V + E)\n public int[] topologicalSort(Digraph digraph) {\n\n DirectedCycle directedCycle = new DirectedCycle(digraph);\n if (directedCycle.hasCycle()) {\n // Digraph is not a DAG so no topological order exists\n return null;\n }\n\n int[] indegree = new int[digraph.vertices()];\n Queue sources = new Queue<>();\n\n ranks = new int[digraph.vertices()];\n\n int[] topologicalSort = new int[digraph.vertices()];\n int topologicalSortIndex = 0;\n\n for (int vertex = 0; vertex < digraph.vertices(); vertex++) {\n for (int neighbor : digraph.adjacent(vertex)) {\n indegree[neighbor]++;\n }\n }\n\n for (int vertex = 0; vertex < digraph.vertices(); vertex++) {\n if (indegree[vertex] == 0) {\n sources.enqueue(vertex);\n }\n }\n\n while (!sources.isEmpty()) {\n int currentSource = sources.dequeue();\n\n ranks[currentSource] = topologicalSortIndex;\n topologicalSort[topologicalSortIndex++] = currentSource;\n\n for (int neighbor : digraph.adjacent(currentSource)) {\n indegree[neighbor]--;\n\n if (indegree[neighbor] == 0) {\n sources.enqueue(neighbor);\n }\n }\n }\n\n return topologicalSort;\n }\n\n public static void main(String[] args) {\n Exercise39_QueueBasedTopologicalSort queueBasedTopologicalSort = new Exercise39_QueueBasedTopologicalSort();\n\n Digraph digraph1 = new Digraph(5);\n digraph1.addEdge(0, 1);\n digraph1.addEdge(0, 2);\n digraph1.addEdge(1, 2);\n digraph1.addEdge(2, 3);\n digraph1.addEdge(3, 4);\n\n int[] topologicalOrder1 = queueBasedTopologicalSort.topologicalSort(digraph1);\n\n StdOut.println(\"Topological order 1: \");\n\n for (int vertex : topologicalOrder1) {\n StdOut.print(vertex + \" \");\n }\n StdOut.println(\"\\nExpected: 0 1 2 3 4\");\n\n Digraph digraph2 = new Digraph(6);\n digraph2.addEdge(0, 1);\n digraph2.addEdge(1, 2);\n digraph2.addEdge(3, 4);\n digraph2.addEdge(4, 5);\n\n int[] topologicalOrder2 = queueBasedTopologicalSort.topologicalSort(digraph2);\n\n StdOut.println(\"\\nTopological order 2: \");\n\n for (int vertex : topologicalOrder2) {\n StdOut.print(vertex + \" \");\n }\n StdOut.println(\"\\nExpected: 0 3 1 4 2 5 \");\n\n Digraph digraph3 = new Digraph(9);\n digraph3.addEdge(0, 1);\n digraph3.addEdge(1, 2);\n digraph3.addEdge(1, 3);\n\n digraph3.addEdge(4, 5);\n digraph3.addEdge(5, 6);\n digraph3.addEdge(6, 8);\n digraph3.addEdge(6, 7);\n digraph3.addEdge(7, 2);\n digraph3.addEdge(8, 3);\n\n int[] topologicalOrder3 = queueBasedTopologicalSort.topologicalSort(digraph3);\n\n StdOut.println(\"\\nTopological order 3: \");\n\n for (int vertex : topologicalOrder3) {\n StdOut.print(vertex + \" \");\n }\n StdOut.println(\"\\nExpected: 0 4 1 5 6 7 8 2 3\");\n }\n}\n", "support_files": [], "metadata": {"number": "4.2.30", "chapter": 4, "chapter_title": "Graphs", "section": 4.2, "section_title": "Directed Graphs", "type": "Creative Problem", "code_execution": false}} {"question": "Euclidean digraphs. Modify your solution to EXERCISE 4.1.37 to create an API EuclideanDigraph for graphs whose vertices are points in the plane, so that you can work with graphical representations.", "answer": "package chapter4.section2;\n\nimport chapter1.section3.Bag;\nimport edu.princeton.cs.algs4.StdDraw;\nimport edu.princeton.cs.algs4.StdOut;\nimport util.DrawUtilities;\nimport util.DrawUtilities.Coordinate;\n\nimport java.awt.*;\n\n/**\n * Created by Rene Argento on 26/10/17.\n */\n@SuppressWarnings(\"unchecked\")\npublic class Exercise38_EuclideanDigraphs {\n\n public class EuclideanDigraph {\n\n public class Vertex {\n protected int id;\n private String name;\n protected Coordinate coordinates;\n\n Vertex(int id, double xCoordinate, double yCoordinate) {\n this(id, String.valueOf(id), xCoordinate, yCoordinate);\n }\n\n Vertex(int id, String name, double xCoordinate, double yCoordinate) {\n this.id = id;\n this.name = name;\n coordinates = new DrawUtilities().new Coordinate(xCoordinate, yCoordinate);\n }\n\n public void updateName(String name) {\n this.name = name;\n }\n }\n\n private final int vertices;\n private int edges;\n private Vertex[] allVertices;\n private Bag[] adjacent;\n\n private int[] indegrees;\n private int[] outdegrees;\n\n public EuclideanDigraph(int vertices) {\n this.vertices = vertices;\n this.edges = 0;\n allVertices = new Vertex[vertices];\n adjacent = (Bag[]) new Bag[vertices];\n\n indegrees = new int[vertices];\n outdegrees = new int[vertices];\n\n for (int vertex = 0; vertex < vertices; vertex++) {\n adjacent[vertex] = new Bag<>();\n }\n }\n\n public int vertices() {\n return vertices;\n }\n\n public int edges() {\n return edges;\n }\n\n public void addVertex(Vertex vertex) {\n allVertices[vertex.id] = vertex;\n }\n\n public void addEdge(int vertexId1, int vertexId2) {\n if (allVertices[vertexId1] == null || allVertices[vertexId2] == null) {\n throw new IllegalArgumentException(\"Vertex id not found\");\n }\n\n adjacent[vertexId1].add(vertexId2);\n\n edges++;\n outdegrees[vertexId1]++;\n indegrees[vertexId2]++;\n }\n\n public void show(double xScaleLow, double xScaleHigh, double yScaleLow, double yScaleHigh,\n double radiusOfCircleAroundVertex, double padding, double arrowLength) {\n StdDraw.setCanvasSize(500, 400);\n StdDraw.setXscale(xScaleLow, xScaleHigh);\n StdDraw.setYscale(yScaleLow, yScaleHigh);\n\n StdDraw.setPenRadius(0.002D);\n StdDraw.setPenColor(Color.BLUE);\n\n for (int vertexId = 0; vertexId < vertices; vertexId++) {\n if (allVertices[vertexId] != null) {\n double xCoordinate = allVertices[vertexId].coordinates.getXCoordinate();\n double yCoordinate = allVertices[vertexId].coordinates.getYCoordinate();\n\n StdDraw.setPenColor(Color.WHITE);\n StdDraw.filledCircle(xCoordinate, yCoordinate, radiusOfCircleAroundVertex);\n\n StdDraw.setPenColor(Color.BLACK);\n StdDraw.circle(xCoordinate, yCoordinate, radiusOfCircleAroundVertex);\n\n StdDraw.setPenColor(Color.BLUE);\n StdDraw.text(xCoordinate, yCoordinate, allVertices[vertexId].name);\n }\n }\n\n StdDraw.setPenColor(Color.BLACK);\n\n for (int vertexId = 0; vertexId < vertices; vertexId++) {\n for (Integer neighbor : adjacent(vertexId)) {\n Vertex neighborVertex = allVertices[neighbor];\n\n DrawUtilities.drawArrow(allVertices[vertexId].coordinates, neighborVertex.coordinates,\n padding, arrowLength);\n }\n }\n }\n\n public Iterable adjacent(int vertexId) {\n return adjacent[vertexId];\n }\n\n public int indegree(int vertex) {\n return indegrees[vertex];\n }\n\n public int outdegree(int vertex) {\n return outdegrees[vertex];\n }\n\n public EuclideanDigraph reverse() {\n EuclideanDigraph reverse = new EuclideanDigraph(vertices);\n\n for (int vertex = 0; vertex < vertices; vertex++) {\n for (Integer neighbor : adjacent(vertex)) {\n reverse.addEdge(neighbor, vertex);\n }\n }\n return reverse;\n }\n\n @Override\n public String toString() {\n StringBuilder stringBuilder = new StringBuilder();\n\n for (int vertex = 0; vertex < vertices(); vertex++) {\n stringBuilder.append(vertex).append(\": \");\n\n for (Integer neighbor : adjacent(vertex)) {\n stringBuilder.append(neighbor).append(\" \");\n }\n stringBuilder.append(\"\\n\");\n }\n return stringBuilder.toString();\n }\n }\n\n public static void main(String[] args) {\n Exercise38_EuclideanDigraphs euclideanDigraphs = new Exercise38_EuclideanDigraphs();\n\n EuclideanDigraph euclideanDigraph = euclideanDigraphs.new EuclideanDigraph(7);\n\n EuclideanDigraph.Vertex vertex0 = euclideanDigraph.new Vertex(0, 6.1, 1.3);\n EuclideanDigraph.Vertex vertex1 = euclideanDigraph.new Vertex(1, 7.2, 2.5);\n EuclideanDigraph.Vertex vertex2 = euclideanDigraph.new Vertex(2, 8.4, 1.3);\n EuclideanDigraph.Vertex vertex3 = euclideanDigraph.new Vertex(3, 8.4, 15.3);\n EuclideanDigraph.Vertex vertex4 = euclideanDigraph.new Vertex(4, 6.1, 15.3);\n EuclideanDigraph.Vertex vertex5 = euclideanDigraph.new Vertex(5, 7.2, 5.2);\n EuclideanDigraph.Vertex vertex6 = euclideanDigraph.new Vertex(6, 7.2, 8.4);\n\n euclideanDigraph.addVertex(vertex0);\n euclideanDigraph.addVertex(vertex1);\n euclideanDigraph.addVertex(vertex2);\n euclideanDigraph.addVertex(vertex3);\n euclideanDigraph.addVertex(vertex4);\n euclideanDigraph.addVertex(vertex5);\n euclideanDigraph.addVertex(vertex6);\n\n euclideanDigraph.addEdge(0, 1);\n euclideanDigraph.addEdge(2, 1);\n euclideanDigraph.addEdge(0, 2);\n euclideanDigraph.addEdge(3, 6);\n euclideanDigraph.addEdge(4, 6);\n euclideanDigraph.addEdge(3, 4);\n euclideanDigraph.addEdge(1, 5);\n euclideanDigraph.addEdge(5, 6);\n\n euclideanDigraph.show(0, 15, 0, 20, 0.5,\n 0.08, 0.4);\n StdOut.println(euclideanDigraph);\n }\n}\n", "support_files": [], "metadata": {"number": "4.2.31", "chapter": 4, "chapter_title": "Graphs", "section": 4.2, "section_title": "Directed Graphs", "type": "Creative Problem", "code_execution": false}} {"question": "Prove that you can rescale the weights by adding a positive constant to all of them or by multiplying them all by a positive constant without affecting the MST.", "answer": "4.3.1\n\nIt is possible to rescale the weights by adding a positive constant to all of them or multiplying them all by a positive constant without affecting the MST.\n\nProof by contradiction:\nConsider that after adding a positive constant to all weights (or multiplying them all by a positive constant) the new MST' is different from the original MST.\nThis would imply that there is a cut C in which edge e has the smallest weight in MST and edge f has the smallest weight in MST'. Since all weights increased the same amount, this is impossible.\n\nSolution 2 (based on https://algs4.cs.princeton.edu/43mst/):\nKruskal's algorithm accesses the edge weights only through the compareTo() method. Adding a positive constant to each weight (or multiplying by a positive constant) won't change the result of the compareTo() method.\n", "support_files": [], "metadata": {"number": "4.3.1", "chapter": 4, "chapter_title": "Graphs", "section": 4.3, "section_title": "Minimum Spanning Trees", "type": "Exercise", "code_execution": false}} {"question": "Draw all of the MSTs of the following graph, with all edge weights equal. The graph has vertices `1..8` and edges:\n\n`1-2, 1-3, 2-4, 3-4, 4-5, 3-6, 4-7, 5-8, 6-7, 7-8`.", "answer": "4.3.2\n\nMSTs:\n\n 1-2\n |\n3-4-5\n|\n6-7-8\n\n 1-2\n |\n3-4-5\n|\n6-7-8\n\n 1 2\n | |\n3-4-5\n|\n6-7-8\n\n 1-2\n | |\n3-4 5\n|\n6-7-8\n\n 1-2\n |\n3-4-5\n |\n6-7-8\n\n 1-2\n |\n3-4-5\n |\n6-7-8\n\n 1 2\n | |\n3-4-5\n |\n6-7-8\n\n 1-2\n | |\n3-4 5\n |\n6-7-8\n\n 1-2\n |\n3 4-5\n| |\n6-7-8\n\n 1-2\n |\n3 4-5\n| |\n6-7-8\n\n 1 2\n | |\n3 4-5\n| |\n6-7-8\n\n 1-2\n | |\n3 4 5\n| |\n6-7-8\n\n 1-2\n |\n3-4-5\n| |\n6 7-8\n\n 1-2\n |\n3-4-5\n| |\n6 7-8\n\n 1 2\n | |\n3-4-5\n| |\n6 7-8\n\n 1-2\n | |\n3-4 5\n| |\n6 7-8\n\n 1-2\n |\n3-4-5\n| |\n6-7 8\n\n 1-2\n |\n3-4-5\n| |\n6-7 8\n\n 1 2\n | |\n3-4-5\n| |\n6-7 8\n\n 1-2\n | |\n3-4 5\n| |\n6-7 8\n\n 1-2\n |\n3-4-5\n | |\n6-7 8\n\n 1-2\n |\n3-4-5\n | |\n6-7 8\n\n 1 2\n | |\n3-4-5\n | |\n6-7 8\n\n 1-2\n | |\n3-4 5\n | |\n6-7 8\n\n 1-2\n |\n3 4-5\n| | |\n6-7 8\n\n 1-2\n |\n3 4-5\n| | |\n6-7 8\n\n 1 2\n | |\n3 4-5\n| | |\n6-7 8\n\n 1-2\n | |\n3 4 5\n| | |\n6-7 8\n\n 1-2\n |\n3-4-5\n| | |\n6 7 8\n\n 1-2\n |\n3-4-5\n| | |\n6 7 8\n\n 1 2\n | |\n3-4-5\n| | |\n6 7 8\n\n 1-2\n | |\n3-4 5\n| | |\n6 7 8\n\n 1-2\n | |\n3-4 5\n| |\n6 7-8\n\n 1-2\n |\n3-4-5\n| |\n6 7-8\n\n 1-2\n |\n3-4-5\n| |\n6 7-8\n\n 1 2\n | |\n3-4-5\n| |\n6 7-8\n\n 1-2\n |\n3-4 5\n| | |\n6 7-8\n\n 1-2\n |\n3-4 5\n| | |\n6 7-8\n\n 1 2\n | |\n3-4 5\n| | |\n6 7-8\n\n 1-2\n | |\n3-4 5\n |\n6-7-8\n\n 1-2\n |\n3-4-5\n |\n6-7-8\n\n 1-2\n |\n3-4-5\n |\n6-7-8\n\n 1 2\n | |\n3-4-5\n |\n6-7-8\n\n 1-2\n | |\n3 4 5\n| |\n6-7-8\n\n 1-2\n |\n3-4 5\n| |\n6-7-8\n\n 1-2\n |\n3-4 5\n| |\n6-7-8\n\n 1 2\n | |\n3-4 5\n| |\n6-7-8\n\n 1-2\n |\n3 4-5\n| |\n6-7-8\n\n 1-2\n |\n3 4-5\n| |\n6-7-8\n\n 1 2\n | |\n3 4-5\n| |\n6-7-8\n\n 1-2\n |\n3-4 5\n | |\n6-7-8\n\n 1-2\n |\n3-4 5\n | |\n6-7-8\n\n 1 2\n | |\n3-4 5\n | |\n6-7-8\n\n 1-2\n |\n3 4 5\n| | |\n6-7-8\n\n 1-2\n |\n3 4 5\n| | |\n6-7-8\n\n 1 2\n | |\n3 4 5\n| | |\n6-7-8\n\nThanks to Miroier (https://github.com/Miroier) for adding the remaining MSTs.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/184\n", "support_files": [], "metadata": {"number": "4.3.2", "chapter": 4, "chapter_title": "Graphs", "section": 4.3, "section_title": "Minimum Spanning Trees", "type": "Exercise", "code_execution": false}} {"question": "Give the MST of the weighted graph obtained by deleting vertex 7 from tinyEWG.txt (see page 604).", "answer": "4.3.6\n\nMST\n\nVertex1 Vertex2 Weight\n0 2 0.26\n2 3 0.17\n1 3 0.29\n1 5 0.32\n4 5 0.35\n6 2 0.40\n", "support_files": [], "metadata": {"number": "4.3.6", "chapter": 4, "chapter_title": "Graphs", "section": 4.3, "section_title": "Minimum Spanning Trees", "type": "Exercise", "code_execution": false}} {"question": "Implement the constructor for EdgeWeightedGraph that reads a graph from the input stream, by suitably modifying the constructor from Graph (see page 526).", "answer": "package chapter4.section3;\n\nimport edu.princeton.cs.algs4.In;\nimport edu.princeton.cs.algs4.StdOut;\nimport util.Constants;\n\n/**\n * Created by Rene Argento on 07/11/17.\n */\npublic class Exercise9 {\n\n public class EdgeWeightedGraphWithInputStreamConstructor extends EdgeWeightedGraph {\n\n public EdgeWeightedGraphWithInputStreamConstructor(In in) {\n super(in.readInt());\n int edges = in.readInt();\n\n if (edges < 0) {\n throw new IllegalArgumentException(\"Number of edges must be nonnegative\");\n }\n\n for (int i = 0; i < edges; i++) {\n int vertex1 = in.readInt();\n int vertex2 = in.readInt();\n double weight = in.readDouble();\n\n Edge edge = new Edge(vertex1, vertex2, weight);\n addEdge(edge);\n }\n }\n }\n\n public static void main(String[] args) {\n String tinyEWGFilePath = Constants.FILES_PATH + Constants.TINY_EWG_FILE;\n Exercise9.EdgeWeightedGraphWithInputStreamConstructor edgeWeightedGraph =\n new Exercise9().new EdgeWeightedGraphWithInputStreamConstructor(new In(tinyEWGFilePath));\n StdOut.println(edgeWeightedGraph);\n }\n}\n", "support_files": [], "metadata": {"number": "4.3.9", "chapter": 4, "chapter_title": "Graphs", "section": 4.3, "section_title": "Minimum Spanning Trees", "type": "Exercise", "code_execution": false}} {"question": "Develop an EdgeWeightedGraph implementation for dense graphs that uses an adjacency-matrix (two-dimensional array of weights) representation. Disallow parallel edges.", "answer": "package chapter4.section3;\n\nimport chapter1.section3.Bag;\nimport edu.princeton.cs.algs4.In;\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 07/11/17.\n */\npublic class Exercise10 {\n\n public class EdgeWeightedGraphAdjacencyMatrix {\n\n private final int vertices;\n private int edges;\n private double[][] adjacent; // adjacency matrix that stores the edge weights\n // adjacent[i][j] = Double.POSITIVE_INFINITY if there is no direct edge\n // between vertex i and vertex j\n\n public EdgeWeightedGraphAdjacencyMatrix(int vertices) {\n this.vertices = vertices;\n edges = 0;\n adjacent = new double[vertices][vertices];\n\n for (int vertex1 = 0; vertex1 < vertices; vertex1++) {\n for (int vertex2 = 0; vertex2 < vertices; vertex2++) {\n adjacent[vertex1][vertex2] = Double.POSITIVE_INFINITY;\n }\n }\n }\n\n public EdgeWeightedGraphAdjacencyMatrix(In in) {\n this(in.readInt());\n int edges = in.readInt();\n\n if (edges < 0) {\n throw new IllegalArgumentException(\"Number of edges must be nonnegative\");\n }\n\n for (int i = 0; i < edges; i++) {\n int vertex1 = in.readInt();\n int vertex2 = in.readInt();\n double weight = in.readDouble();\n\n Edge edge = new Edge(vertex1, vertex2, weight);\n addEdge(edge);\n }\n }\n\n public int vertices() {\n return vertices;\n }\n\n public int edgesCount() {\n return edges;\n }\n\n public void addEdge(Edge edge) {\n int vertex1 = edge.either();\n int vertex2 = edge.other(vertex1);\n double weight = edge.weight();\n\n // Parallel edges are ignored\n if (hasEdge(vertex1, vertex2)) {\n return;\n }\n\n adjacent[vertex1][vertex2] = weight;\n adjacent[vertex2][vertex1] = weight;\n edges++;\n }\n\n public boolean hasEdge(int vertex1, int vertex2) {\n return adjacent[vertex1][vertex2] != Double.POSITIVE_INFINITY;\n }\n\n public Iterable adjacent(int vertex) {\n Bag adjacentEdges = new Bag<>();\n\n for (int i = 0; i < vertices; i++) {\n if (hasEdge(vertex, i)) {\n adjacentEdges.add(new Edge(vertex, i, adjacent[vertex][i]));\n }\n }\n\n return adjacentEdges;\n }\n\n public Iterable edges() {\n Bag edges = new Bag<>();\n\n for (int vertex = 0; vertex < vertices; vertex++) {\n for (Edge edge : adjacent(vertex)) {\n if (edge.other(vertex) > vertex) {\n edges.add(edge);\n }\n }\n }\n\n return edges;\n }\n\n @Override\n public String toString() {\n StringBuilder stringBuilder = new StringBuilder();\n\n for (int vertex = 0; vertex < vertices(); vertex++) {\n stringBuilder.append(vertex).append(\": \");\n\n for (Edge neighbor : adjacent(vertex)) {\n stringBuilder.append(neighbor).append(\" \");\n }\n stringBuilder.append(\"\\n\");\n }\n\n return stringBuilder.toString();\n }\n }\n\n public static void main(String[] args) {\n Exercise10.EdgeWeightedGraphAdjacencyMatrix edgeWeightedGraphAdjacencyMatrix =\n new Exercise10().new EdgeWeightedGraphAdjacencyMatrix(5);\n edgeWeightedGraphAdjacencyMatrix.addEdge(new Edge(0, 2, 0.35));\n edgeWeightedGraphAdjacencyMatrix.addEdge(new Edge(0, 4, 0.12));\n edgeWeightedGraphAdjacencyMatrix.addEdge(new Edge(1, 2, 0.99));\n edgeWeightedGraphAdjacencyMatrix.addEdge(new Edge(3, 2, 0.58));\n edgeWeightedGraphAdjacencyMatrix.addEdge(new Edge(4, 4, 0.1));\n edgeWeightedGraphAdjacencyMatrix.addEdge(new Edge(2, 4, 0.34));\n // Parallel edge - should be ignored\n edgeWeightedGraphAdjacencyMatrix.addEdge(new Edge(0, 4, 0.55));\n\n StdOut.println(\"Vertices: \" + edgeWeightedGraphAdjacencyMatrix.vertices() + \" Expected: 5\");\n StdOut.println(\"Edges: \" + edgeWeightedGraphAdjacencyMatrix.edgesCount() + \" Expected: 6\");\n StdOut.println(\"Has edge 2-3: \" + edgeWeightedGraphAdjacencyMatrix.hasEdge(2, 3) + \" Expected: true\");\n StdOut.println(\"Has edge 0-3: \" + edgeWeightedGraphAdjacencyMatrix.hasEdge(0, 3) + \" Expected: false\");\n\n StdOut.println(\"\\n\" + edgeWeightedGraphAdjacencyMatrix);\n\n StdOut.println(\"Expected:\\n\" +\n \"0: 0-4 0.12000 0-2 0.35000 \\n\" +\n \"1: 1-2 0.99000 \\n\" +\n \"2: 2-4 0.34000 2-3 0.58000 2-1 0.99000 2-0 0.35000 \\n\" +\n \"3: 3-2 0.58000 \\n\" +\n \"4: 4-4 0.10000 4-2 0.34000 4-0 0.12000\");\n }\n}\n", "support_files": [], "metadata": {"number": "4.3.10", "chapter": 4, "chapter_title": "Graphs", "section": 4.3, "section_title": "Minimum Spanning Trees", "type": "Exercise", "code_execution": false}} {"question": "Determine the amount of memory used by EdgeWeightedGraph to represent a graph with V vertices and E edges, using the memory-cost model of SECTION 1.4.", "answer": "4.3.11\n\nEdge\n* object overhead -> 16 bytes\n* int value (vertex1) -> 4 bytes\n* int value (vertex2) -> 4 bytes\n* double value (weight) -> 8 bytes\nAmount of memory needed: 16 + 4 + 4 + 8 = 32 bytes\n\nNode\n* object overhead -> 16 bytes\n* extra overhead for reference to the enclosing instance -> 8 bytes\n* Item reference (item) -> 8 bytes\n* Node reference (next) -> 8 bytes\nAmount of memory needed: 16 + 8 + 8 + 8 = 40 bytes\n\nBag\n* object overhead -> 16 bytes\n* Node reference (first) -> 8 bytes\n* int value (size) -> 4 bytes\n* padding -> 4 bytes\n* N Nodes -> 40N bytes (there will be 2 Nodes per Edge when computing the EdgeWeightedGraph memory, so this will become 80N)\n* Edge (item) -> 32N bytes\nAmount of memory needed: 16 + 8 + 4 + 4 + 40N + 32N = 72N + 32 bytes\n\nEdgeWeightedGraph\n* object overhead -> 16 bytes\n* int value (V) -> 4 bytes\n* int value (E) -> 4 bytes\n* Bag[] reference (adj) -> 8 bytes\n* Bag[] (adj)\n object overhead -> 16 bytes\n int value (length) -> 4 bytes\n padding -> 4 bytes\n Bag references -> 8V\n Bag -> 72E + 32 bytes -> There are V Bags in total, and they have 2E nodes (so we double the 40N bytes from the Nodes memory in Bag) -> 72E + 32V + 40E -> 112E + 32V\nAmount of memory needed: 16 + 4 + 4 + 8 + 16 + 4 + 4 + 8V + 112E + 32V = 112E + 40V + 56 bytes\n", "support_files": [], "metadata": {"number": "4.3.11", "chapter": 4, "chapter_title": "Graphs", "section": 4.3, "section_title": "Minimum Spanning Trees", "type": "Exercise", "code_execution": false}} {"question": "Suppose that a graph has distinct edge weights. Does its shortest edge have to belong to the MST? Can its longest edge belong to the MST? Does a min-weight edge on every cycle have to belong to the MST? Prove your answer to each question or give a counterexample.", "answer": "Considering a graph with distinct edge weights:\n\n* The lightest edge must belong to the MST. It is the unique minimum-weight edge across the cut that separates one of its endpoints from the rest of the graph, so the cut property forces it into every MST.\n\n* The heaviest edge can belong to the MST. Example: triangle `A-B-C-A` plus a leaf edge `C-E`, with weights `A-B = 1`, `A-C = 2`, `B-C = 3`, and `C-E = 100`. The edge `C-E` is the heaviest edge, but it is the only edge incident to `E`, so every spanning tree must include it.\n\n* A minimum-weight edge on some cycle does not necessarily belong to the MST. In the graph with edges `A-B = 1`, `B-D = 2`, `A-D = 3`, `A-C = 4`, `C-D = 5`, and `B-C = 6`, the edge `A-D` is the minimum-weight edge on cycle `A-C-D-A`, but the MST is `A-B, B-D, A-C`, so `A-D` is not in the MST.", "support_files": [], "metadata": {"number": "4.3.12", "chapter": 4, "chapter_title": "Graphs", "section": 4.3, "section_title": "Minimum Spanning Trees", "type": "Exercise", "code_execution": false}} {"question": "Given an MST for an edge-weighted graph G, suppose that an edge in G that does not disconnect G is deleted. Describe how to find an MST of the new graph in time proportional to E.", "answer": "4.3.14\n\nThere are 2 possible cases when an edge from G is deleted.\n\n1- Case 1: The deleted edge is not part of the given MST (this can be checked in linear time)\nIn this case the MST of the new graph remains the same as the original MST.\nThe only situations in which an MST would change would be if a new edge was added with less weight than an edge that is part of an MST or if one of the edges that are part of an MST were deleted.\n\n2- Case 2: The deleted edge is part of the given MST\nIn this case, the given MST is now divided in 2 connected components.\nCheck which vertices were connected by the deleted edge. Assuming that edge e was deleted and that it connected vertices v and w:\nRun a breadth-first search from vertex v and color all reached vertices blue (this can be done in O(E + V) time).\nNow check all edges (this can be done in O(E) time):\nIf an edge connects a blue vertex with a non-blue vertex, it is a candidate for being part of the new MST. Check its weight and see if it is the first weight checked or if it is less than all the other candidate edge weights.\nIf it is, store its weight and its reference.\nIn the end, after having checked all edges, add the candidate edge with the smallest weight to the MST, which will become an MST of the new graph.\n", "support_files": [], "metadata": {"number": "4.3.14", "chapter": 4, "chapter_title": "Graphs", "section": 4.3, "section_title": "Minimum Spanning Trees", "type": "Exercise", "code_execution": false}} {"question": "Suppose that you use a priority-queue implementation that maintains a sorted list. What would be the order of growth of the worst-case running time for Prim’s algorithm and for Kruskal’s algorithm for graphs with V vertices and E edges? When would this method be appropriate, if ever? Defend your answer.", "answer": "A sorted-list priority queue makes `delete-min` cheap but makes insertion and key updates expensive.\n\nFor lazy Prim's algorithm, edges are inserted into the priority queue. There can be `Theta(E)` insertions, each costing `Theta(E)` in the worst case to keep the list sorted, so the worst-case running time is `Theta(E^2)`.\n\nFor eager Prim's algorithm, the priority queue contains vertices. There are at most `V` items in the queue, but up to `E` insert/decrease-key operations, each costing `Theta(V)` with a sorted list, so the worst-case running time is `Theta(EV)`.\n\nFor Kruskal's algorithm, all `E` edges are inserted into the priority queue. Building the sorted list by repeated insertion costs `Theta(E^2)`, and the delete-min and union-find work is lower order, so the worst-case running time is `Theta(E^2)`.\n\nThis method is rarely appropriate for these algorithms unless the input is tiny or the edges are already sorted and the implementation can exploit that directly.", "support_files": [], "metadata": {"number": "4.3.19", "chapter": 4, "chapter_title": "Graphs", "section": 4.3, "section_title": "Minimum Spanning Trees", "type": "Exercise", "code_execution": false}} {"question": "True or false: At any point during the execution of Kruskal’s algorithm, each vertex is closer to some vertex in its subtree than to any vertex not in its subtree. Prove your answer.", "answer": "4.3.20\n\nAt any point during the execution of Kruskal's algorithm, each vertex is closer to some vertex in its subtree than to any vertex not in its subtree.\n\nTrue. Since Kruskal's algorithm adds edges to an MST by order of weight/length, if there is an edge e = v-w of length 1 and there is an edge f = v-z of length 2, there are two possible cases:\n\nCase 1: Edge e is chosen before edge f.\nIn this case, vertex v is closer to a vertex in its subtree (vertex w) than to a vertex not in its subtree (vertex z).\n\nCase 2: Edge f is chosen before edge e.\nThis can only happen if choosing edge e would generate a cycle. But in order to generate a cycle there must be another vertex connected to both vertex v and vertex w. Let's call this vertex a. If vertex a is already connected to vertex v this means that the length of the edge connecting v-a is smaller than the length of edge e. Therefore, even in this case vertex v is closer to a vertex in its subtree (vertex a) than to a vertex not in its subtree (both vertices w and z).\n", "support_files": [], "metadata": {"number": "4.3.20", "chapter": 4, "chapter_title": "Graphs", "section": 4.3, "section_title": "Minimum Spanning Trees", "type": "Exercise", "code_execution": false}} {"question": "Provide an implementation of edges() for PrimMST (page 622).", "answer": "This method belongs inside `PrimMST`, where `edgeTo[]` is available. Enqueue every non-null edge; vertex 0 usually has no incoming MST edge.\n\n```java\npublic Iterable edges() {\n Queue mst = new Queue();\n for (int v = 0; v < edgeTo.length; v++) {\n if (edgeTo[v] != null) mst.enqueue(edgeTo[v]);\n }\n return mst;\n}\n```\n\nImplementing this as a subclass is not correct if `edgeTo` is private in `PrimMST`.", "support_files": [], "metadata": {"number": "4.3.21", "chapter": 4, "chapter_title": "Graphs", "section": 4.3, "section_title": "Minimum Spanning Trees", "type": "Exercise", "code_execution": false}} {"question": "Reverse-delete algorithm. Develop an implementation that computes the MST as follows: Start with a graph containing all of the edges. Then repeatedly go through the edges in decreasing order of weight. For each edge, check if deleting that edge will disconnect the graph; if not, delete it. Prove that this algorithm computes the MST. What is the order of growth of the number of edge-weight compares performed by your implementation?", "answer": "// Exercise24_ReverseDeleteAlgorithm.java\npackage chapter4.section3;\n\nimport chapter1.section3.Queue;\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\n/**\n * Created by Rene Argento on 09/11/17.\n */\npublic class Exercise24_ReverseDeleteAlgorithm {\n\n // O(E * (V + E)) = O(E^2)\n public Queue minimumSpanningTreeWithReverseDelete(EdgeWeightedGraphWithDelete edgeWeightedGraph) {\n List edgesList = new ArrayList<>();\n for (Edge edge : edgeWeightedGraph.edges()) {\n edgesList.add(edge);\n }\n edgesList.sort(Collections.reverseOrder());\n\n for (Edge edge : edgesList) {\n edgeWeightedGraph.deleteEdge(edge);\n\n ConnectedComponentsEdgeWeightedGraph connectedComponentsEdgeWeightedGraph =\n new ConnectedComponentsEdgeWeightedGraph(edgeWeightedGraph);\n // If deleting the edge disconnected the graph, re-add it\n if (connectedComponentsEdgeWeightedGraph.count() > 1) {\n edgeWeightedGraph.addEdge(edge);\n }\n }\n\n Queue minimumSpanningTree = new Queue<>();\n for (Edge edge : edgeWeightedGraph.edges()) {\n minimumSpanningTree.enqueue(edge);\n }\n return minimumSpanningTree;\n }\n\n public static void main(String[] args) {\n Exercise24_ReverseDeleteAlgorithm reverseDeleteAlgorithm = new Exercise24_ReverseDeleteAlgorithm();\n\n EdgeWeightedGraphWithDelete edgeWeightedGraph1 = new EdgeWeightedGraphWithDelete(5);\n edgeWeightedGraph1.addEdge(new Edge(0, 1, 0.42));\n edgeWeightedGraph1.addEdge(new Edge(1, 2, 0.12));\n edgeWeightedGraph1.addEdge(new Edge(2, 3, 0.5));\n edgeWeightedGraph1.addEdge(new Edge(3, 4, 0.8));\n edgeWeightedGraph1.addEdge(new Edge(3, 4, 0.82));\n edgeWeightedGraph1.addEdge(new Edge(4, 4, 0.1));\n\n EdgeWeightedGraphWithDelete edgeWeightedGraph2 = new EdgeWeightedGraphWithDelete(9);\n edgeWeightedGraph2.addEdge(new Edge(0, 1, 0.3));\n edgeWeightedGraph2.addEdge(new Edge(1, 2, 0.41));\n\n edgeWeightedGraph2.addEdge(new Edge(2, 5, 0.2));\n edgeWeightedGraph2.addEdge(new Edge(5, 3, 0.11));\n edgeWeightedGraph2.addEdge(new Edge(3, 4, 0.25));\n edgeWeightedGraph2.addEdge(new Edge(2, 4, 0.76));\n edgeWeightedGraph2.addEdge(new Edge(4, 4, 0.1));\n\n edgeWeightedGraph2.addEdge(new Edge(5, 6, 0.33));\n edgeWeightedGraph2.addEdge(new Edge(6, 8, 0.99));\n edgeWeightedGraph2.addEdge(new Edge(6, 7, 0.77));\n edgeWeightedGraph2.addEdge(new Edge(7, 8, 0.2));\n\n StdOut.println(\"Reverse-delete Minimum Spanning Tree 1\");\n\n Queue minimumSpanningTree1 = reverseDeleteAlgorithm.minimumSpanningTreeWithReverseDelete(edgeWeightedGraph1);\n\n for (Edge edge : minimumSpanningTree1) {\n StdOut.println(edge);\n }\n\n StdOut.println(\"\\nExpected:\\n\" +\n \"3-4 0.80000\\n\" +\n \"2-3 0.50000\\n\" +\n \"1-2 0.12000\\n\" +\n \"0-1 0.42000\\n\");\n\n StdOut.println(\"Reverse-delete Minimum Spanning Tree 2\");\n\n Queue minimumSpanningTree2 = reverseDeleteAlgorithm.minimumSpanningTreeWithReverseDelete(edgeWeightedGraph2);\n\n for (Edge edge : minimumSpanningTree2) {\n StdOut.println(edge);\n }\n\n StdOut.println(\"\\nExpected:\\n\" +\n \"7-8 0.20000\\n\" +\n \"6-7 0.77000\\n\" +\n \"5-6 0.33000\\n\" +\n \"5-3 0.11000\\n\" +\n \"3-4 0.25000\\n\" +\n \"2-5 0.20000\\n\" +\n \"1-2 0.41000\\n\" +\n \"0-1 0.30000\");\n }\n}\n\nAdditional notes/results:\n4.3.24 - Reverse-delete algorithm\n\nThe reverse-delete algorithm starts with a graph containing all the edges.\nIt then repeatedly goes through the edges in decreasing order of weight.\nFor each edge, it checks if deleting that edge will disconnect the graph; if not it deletes it.\n\nProof of correctness:\nThe graph edges are evaluated in decreasing order of weight.\nConsider by contradiction that there is an edge e that is the maximum-weight edge in a cycle C and that\nthe reverse-delete algorithm does not delete it once it is evaluated (note that during normal operation the algorithm would delete it,\nsince it is part of a cycle and its removal does not disconnect the graph).\nThis means that another edge in cycle C will be deleted before the algorithm finishes the computation of the MST, since an MST cannot contain any cycles.\nLet's assume that edge f is deleted. Since the edges are evaluated in decreasing order of weight and e is the\nmaximum-weight edge in C, weight(f) < weight(e).\nNow, after the MST computation (let's call it MST1) is complete, re-add edge f.\nThis will generate cycle C again in MST1.\nIf this time we remove edge e instead of edge f, the new MST (let's call it MST2) weight will be less than the weight of MST1\n(because weight(f) < weight(e)). This contradicts the minimality of MST1.\n\nThe order of growth of the number of edge-weight compares performed by the reverse-delete algorithm is O(E lg E).\nThis is because edge weight compares are only made when the array of edges is sorted in decreasing order.", "support_files": [], "metadata": {"number": "4.3.24", "chapter": 4, "chapter_title": "Graphs", "section": 4.3, "section_title": "Minimum Spanning Trees", "type": "Creative Problem", "code_execution": false}} {"question": "Animations. Write a client program that does dynamic graphical animations of MST algorithms. Run your program for mediumEWG.txt to produce images like the figures on page 621 and page 624.", "answer": "// Exercise27_Animations_Kruskal.java\npackage chapter4.section3;\n\nimport chapter1.section3.Queue;\nimport chapter1.section5.UnionFind;\nimport chapter2.section4.PriorityQueueResize;\nimport edu.princeton.cs.algs4.In;\nimport edu.princeton.cs.algs4.StdDraw;\nimport edu.princeton.cs.algs4.StdRandom;\nimport util.Constants;\n\nimport java.awt.*;\n\n/**\n * Created by Rene Argento on 11/11/17.\n */\npublic class Exercise27_Animations_Kruskal {\n\n private class Coordinate {\n double xCoordinate;\n double yCoordinate;\n\n Coordinate(double xCoordinate, double yCoordinate) {\n this.xCoordinate = xCoordinate;\n this.yCoordinate = yCoordinate;\n }\n }\n\n public class KruskalMSTAnimations {\n\n private Queue minimumSpanningTree;\n private double weight;\n\n private double radiusOfCircleAroundVertex;\n\n public KruskalMSTAnimations(EdgeWeightedGraph edgeWeightedGraph, double xScaleLow, double xScaleHigh,\n double yScaleLow, double yScaleHigh, double radiusOfCircleAroundVertex) {\n minimumSpanningTree = new Queue<>();\n PriorityQueueResize priorityQueue = new PriorityQueueResize<>(PriorityQueueResize.Orientation.MIN);\n\n UnionFind unionFind = new UnionFind(edgeWeightedGraph.vertices());\n\n this.radiusOfCircleAroundVertex = radiusOfCircleAroundVertex;\n\n Coordinate[] randomCoordinates = getRandomCoordinates(edgeWeightedGraph);\n initCanvas(xScaleLow, xScaleHigh, yScaleLow, yScaleHigh);\n\n drawVertices(randomCoordinates, -1, unionFind);\n drawInitialEdges(edgeWeightedGraph, randomCoordinates);\n\n for (Edge edge : edgeWeightedGraph.edges()) {\n priorityQueue.insert(edge);\n }\n\n while (!priorityQueue.isEmpty() && minimumSpanningTree.size() < edgeWeightedGraph.vertices() - 1) {\n Edge edge = priorityQueue.deleteTop(); // Get lowest-weight edge from priority queue\n int vertex1 = edge.either();\n int vertex2 = edge.other(vertex1);\n\n // Ignore ineligible edges\n if (unionFind.connected(vertex1, vertex2)) {\n continue;\n }\n\n drawEdgeInMST(vertex1, vertex2, randomCoordinates);\n drawVertices(randomCoordinates, vertex1, unionFind);\n\n unionFind.union(vertex1, vertex2);\n minimumSpanningTree.enqueue(edge); // Add edge to the minimum spanning tree\n\n weight += edge.weight();\n }\n\n // Re-draw vertices to clean up the radius around their labels\n drawVertices(randomCoordinates, -1, unionFind);\n }\n\n public Iterable edges() {\n return minimumSpanningTree;\n }\n\n public double lazyWeight() {\n double weight = 0;\n\n for (Edge edge : edges()) {\n weight += edge.weight();\n }\n\n return weight;\n }\n\n public double eagerWeight() {\n return weight;\n }\n\n private void initCanvas(double xScaleLow, double xScaleHigh, double yScaleLow, double yScaleHigh) {\n // Set canvas size\n// StdDraw.setCanvasSize(500, 400); // Use this dimension for tinyEWG.txt\n StdDraw.setCanvasSize(1000, 1000);\n StdDraw.setXscale(xScaleLow, xScaleHigh);\n StdDraw.setYscale(yScaleLow, yScaleHigh);\n }\n\n private Coordinate[] getRandomCoordinates(EdgeWeightedGraph edgeWeightedGraph) {\n Coordinate[] vertexCoordinates = new Coordinate[edgeWeightedGraph.vertices()];\n\n for (int vertex = 0; vertex < edgeWeightedGraph.vertices(); vertex++) {\n // tinyEWG coordinates\n// double randomXCoordinate = StdRandom.uniform();\n// double randomYCoordinate = StdRandom.uniform();\n\n double randomXCoordinate = StdRandom.uniform(1000);\n double randomYCoordinate = StdRandom.uniform(1000);\n\n vertexCoordinates[vertex] = new Coordinate(randomXCoordinate, randomYCoordinate);\n }\n\n return vertexCoordinates;\n }\n\n private void drawVertices(Coordinate[] coordinates, int cutSet1Vertex, UnionFind unionFind) {\n int cutSet1Id = -1;\n\n if (cutSet1Vertex != -1) {\n cutSet1Id = unionFind.find(cutSet1Vertex);\n }\n\n StdDraw.setPenRadius(0.002D);\n\n for (int vertexId = 0; vertexId < coordinates.length; vertexId++) {\n\n if (unionFind.find(vertexId) == cutSet1Id) {\n StdDraw.setPenColor(Color.LIGHT_GRAY);\n } else {\n StdDraw.setPenColor(Color.WHITE);\n }\n StdDraw.filledCircle(coordinates[vertexId].xCoordinate, coordinates[vertexId].yCoordinate,\n radiusOfCircleAroundVertex);\n\n StdDraw.setPenColor(Color.BLACK);\n StdDraw.circle(coordinates[vertexId].xCoordinate, coordinates[vertexId].yCoordinate,\n radiusOfCircleAroundVertex);\n\n StdDraw.setPenColor(Color.BLACK);\n StdDraw.text(coordinates[vertexId].xCoordinate, coordinates[vertexId].yCoordinate,\n String.valueOf(vertexId));\n }\n }\n\n private void drawInitialEdges(EdgeWeightedGraph edgeWeightedGraph, Coordinate[] coordinates) {\n StdDraw.setPenRadius(0.003D);\n StdDraw.setPenColor(Color.LIGHT_GRAY);\n\n for (int vertex = 0; vertex < edgeWeightedGraph.vertices(); vertex++) {\n for (Edge edge : edgeWeightedGraph.adjacent(vertex)) {\n int otherVertex = edge.other(vertex);\n\n if (vertex > otherVertex) {\n StdDraw.line(coordinates[vertex].xCoordinate, coordinates[vertex].yCoordinate,\n coordinates[otherVertex].xCoordinate, coordinates[otherVertex].yCoordinate);\n }\n }\n }\n sleep();\n }\n\n private void drawEdgeInMST(int vertex1, int vertex2, Coordinate[] coordinates) {\n StdDraw.setPenRadius(0.005D);\n StdDraw.setPenColor(Color.RED);\n\n StdDraw.line(coordinates[vertex1].xCoordinate, coordinates[vertex1].yCoordinate,\n coordinates[vertex2].xCoordinate, coordinates[vertex2].yCoordinate);\n\n sleep();\n\n StdDraw.setPenColor(Color.BLACK);\n StdDraw.line(coordinates[vertex1].xCoordinate, coordinates[vertex1].yCoordinate,\n coordinates[vertex2].xCoordinate, coordinates[vertex2].yCoordinate);\n\n sleep();\n }\n\n private void sleep() {\n try {\n Thread.sleep(100);\n// Thread.sleep(1000); // Use this timer for tinyEWG.txt\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n\n }\n\n public static void main(String[] args) {\n// String filePath = Constants.FILES_PATH + Constants.TINY_EWG_FILE;\n String filePath = Constants.FILES_PATH + Constants.MEDIUM_EWG_FILE;\n EdgeWeightedGraph edgeWeightedGraph = new EdgeWeightedGraph(new In(filePath));\n\n// new Exercise27_Animations_Kruskal().new KruskalMSTAnimations(edgeWeightedGraph, -0.1, 1.1,\n// -0.1, 1.1, 0.04); // Use these dimensions for tinyEWG.txt\n new Exercise27_Animations_Kruskal().new KruskalMSTAnimations(edgeWeightedGraph, -1, 1001,\n -1, 1001, 15);\n }\n}\n\n// Exercise27_Animations_Prim.java\npackage chapter4.section3;\n\nimport chapter1.section3.Queue;\nimport chapter2.section4.IndexMinPriorityQueue;\nimport chapter3.section5.HashSet;\nimport edu.princeton.cs.algs4.In;\nimport edu.princeton.cs.algs4.StdDraw;\nimport edu.princeton.cs.algs4.StdRandom;\nimport util.Constants;\n\nimport java.awt.*;\n\n/**\n * Created by Rene Argento on 10/11/17.\n */\npublic class Exercise27_Animations_Prim {\n\n private class Coordinate {\n double xCoordinate;\n double yCoordinate;\n\n Coordinate(double xCoordinate, double yCoordinate) {\n this.xCoordinate = xCoordinate;\n this.yCoordinate = yCoordinate;\n }\n }\n\n public class PrimMSTAnimations {\n\n private Edge[] edgeTo; // shortest edge from tree vertex\n private double[] distTo; // distTo[vertex] = edgeTo[vertex].weight()\n private boolean[] marked; // true if vertex is on the minimum spanning tree\n private IndexMinPriorityQueue priorityQueue; // eligible crossing edges\n\n private double weight;\n private double radiusOfCircleAroundVertex;\n private HashSet verticesInMST;\n\n public PrimMSTAnimations(EdgeWeightedGraph edgeWeightedGraph, double xScaleLow, double xScaleHigh,\n double yScaleLow, double yScaleHigh, double radiusOfCircleAroundVertex) {\n edgeTo = new Edge[edgeWeightedGraph.vertices()];\n distTo = new double[edgeWeightedGraph.vertices()];\n marked = new boolean[edgeWeightedGraph.vertices()];\n this.radiusOfCircleAroundVertex = radiusOfCircleAroundVertex;\n verticesInMST = new HashSet<>();\n\n Coordinate[] randomCoordinates = getRandomCoordinates(edgeWeightedGraph);\n initCanvas(xScaleLow, xScaleHigh, yScaleLow, yScaleHigh);\n\n drawInitialVertices(randomCoordinates);\n drawInitialEdges(edgeWeightedGraph, randomCoordinates);\n\n for (int vertex = 0; vertex < edgeWeightedGraph.vertices(); vertex++) {\n distTo[vertex] = Double.POSITIVE_INFINITY;\n }\n priorityQueue = new IndexMinPriorityQueue<>(edgeWeightedGraph.vertices());\n\n // Initialize priority queue with 0, weight 0\n distTo[0] = 0;\n priorityQueue.insert(0, 0.0);\n\n while (!priorityQueue.isEmpty()) {\n // Add closest vertex to the minimum spanning tree\n int vertexToVisit = priorityQueue.deleteMin();\n\n visit(edgeWeightedGraph, vertexToVisit, randomCoordinates);\n verticesInMST.add(vertexToVisit);\n\n // Draw current graph and MST\n if (!priorityQueue.isEmpty()) {\n int nextVertexInMST = priorityQueue.minIndex();\n int vertexConnectedToNextVertexInMST = edgeTo[nextVertexInMST].other(nextVertexInMST);\n\n drawEdgeInMST(vertexConnectedToNextVertexInMST, nextVertexInMST, randomCoordinates);\n drawCandidateEdgesToMST(edgeTo, randomCoordinates, nextVertexInMST);\n }\n }\n\n // Re-draw vertices to clean up the radius around their labels\n drawVerticesInMST(randomCoordinates);\n }\n\n private void initCanvas(double xScaleLow, double xScaleHigh, double yScaleLow, double yScaleHigh) {\n // Set canvas size\n// StdDraw.setCanvasSize(500, 400); // Use this dimension for tinyEWG.txt\n StdDraw.setCanvasSize(1000, 1000);\n StdDraw.setXscale(xScaleLow, xScaleHigh);\n StdDraw.setYscale(yScaleLow, yScaleHigh);\n }\n\n private Coordinate[] getRandomCoordinates(EdgeWeightedGraph edgeWeightedGraph) {\n Coordinate[] vertexCoordinates = new Coordinate[edgeWeightedGraph.vertices()];\n\n for (int vertex = 0; vertex < edgeWeightedGraph.vertices(); vertex++) {\n // tinyEWG coordinates\n// double randomXCoordinate = StdRandom.uniform();\n// double randomYCoordinate = StdRandom.uniform();\n\n double randomXCoordinate = StdRandom.uniform(1000);\n double randomYCoordinate = StdRandom.uniform(1000);\n\n vertexCoordinates[vertex] = new Coordinate(randomXCoordinate, randomYCoordinate);\n }\n\n return vertexCoordinates;\n }\n\n private void drawInitialVertices(Coordinate[] coordinates) {\n for (int vertexId = 0; vertexId < coordinates.length; vertexId++) {\n\n StdDraw.setPenColor(Color.LIGHT_GRAY);\n StdDraw.filledCircle(coordinates[vertexId].xCoordinate, coordinates[vertexId].yCoordinate,\n radiusOfCircleAroundVertex);\n\n StdDraw.setPenColor(Color.BLACK);\n StdDraw.circle(coordinates[vertexId].xCoordinate, coordinates[vertexId].yCoordinate,\n radiusOfCircleAroundVertex);\n\n StdDraw.setPenColor(Color.BLACK);\n StdDraw.text(coordinates[vertexId].xCoordinate, coordinates[vertexId].yCoordinate,\n String.valueOf(vertexId));\n }\n }\n\n private void drawVerticesInMST(Coordinate[] coordinates) {\n StdDraw.setPenRadius(0.002D);\n\n for (int vertexId : verticesInMST.keys()) {\n StdDraw.setPenColor(Color.WHITE);\n StdDraw.filledCircle(coordinates[vertexId].xCoordinate, coordinates[vertexId].yCoordinate,\n radiusOfCircleAroundVertex);\n\n StdDraw.setPenColor(Color.BLACK);\n StdDraw.circle(coordinates[vertexId].xCoordinate, coordinates[vertexId].yCoordinate,\n radiusOfCircleAroundVertex);\n\n StdDraw.setPenColor(Color.BLACK);\n StdDraw.text(coordinates[vertexId].xCoordinate, coordinates[vertexId].yCoordinate,\n String.valueOf(vertexId));\n }\n }\n\n private void visit(EdgeWeightedGraph edgeWeightedGraph, int vertex, Coordinate[] coordinates) {\n // Add vertex to the minimum spanning tree; update data structures\n marked[vertex] = true;\n\n for (Edge edge : edgeWeightedGraph.adjacent(vertex)) {\n int otherVertex = edge.other(vertex);\n if (marked[otherVertex]) {\n // Only draw an ineligible edge if this edge is not part of the MST\n if (edgeTo[vertex].other(vertex) != otherVertex) {\n drawIneligibleEdge(vertex, otherVertex, coordinates);\n }\n\n continue; // vertex-otherVertex is ineligible\n }\n\n if (edge.weight() < distTo[otherVertex]) {\n // If there is another edge candidate for the MST connected to otherVertex, draw it as ineligible\n if (edgeTo[otherVertex] != null) {\n int previousBestVertexConnectedToOtherVertex = edgeTo[otherVertex].other(otherVertex);\n drawIneligibleEdge(previousBestVertexConnectedToOtherVertex, otherVertex, coordinates);\n }\n\n // Edge edge is the new best connection from the minimum spanning tree to otherVertex\n if (distTo[otherVertex] != Double.POSITIVE_INFINITY) {\n weight -= distTo[otherVertex];\n }\n weight += edge.weight();\n\n edgeTo[otherVertex] = edge;\n distTo[otherVertex] = edge.weight();\n\n if (priorityQueue.contains(otherVertex)) {\n priorityQueue.decreaseKey(otherVertex, distTo[otherVertex]);\n } else {\n priorityQueue.insert(otherVertex, distTo[otherVertex]);\n }\n } else {\n drawIneligibleEdge(vertex, otherVertex, coordinates);\n }\n }\n }\n\n public Iterable edges() {\n Queue minimumSpanningTree = new Queue<>();\n\n for (int vertex = 1; vertex < edgeTo.length; vertex++) {\n minimumSpanningTree.enqueue(edgeTo[vertex]);\n }\n\n return minimumSpanningTree;\n }\n\n public double lazyWeight() {\n double weight = 0;\n\n for (Edge edge : edges()) {\n weight += edge.weight();\n }\n return weight;\n }\n\n public double eagerWeight() {\n return weight;\n }\n\n private void drawInitialEdges(EdgeWeightedGraph edgeWeightedGraph, Coordinate[] coordinates) {\n StdDraw.setPenRadius(0.002D);\n StdDraw.setPenColor(Color.BLACK);\n\n for (int vertex = 0; vertex < edgeWeightedGraph.vertices(); vertex++) {\n for (Edge edge : edgeWeightedGraph.adjacent(vertex)) {\n int otherVertex = edge.other(vertex);\n\n if (vertex > otherVertex) {\n StdDraw.line(coordinates[vertex].xCoordinate, coordinates[vertex].yCoordinate,\n coordinates[otherVertex].xCoordinate, coordinates[otherVertex].yCoordinate);\n }\n }\n }\n sleep();\n }\n\n private void drawCandidateEdgesToMST(Edge[] edgeTo, Coordinate[] coordinates, int nextVertexInMST) {\n for (Edge edge : edgeTo) {\n if (edge == null) {\n continue;\n }\n\n int vertex1 = edge.either();\n int vertex2 = edge.other(vertex1);\n\n if (vertex1 == nextVertexInMST || vertex2 == nextVertexInMST) {\n //Already colored and in MST\n continue;\n }\n\n if (!marked[vertex1] || !marked[vertex2]) {\n StdDraw.setPenRadius(0.002D);\n StdDraw.setPenColor(Color.RED);\n\n StdDraw.line(coordinates[vertex2].xCoordinate, coordinates[vertex2].yCoordinate,\n coordinates[vertex1].xCoordinate, coordinates[vertex1].yCoordinate);\n }\n }\n\n drawVerticesInMST(coordinates);\n sleep();\n }\n\n private void drawEdgeInMST(int vertex1, int vertex2, Coordinate[] coordinates) {\n StdDraw.setPenRadius(0.007D);\n StdDraw.setPenColor(Color.RED);\n\n StdDraw.line(coordinates[vertex1].xCoordinate, coordinates[vertex1].yCoordinate,\n coordinates[vertex2].xCoordinate, coordinates[vertex2].yCoordinate);\n sleep();\n\n StdDraw.setPenColor(Color.BLACK);\n StdDraw.line(coordinates[vertex1].xCoordinate, coordinates[vertex1].yCoordinate,\n coordinates[vertex2].xCoordinate, coordinates[vertex2].yCoordinate);\n drawVerticesInMST(coordinates);\n sleep();\n }\n\n private void drawIneligibleEdge(int vertex1, int vertex2, Coordinate[] coordinates) {\n StdDraw.setPenRadius(0.005D);\n StdDraw.setPenColor(Color.LIGHT_GRAY);\n\n StdDraw.line(coordinates[vertex1].xCoordinate, coordinates[vertex1].yCoordinate,\n coordinates[vertex2].xCoordinate, coordinates[vertex2].yCoordinate);\n }\n\n private void sleep() {\n try {\n Thread.sleep(100);\n// Thread.sleep(1000); // Use this timer for tinyEWG.txt\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n }\n\n public static void main(String[] args) {\n// String filePath = Constants.FILES_PATH + Constants.TINY_EWG_FILE;\n String filePath = Constants.FILES_PATH + Constants.MEDIUM_EWG_FILE;\n EdgeWeightedGraph edgeWeightedGraph = new EdgeWeightedGraph(new In(filePath));\n\n// new Exercise27_Animations_Prim().new PrimMSTAnimations(edgeWeightedGraph, -0.1, 1.1,\n// -0.1, 1.1, 0.04); // Use these dimensions for tinyEWG.txt\n new Exercise27_Animations_Prim().new PrimMSTAnimations(edgeWeightedGraph, -1, 1001,\n -1, 1001, 15);\n }\n}\n", "support_files": [], "metadata": {"number": "4.3.27", "chapter": 4, "chapter_title": "Graphs", "section": 4.3, "section_title": "Minimum Spanning Trees", "type": "Creative Problem", "code_execution": false}} {"question": "Space-efficient data structures. Develop an implementation of the lazy version of Prim’s algorithm that saves space by using lower-level data structures for EdgeWeightedGraph and for MinPQ instead of Bag and Edge. Estimate the amount of memory saved as a function of V and E, using the memory-cost model of SECTION 1.4 (see EXERCISE 4.3.11).", "answer": "// Exercise28_SpaceEfficientDataStructures.java\npackage chapter4.section3;\n\nimport chapter1.section3.Bag;\nimport chapter1.section3.Queue;\nimport chapter2.section4.PriorityQueueResize;\nimport edu.princeton.cs.algs4.In;\nimport edu.princeton.cs.algs4.StdOut;\n\nimport static chapter4.section3.Exercise28_SpaceEfficientDataStructures.EdgeWeightedGraphSpaceEfficient.NO_CONNECTION;\n\n/**\n * Created by Rene Argento on 11/11/17.\n */\npublic class Exercise28_SpaceEfficientDataStructures {\n\n // Also used on exercise 4.3.40\n public interface EdgeWeightedGraphSpaceEfficientInterface {\n int vertices();\n int edgesCount();\n void addEdge(Edge edge);\n double[] adjacent(int vertex);\n Iterable edges();\n }\n\n // Space efficient version of EdgeWeightedGraph\n // Trade-offs: does not support parallel edges, adjacent() operation takes O(V) instead of O(degree(V))\n // In case of parallel edges, only the edge with minimum weight will be stored\n @SuppressWarnings(\"unchecked\")\n public class EdgeWeightedGraphSpaceEfficient implements EdgeWeightedGraphSpaceEfficientInterface {\n\n private final int vertices;\n private int edges;\n private double[][] adjacent;\n\n public static final double NO_CONNECTION = Double.POSITIVE_INFINITY;\n\n public EdgeWeightedGraphSpaceEfficient(int vertices) {\n this.vertices = vertices;\n edges = 0;\n adjacent = new double[vertices][vertices];\n\n for (int vertex = 0; vertex < vertices; vertex++) {\n adjacent[vertex] = new double[vertices];\n\n for (int adjacentVertex = 0; adjacentVertex < vertices; adjacentVertex++) {\n adjacent[vertex][adjacentVertex] = NO_CONNECTION;\n }\n }\n }\n\n public EdgeWeightedGraphSpaceEfficient(In in) {\n this(in.readInt());\n int edges = in.readInt();\n\n if (edges < 0) {\n throw new IllegalArgumentException(\"Number of edges must be nonnegative\");\n }\n\n for (int i = 0; i < edges; i++) {\n int vertex1 = in.readInt();\n int vertex2 = in.readInt();\n double weight = in.readDouble();\n\n Edge edge = new Edge(vertex1, vertex2, weight);\n addEdge(edge);\n }\n }\n\n public int vertices() {\n return vertices;\n }\n\n public int edgesCount() {\n return edges;\n }\n\n public void addEdge(Edge edge) {\n int vertex1 = edge.either();\n int vertex2 = edge.other(vertex1);\n\n if (adjacent[vertex1][vertex2] != NO_CONNECTION) {\n if (adjacent[vertex1][vertex2] <= edge.weight()) {\n return;\n }\n edges--;\n }\n\n adjacent[vertex1][vertex2] = edge.weight();\n adjacent[vertex2][vertex1] = edge.weight();\n edges++;\n }\n\n public double[] adjacent(int vertex) {\n return adjacent[vertex];\n }\n\n public Iterable edges() {\n Bag edges = new Bag<>();\n\n for (int vertex1 = 0; vertex1 < vertices; vertex1++) {\n for (int vertex2 = vertex1 + 1; vertex2 < vertices; vertex2++) {\n if (adjacent[vertex1][vertex2] != NO_CONNECTION) {\n edges.add(new Edge(vertex1, vertex2, adjacent[vertex1][vertex2]));\n }\n }\n }\n return edges;\n }\n\n @Override\n public String toString() {\n StringBuilder stringBuilder = new StringBuilder();\n\n for (int vertex1 = 0; vertex1 < vertices; vertex1++) {\n stringBuilder.append(vertex1).append(\": \");\n\n for (int vertex2 = 0; vertex2 < vertices; vertex2++) {\n if (adjacent[vertex1][vertex2] != NO_CONNECTION) {\n String formattedEdge = String.format(\"%d-%d %.5f\", vertex1, vertex2, adjacent[vertex1][vertex2]);\n stringBuilder.append(formattedEdge).append(\" \");\n }\n }\n stringBuilder.append(\"\\n\");\n }\n return stringBuilder.toString();\n }\n }\n\n // Space efficient version of lazy Prim's algorithm\n // Trade-off: it has runtime complexity of O(E * V^2)\n public class LazyPrimMSTSpaceEfficient {\n private boolean[] marked; // minimum spanning tree vertices\n private Queue minimumSpanningTree;\n private PriorityQueueResize priorityQueue; // crossing (and ineligible) edge weights\n\n private double weight;\n\n public LazyPrimMSTSpaceEfficient(EdgeWeightedGraphSpaceEfficientInterface edgeWeightedGraph) {\n priorityQueue = new PriorityQueueResize<>(PriorityQueueResize.Orientation.MIN);\n marked = new boolean[edgeWeightedGraph.vertices()];\n minimumSpanningTree = new Queue<>();\n\n visit(edgeWeightedGraph, 0); // assumes the graph is connected\n\n while (!priorityQueue.isEmpty()) {\n Double minEdgeWeight = priorityQueue.deleteTop(); // Get lowest-weight edge from priority queue\n\n boolean isMinWeightEdgeEligible = false;\n\n Edge edgeToAddInMST = null;\n\n for (int vertex = 0; vertex < edgeWeightedGraph.vertices(); vertex++) {\n double[] adjacentEdges = edgeWeightedGraph.adjacent(vertex);\n\n for (int otherVertex = 0; otherVertex < adjacentEdges.length; otherVertex++) {\n double edgeWeight = adjacentEdges[otherVertex];\n\n if (edgeWeight == NO_CONNECTION) {\n continue;\n }\n\n if (edgeWeight == minEdgeWeight\n && ((marked[vertex] && !marked[otherVertex]) || (marked[otherVertex] && !marked[vertex]))) {\n isMinWeightEdgeEligible = true;\n edgeToAddInMST = new Edge(vertex, otherVertex, edgeWeight);\n\n break;\n }\n }\n\n if (isMinWeightEdgeEligible) {\n break;\n }\n }\n\n if (!isMinWeightEdgeEligible) {\n continue;\n }\n\n int vertex1 = edgeToAddInMST.either();\n int vertex2 = edgeToAddInMST.other(vertex1);\n\n // Add edge to the minimum spanning tree\n minimumSpanningTree.enqueue(edgeToAddInMST);\n weight += edgeToAddInMST.weight();\n\n // Add vertex to the minimum spanning tree\n if (!marked[vertex1]) {\n visit(edgeWeightedGraph, vertex1);\n }\n if (!marked[vertex2]) {\n visit(edgeWeightedGraph, vertex2);\n }\n }\n }\n\n private void visit(EdgeWeightedGraphSpaceEfficientInterface edgeWeightedGraph, int vertex) {\n // Mark vertex and add to priority queue all edge weights from vertex to unmarked vertices\n marked[vertex] = true;\n\n double[] adjacentEdges = edgeWeightedGraph.adjacent(vertex);\n\n for (int otherVertex = 0; otherVertex < adjacentEdges.length; otherVertex++) {\n double edgeWeight = adjacentEdges[otherVertex];\n\n if (edgeWeight != NO_CONNECTION && !marked[otherVertex]) {\n priorityQueue.insert(edgeWeight);\n }\n }\n }\n\n public Iterable edges() {\n return minimumSpanningTree;\n }\n\n public double lazyWeight() {\n double weight = 0;\n\n for (Edge edge : edges()) {\n weight += edge.weight();\n }\n return weight;\n }\n\n public double eagerWeight() {\n return weight;\n }\n }\n\n public static void main(String[] args) {\n Exercise28_SpaceEfficientDataStructures spaceEfficientDataStructures = new Exercise28_SpaceEfficientDataStructures();\n\n EdgeWeightedGraphSpaceEfficient edgeWeightedGraphSpaceEfficient =\n spaceEfficientDataStructures.new EdgeWeightedGraphSpaceEfficient(5);\n edgeWeightedGraphSpaceEfficient.addEdge(new Edge(0, 1, 0.42));\n edgeWeightedGraphSpaceEfficient.addEdge(new Edge(0, 3, 0.5));\n edgeWeightedGraphSpaceEfficient.addEdge(new Edge(1, 2, 0.12));\n edgeWeightedGraphSpaceEfficient.addEdge(new Edge(1, 4, 0.91));\n edgeWeightedGraphSpaceEfficient.addEdge(new Edge(2, 3, 0.72));\n edgeWeightedGraphSpaceEfficient.addEdge(new Edge(3, 4, 0.8));\n edgeWeightedGraphSpaceEfficient.addEdge(new Edge(3, 4, 0.82));\n edgeWeightedGraphSpaceEfficient.addEdge(new Edge(4, 4, 0.1));\n\n LazyPrimMSTSpaceEfficient lazyPrimMSTSpaceEfficient =\n spaceEfficientDataStructures.new LazyPrimMSTSpaceEfficient(edgeWeightedGraphSpaceEfficient);\n\n for (Edge edge : lazyPrimMSTSpaceEfficient.edges()) {\n StdOut.println(edge);\n }\n\n StdOut.println(\"\\nExpected:\\n\" +\n \"0-1 0.42000\\n\" +\n \"1-2 0.12000\\n\" +\n \"0-3 0.50000\\n\" +\n \"3-4 0.80000\");\n }\n}\n\nAdditional notes/results:\n4.3.28 - Space-efficient data structures\n\nUsing a two-dimensional array of double for adjacent edges instead of using an array of Bag:\n\ndouble[][]\n* object overhead -> 16 bytes\n* int value (length) -> 4 bytes\n* padding -> 4 bytes\n* double[] array overheads + lengths + paddings -> 24V bytes\n* double[] references -> 8V bytes\n* double values (weight) -> 8V^2 bytes\nAmount of memory needed: 16 + 4 + 4 + 24V + 8V + 8V^2 = 8V^2 + 32V + 24 bytes\n\nEdgeWeightedGraphSpaceEfficient\n* object overhead -> 16 bytes\n* int value (V) -> 4 bytes\n* int value (E) -> 4 bytes\n* double[][] reference (adj) -> 8 bytes\n* double[][] (adj) -> 8V^2 + 32V + 24 bytes\nAmount of memory needed: 16 + 4 + 4 + 8 + 8V^2 + 32V + 24 = 8V^2 + 32V + 56 bytes\n\nAs seen on exercise 4.3.11, an array of Bag uses 112E + 40V + 56 bytes.\nThe memory saved when using a two-dimensional array of doubles for adjacent edges is 112E + 8V, but it also uses 8V^2 extra memory. This means that its memory saving benefit is higher when the graph has a large number of edges, such as in the case of dense graphs.\n\nUsing Doubles as keys for the priority queue instead of using Edges:\n\nEdge\n* object overhead -> 16 bytes\n* int value (vertex1) -> 4 bytes\n* int value (vertex2) -> 4 bytes\n* double value (weight) -> 8 bytes\nAmount of memory needed: 16 + 4 + 4 + 8 = 32 bytes\n\nDouble\n* object overhead -> 16 bytes\n* double value -> 8 bytes\nAmount of memory needed: 16 + 8 = 24 bytes\n\nPriorityQueue (assuming a min-priority queue and not a priority queue that may be either min or max)\n* object overhead -> 16 bytes\n* int value (size) -> 4 bytes\n* padding -> 4 bytes\n* Key[] reference (priorityQueue) -> 8 bytes\n* Key[] (priorityQueue)\n object overhead -> 16 bytes\n int value (length) -> 4 bytes\n padding -> 4 bytes\n Key references -> 8E -> (Resizing array): 8E * 2 = 16E\n\n Edge -> 32 bytes -> 32E\n Double -> 24 bytes -> 24E\nAmount of memory needed when using Edge keys: 16 + 4 + 4 + 8 + 16 + 4 + 4 + 16E + 32E = 48E + 56 bytes\nAmount of memory needed when using Double keys: 16 + 4 + 4 + 8 + 16 + 4 + 4 + 16E + 24E = 40E + 56 bytes\n\nThe memory saved when using Double keys for the priority queue is 8E.\n\nTotal memory saved = 112E + 8V + 8E = 120E + 8V, with an extra use of 8V^2 memory.", "support_files": [], "metadata": {"number": "4.3.28", "chapter": 4, "chapter_title": "Graphs", "section": 4.3, "section_title": "Minimum Spanning Trees", "type": "Creative Problem", "code_execution": false}} {"question": "Euclidean weighted graphs. Modify your solution to EXERCISE 4.1.37 to create an API EuclideanEdgeWeightedGraph for graphs whose vertices are points in the plane, so that you can work with graphical representations.", "answer": "package chapter4.section3;\n\nimport chapter1.section3.Bag;\nimport edu.princeton.cs.algs4.StdDraw;\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.awt.*;\n\n/**\n * Created by Rene Argento on 11/11/17.\n */\n@SuppressWarnings(\"unchecked\")\npublic class Exercise30_EuclideanWeightedGraphs {\n\n public class EuclideanEdgeWeightedGraph implements EdgeWeightedGraphInterface {\n\n public class Vertex {\n protected int id;\n protected String name;\n protected double xCoordinate;\n protected double yCoordinate;\n\n Vertex(int id, double xCoordinate, double yCoordinate) {\n this(id, String.valueOf(id), xCoordinate, yCoordinate);\n }\n\n Vertex(int id, String name, double xCoordinate, double yCoordinate) {\n this.id = id;\n this.name = name;\n this.xCoordinate = xCoordinate;\n this.yCoordinate = yCoordinate;\n }\n\n public void updateName(String name) {\n this.name = name;\n }\n }\n\n private final int vertices;\n private int edges;\n private Vertex[] allVertices;\n private Bag[] adjacent;\n\n public EuclideanEdgeWeightedGraph(int vertices) {\n this.vertices = vertices;\n edges = 0;\n allVertices = new Vertex[vertices];\n adjacent = (Bag[]) new Bag[vertices];\n\n for (int vertex = 0; vertex < vertices; vertex++) {\n adjacent[vertex] = new Bag<>();\n }\n }\n\n public int vertices() {\n return vertices;\n }\n\n public int edgesCount() {\n return edges;\n }\n\n public void addVertex(Vertex vertex) {\n allVertices[vertex.id] = vertex;\n }\n\n public void addEdge(Edge edge) {\n int vertexId1 = edge.either();\n int vertexId2 = edge.other(vertexId1);\n\n if (allVertices[vertexId1] == null || allVertices[vertexId2] == null) {\n throw new IllegalArgumentException(\"Vertex id not found\");\n }\n\n adjacent[vertexId1].add(edge);\n adjacent[vertexId2].add(edge);\n edges++;\n }\n\n public void show(double xScaleLow, double xScaleHigh, double yScaleLow, double yScaleHigh, double radiusOfCircleAroundVertex) {\n StdDraw.setCanvasSize(500, 400);\n StdDraw.setXscale(xScaleLow, xScaleHigh);\n StdDraw.setYscale(yScaleLow, yScaleHigh);\n\n StdDraw.setPenRadius(0.002D);\n StdDraw.setPenColor(Color.BLACK);\n\n for (int vertexId = 0; vertexId < vertices; vertexId++) {\n for (Edge edge : adjacent(vertexId)) {\n int otherVertexId = edge.other(vertexId);\n Vertex otherVertex = allVertices[otherVertexId];\n\n if (otherVertexId >= vertexId) {\n StdDraw.line(allVertices[vertexId].xCoordinate, allVertices[vertexId].yCoordinate,\n otherVertex.xCoordinate, otherVertex.yCoordinate);\n }\n }\n }\n\n for (int vertexId = 0; vertexId < vertices; vertexId++) {\n if (allVertices[vertexId] != null) {\n\n StdDraw.setPenColor(Color.WHITE);\n StdDraw.filledCircle(allVertices[vertexId].xCoordinate, allVertices[vertexId].yCoordinate,\n radiusOfCircleAroundVertex);\n\n StdDraw.setPenColor(Color.BLACK);\n StdDraw.circle(allVertices[vertexId].xCoordinate, allVertices[vertexId].yCoordinate,\n radiusOfCircleAroundVertex);\n\n StdDraw.setPenColor(Color.BLUE);\n StdDraw.text(allVertices[vertexId].xCoordinate, allVertices[vertexId].yCoordinate,\n allVertices[vertexId].name);\n }\n }\n }\n\n public Iterable adjacent(int vertexId) {\n return adjacent[vertexId];\n }\n\n public Iterable edges() {\n Bag edges = new Bag<>();\n\n for ( int vertex = 0; vertex < vertices; vertex++) {\n for (Edge edge : adjacent[vertex]) {\n int otherVertex = edge.other(vertex);\n\n if (otherVertex > vertex) {\n edges.add(edge);\n }\n }\n }\n return edges;\n }\n\n @Override\n public String toString() {\n StringBuilder stringBuilder = new StringBuilder();\n\n for (int vertex = 0; vertex < vertices(); vertex++) {\n stringBuilder.append(vertex).append(\": \");\n\n for (Edge neighbor : adjacent(vertex)) {\n stringBuilder.append(neighbor).append(\" \");\n }\n stringBuilder.append(\"\\n\");\n }\n\n return stringBuilder.toString();\n }\n }\n\n public static void main(String[] args) {\n Exercise30_EuclideanWeightedGraphs euclideanWeightedGraphs = new Exercise30_EuclideanWeightedGraphs();\n\n Exercise30_EuclideanWeightedGraphs.EuclideanEdgeWeightedGraph euclideanEdgeWeightedGraph =\n euclideanWeightedGraphs.new EuclideanEdgeWeightedGraph(7);\n\n EuclideanEdgeWeightedGraph.Vertex vertex0 = euclideanEdgeWeightedGraph.new Vertex(0, 6.1, 1.3);\n EuclideanEdgeWeightedGraph.Vertex vertex1 = euclideanEdgeWeightedGraph.new Vertex(1, 7.2, 2.5);\n EuclideanEdgeWeightedGraph.Vertex vertex2 = euclideanEdgeWeightedGraph.new Vertex(2, 8.4, 1.3);\n EuclideanEdgeWeightedGraph.Vertex vertex3 = euclideanEdgeWeightedGraph.new Vertex(3, 8.4, 15.3);\n EuclideanEdgeWeightedGraph.Vertex vertex4 = euclideanEdgeWeightedGraph.new Vertex(4, 6.1, 15.3);\n EuclideanEdgeWeightedGraph.Vertex vertex5 = euclideanEdgeWeightedGraph.new Vertex(5, 7.2, 5.2);\n EuclideanEdgeWeightedGraph.Vertex vertex6 = euclideanEdgeWeightedGraph.new Vertex(6, 7.2, 8.4);\n\n euclideanEdgeWeightedGraph.addVertex(vertex0);\n euclideanEdgeWeightedGraph.addVertex(vertex1);\n euclideanEdgeWeightedGraph.addVertex(vertex2);\n euclideanEdgeWeightedGraph.addVertex(vertex3);\n euclideanEdgeWeightedGraph.addVertex(vertex4);\n euclideanEdgeWeightedGraph.addVertex(vertex5);\n euclideanEdgeWeightedGraph.addVertex(vertex6);\n\n double distanceFromVertex0ToVertex1 = euclideanWeightedGraphs.getDistanceBetweenVertices(vertex0, vertex1);\n double distanceFromVertex2ToVertex1 = euclideanWeightedGraphs.getDistanceBetweenVertices(vertex2, vertex1);\n double distanceFromVertex0ToVertex2 = euclideanWeightedGraphs.getDistanceBetweenVertices(vertex0, vertex2);\n double distanceFromVertex3ToVertex6 = euclideanWeightedGraphs.getDistanceBetweenVertices(vertex3, vertex6);\n double distanceFromVertex4ToVertex6 = euclideanWeightedGraphs.getDistanceBetweenVertices(vertex4, vertex6);\n double distanceFromVertex3ToVertex4 = euclideanWeightedGraphs.getDistanceBetweenVertices(vertex3, vertex4);\n double distanceFromVertex1ToVertex5 = euclideanWeightedGraphs.getDistanceBetweenVertices(vertex1, vertex5);\n double distanceFromVertex5ToVertex6 = euclideanWeightedGraphs.getDistanceBetweenVertices(vertex5, vertex6);\n\n euclideanEdgeWeightedGraph.addEdge(new Edge(0, 1, distanceFromVertex0ToVertex1));\n euclideanEdgeWeightedGraph.addEdge(new Edge(2, 1, distanceFromVertex2ToVertex1));\n euclideanEdgeWeightedGraph.addEdge(new Edge(0, 2, distanceFromVertex0ToVertex2));\n euclideanEdgeWeightedGraph.addEdge(new Edge(3, 6, distanceFromVertex3ToVertex6));\n euclideanEdgeWeightedGraph.addEdge(new Edge(4, 6, distanceFromVertex4ToVertex6));\n euclideanEdgeWeightedGraph.addEdge(new Edge(3, 4, distanceFromVertex3ToVertex4));\n euclideanEdgeWeightedGraph.addEdge(new Edge(1, 5, distanceFromVertex1ToVertex5));\n euclideanEdgeWeightedGraph.addEdge(new Edge(5, 6, distanceFromVertex5ToVertex6));\n\n euclideanEdgeWeightedGraph.show(0, 15, -2, 18, 0.5);\n StdOut.println(euclideanEdgeWeightedGraph);\n }\n\n private double getDistanceBetweenVertices(EuclideanEdgeWeightedGraph.Vertex vertex1,\n EuclideanEdgeWeightedGraph.Vertex vertex2) {\n double xDifference = vertex1.xCoordinate - vertex2.xCoordinate;\n double yDifference = vertex1.yCoordinate - vertex2.yCoordinate;\n return Math.sqrt((xDifference * xDifference) + (yDifference * yDifference));\n }\n}\n", "support_files": [], "metadata": {"number": "4.3.30", "chapter": 4, "chapter_title": "Graphs", "section": 4.3, "section_title": "Minimum Spanning Trees", "type": "Creative Problem", "code_execution": false}} {"question": "MST weights. Develop implementations of weight() for LazyPrimMST, PrimMST, and KruskalMST, using a lazy strategy that iterates through the MST edges when the client calls weight().Then develop alternate implementations that use an eager strategy that maintains a running total as the MST is computed.", "answer": "package chapter4.section3;\n\nimport chapter1.section3.Queue;\nimport chapter1.section5.UnionFind;\nimport chapter2.section4.IndexMinPriorityQueue;\nimport chapter2.section4.PriorityQueueResize;\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 11/11/17.\n */\npublic class Exercise31_MSTWeights {\n\n public class LazyPrimMSTWeight {\n\n private boolean[] marked; // minimum spanning tree vertices\n private Queue minimumSpanningTree;\n private PriorityQueueResize priorityQueue; // crossing (and ineligible) edges\n\n private double weight;\n\n public LazyPrimMSTWeight(EdgeWeightedGraph edgeWeightedGraph) {\n priorityQueue = new PriorityQueueResize<>(PriorityQueueResize.Orientation.MIN);\n marked = new boolean[edgeWeightedGraph.vertices()];\n minimumSpanningTree = new Queue<>();\n\n visit(edgeWeightedGraph, 0); // assumes the graph is connected\n\n while (!priorityQueue.isEmpty()) {\n Edge edge = priorityQueue.deleteTop(); // Get lowest-weight edge from priority queue\n int vertex1 = edge.either();\n int vertex2 = edge.other(vertex1);\n\n // Skip if ineligible\n if (marked[vertex1] && marked[vertex2]) {\n continue;\n }\n\n // Add edge to the minimum spanning tree\n minimumSpanningTree.enqueue(edge);\n weight += edge.weight();\n\n // Add vertex to the minimum spanning tree\n if (!marked[vertex1]) {\n visit(edgeWeightedGraph, vertex1);\n }\n if (!marked[vertex2]) {\n visit(edgeWeightedGraph, vertex2);\n }\n }\n }\n\n private void visit(EdgeWeightedGraph edgeWeightedGraph, int vertex) {\n // Mark vertex and add to priority queue all edges from vertex to unmarked vertices\n marked[vertex] = true;\n\n for (Edge edge : edgeWeightedGraph.adjacent(vertex)) {\n if (!marked[edge.other(vertex)]) {\n priorityQueue.insert(edge);\n }\n }\n }\n\n public Iterable edges() {\n return minimumSpanningTree;\n }\n\n public double lazyWeight() {\n double weight = 0;\n\n for (Edge edge : edges()) {\n weight += edge.weight();\n }\n return weight;\n }\n\n public double eagerWeight() {\n return weight;\n }\n }\n\n public class PrimMSTWeight {\n private Edge[] edgeTo; // shortest edge from tree vertex\n private double[] distTo; // distTo[vertex] = edgeTo[vertex].weight()\n private boolean[] marked; // true if vertex is on the minimum spanning tree\n private IndexMinPriorityQueue priorityQueue; // eligible crossing edges\n\n private double weight;\n\n public PrimMSTWeight(EdgeWeightedGraph edgeWeightedGraph) {\n edgeTo = new Edge[edgeWeightedGraph.vertices()];\n distTo = new double[edgeWeightedGraph.vertices()];\n marked = new boolean[edgeWeightedGraph.vertices()];\n\n for (int vertex = 0; vertex < edgeWeightedGraph.vertices(); vertex++) {\n distTo[vertex] = Double.POSITIVE_INFINITY;\n }\n priorityQueue = new IndexMinPriorityQueue<>(edgeWeightedGraph.vertices());\n\n // Initialize priority queue with 0, weight 0\n distTo[0] = 0;\n priorityQueue.insert(0, 0.0);\n\n while (!priorityQueue.isEmpty()) {\n visit(edgeWeightedGraph, priorityQueue.deleteMin()); // Add closest vertex to the minimum spanning tree\n }\n }\n\n private void visit(EdgeWeightedGraph edgeWeightedGraph, int vertex) {\n // Add vertex to the minimum spanning tree; update data structures\n marked[vertex] = true;\n\n for (Edge edge : edgeWeightedGraph.adjacent(vertex)) {\n int otherVertex = edge.other(vertex);\n if (marked[otherVertex]) {\n continue; // vertex-otherVertex is ineligible\n }\n\n if (edge.weight() < distTo[otherVertex]) {\n // Edge edge is the new best connection from the minimum spanning tree to otherVertex\n if (distTo[otherVertex] != Double.POSITIVE_INFINITY) {\n weight -= distTo[otherVertex];\n }\n weight += edge.weight();\n\n edgeTo[otherVertex] = edge;\n distTo[otherVertex] = edge.weight();\n\n if (priorityQueue.contains(otherVertex)) {\n priorityQueue.decreaseKey(otherVertex, distTo[otherVertex]);\n } else {\n priorityQueue.insert(otherVertex, distTo[otherVertex]);\n }\n }\n }\n }\n\n public Iterable edges() {\n Queue minimumSpanningTree = new Queue<>();\n\n for (int vertex = 1; vertex < edgeTo.length; vertex++) {\n minimumSpanningTree.enqueue(edgeTo[vertex]);\n }\n return minimumSpanningTree;\n }\n\n public double lazyWeight() {\n double weight = 0;\n\n for (Edge edge : edges()) {\n weight += edge.weight();\n }\n return weight;\n }\n\n public double eagerWeight() {\n return weight;\n }\n }\n\n public class KruskalMSTWeight {\n private Queue minimumSpanningTree;\n private double weight;\n\n public KruskalMSTWeight(EdgeWeightedGraph edgeWeightedGraph) {\n minimumSpanningTree = new Queue<>();\n PriorityQueueResize priorityQueue = new PriorityQueueResize<>(PriorityQueueResize.Orientation.MIN);\n\n for (Edge edge : edgeWeightedGraph.edges()) {\n priorityQueue.insert(edge);\n }\n\n UnionFind unionFind = new UnionFind(edgeWeightedGraph.vertices());\n\n while (!priorityQueue.isEmpty() && minimumSpanningTree.size() < edgeWeightedGraph.vertices() - 1) {\n Edge edge = priorityQueue.deleteTop(); // Get lowest-weight edge from priority queue\n int vertex1 = edge.either();\n int vertex2 = edge.other(vertex1);\n\n // Ignore ineligible edges\n if (unionFind.connected(vertex1, vertex2)) {\n continue;\n }\n\n unionFind.union(vertex1, vertex2);\n minimumSpanningTree.enqueue(edge); // Add edge to the minimum spanning tree\n\n weight += edge.weight();\n }\n }\n\n public Iterable edges() {\n return minimumSpanningTree;\n }\n\n public double lazyWeight() {\n double weight = 0;\n\n for (Edge edge : edges()) {\n weight += edge.weight();\n }\n return weight;\n }\n\n public double eagerWeight() {\n return weight;\n }\n }\n\n public static void main(String[] args) {\n Exercise31_MSTWeights mstWeights = new Exercise31_MSTWeights();\n\n EdgeWeightedGraph edgeWeightedGraph = new EdgeWeightedGraph(5);\n edgeWeightedGraph.addEdge(new Edge(0, 1, 0.42));\n edgeWeightedGraph.addEdge(new Edge(0, 3, 0.5));\n edgeWeightedGraph.addEdge(new Edge(1, 2, 0.12));\n edgeWeightedGraph.addEdge(new Edge(1, 4, 0.91));\n edgeWeightedGraph.addEdge(new Edge(2, 3, 0.72));\n edgeWeightedGraph.addEdge(new Edge(3, 4, 0.8));\n edgeWeightedGraph.addEdge(new Edge(3, 4, 0.82));\n edgeWeightedGraph.addEdge(new Edge(4, 4, 0.1));\n\n Exercise31_MSTWeights.LazyPrimMSTWeight lazyPrimMSTWeight =\n mstWeights.new LazyPrimMSTWeight(edgeWeightedGraph);\n\n Exercise31_MSTWeights.PrimMSTWeight primMSTWeight =\n mstWeights.new PrimMSTWeight(edgeWeightedGraph);\n\n Exercise31_MSTWeights.KruskalMSTWeight kruskalMSTWeight =\n mstWeights.new KruskalMSTWeight(edgeWeightedGraph);\n\n StdOut.println(\"Expected MST weight: 1.84\\n\");\n StdOut.println(\"Lazy Prim MST lazy weight: \" + lazyPrimMSTWeight.lazyWeight());\n StdOut.println(\"Lazy Prim MST eager weight: \" + lazyPrimMSTWeight.eagerWeight());\n\n StdOut.println(\"Eager Prim MST lazy weight: \" + primMSTWeight.lazyWeight());\n StdOut.println(\"Eager Prim MST eager weight: \" + primMSTWeight.eagerWeight());\n\n StdOut.println(\"Kruskal MST lazy weight: \" + kruskalMSTWeight.lazyWeight());\n StdOut.println(\"Kruskal MST eager weight: \" + kruskalMSTWeight.eagerWeight());\n }\n}\n", "support_files": [], "metadata": {"number": "4.3.31", "chapter": 4, "chapter_title": "Graphs", "section": 4.3, "section_title": "Minimum Spanning Trees", "type": "Creative Problem", "code_execution": false}} {"question": "Certification. Write an MST and EdgeWeightedGraph client check() that uses the following cut optimality conditions implied by PROPOSITION J 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?", "answer": "A correct certification client must check four things:\n\n1. every proposed MST edge is actually an edge of the graph,\n2. the proposed edges are acyclic,\n3. the proposed edges connect all vertices, and\n4. for every proposed edge `e`, after removing `e` from the proposed tree, no crossing graph edge is lighter than `e`.\n\n```java\npublic static boolean check(EdgeWeightedGraph g, Iterable tree) {\n Queue mst = new Queue<>();\n for (Edge e : tree) {\n if (!containsEdge(g, e)) return false;\n mst.enqueue(e);\n }\n\n UF uf = new UF(g.V());\n int edges = 0;\n for (Edge e : mst) {\n int v = e.either(), w = e.other(v);\n if (uf.connected(v, w)) return false;\n uf.union(v, w);\n edges++;\n }\n if (edges != g.V() - 1 || uf.count() != 1) return false;\n\n for (Edge removed : mst) {\n uf = new UF(g.V());\n for (Edge e : mst) {\n if (e == removed) continue;\n int v = e.either(), w = e.other(v);\n uf.union(v, w);\n }\n for (Edge e : g.edges()) {\n int v = e.either(), w = e.other(v);\n if (!uf.connected(v, w) && e.weight() < removed.weight()) return false;\n }\n }\n return true;\n}\n\nprivate static boolean containsEdge(EdgeWeightedGraph g, Edge target) {\n int v = target.either(), w = target.other(v);\n for (Edge e : g.adj(v)) {\n int x = e.either(), y = e.other(x);\n if (((x == v && y == w) || (x == w && y == v))\n && e.weight() == target.weight()) return true;\n }\n return false;\n}\n```\n\nThe cut checks dominate the running time: `O(EV alpha(V))` with union-find, or `O(EV)` at this level of abstraction.", "support_files": [], "metadata": {"number": "4.3.33", "chapter": 4, "chapter_title": "Graphs", "section": 4.3, "section_title": "Minimum Spanning Trees", "type": "Creative Problem", "code_execution": false}} {"question": "True or false: Adding a constant to every edge weight does not change the solution to the single-source shortest-paths problem.", "answer": "4.4.1\n\nFalse. Adding a constant to every edge weight will add more weight to the paths that are composed of more edges, possibly changing the solution to the single-source shortest-paths problem.\n", "support_files": [], "metadata": {"number": "4.4.1", "chapter": 4, "chapter_title": "Graphs", "section": 4.4, "section_title": "Shortest Paths", "type": "Exercise", "code_execution": false}} {"question": "Provide an implementation of toString() for EdgeWeightedDigraph.", "answer": "package chapter4.section4;\n\nimport edu.princeton.cs.algs4.In;\nimport edu.princeton.cs.algs4.StdOut;\nimport util.Constants;\n\n/**\n * Created by Rene Argento on 29/11/17.\n */\npublic class Exercise2 {\n\n public class EdgeWeightedDigraphWithInConstructor extends EdgeWeightedDigraph {\n\n public EdgeWeightedDigraphWithInConstructor(In in) {\n super(in.readInt());\n int edges = in.readInt();\n\n if (edges < 0) {\n throw new IllegalArgumentException(\"Number of edges must be nonnegative\");\n }\n\n for (int i = 0; i < edges; i++) {\n int vertexFrom = in.readInt();\n int vertexTo = in.readInt();\n double weight = in.readDouble();\n\n DirectedEdge edge = new DirectedEdge(vertexFrom, vertexTo, weight);\n addEdge(edge);\n }\n }\n\n @Override\n public String toString() {\n StringBuilder stringBuilder = new StringBuilder();\n\n for (int vertex = 0; vertex < vertices(); vertex++) {\n stringBuilder.append(vertex).append(\": \");\n\n for (DirectedEdge neighbor : adjacent(vertex)) {\n stringBuilder.append(neighbor).append(\" \");\n }\n stringBuilder.append(\"\\n\");\n }\n\n return stringBuilder.toString();\n }\n }\n\n /**\n * File content:\n 6\n 5\n 2 5 33\n 3 2 14\n 4 5 89\n 4 5 86\n 3 0 15\n */\n\n public static void main(String[] args) {\n String filePath = Constants.FILES_PATH + Constants.EWD_FILE;\n EdgeWeightedDigraphWithInConstructor edgeWeightedDigraphWithInConstructor =\n new Exercise2().new EdgeWeightedDigraphWithInConstructor(new In(filePath));\n\n StdOut.println(edgeWeightedDigraphWithInConstructor);\n\n StdOut.println(\"Expected:\\n\" +\n \"0: \\n\" +\n \"1: \\n\" +\n \"2: 2->5 33.00 \\n\" +\n \"3: 3->0 15.00 3->2 14.00 \\n\" +\n \"4: 4->5 86.00 4-5 89.00 \\n\" +\n \"5: \");\n }\n}\n", "support_files": [], "metadata": {"number": "4.4.2", "chapter": 4, "chapter_title": "Graphs", "section": 4.4, "section_title": "Shortest Paths", "type": "Exercise", "code_execution": false}} {"question": "Give a trace that shows the process of computing the SPT of the digraph defined in EXERCISE 4.4.5 with the eager version of Dijkstra’s algorithm.", "answer": "4.4.6\n\nShortest-paths tree\n 0\n\nedgeTo[]\n0\n1\n2\n3 \n4\n5\n6\n7\n\ndistTo[]\n0 0.00\n1\n2\n3 \n4\n5\n6\n7\n\nShortest-paths tree\n 0\n /\n v\n 4\n\nedgeTo[]\n0\n1\n2\n3 \n4 0->4 0.38\n5\n6\n7\n\ndistTo[]\n0 0.00\n1\n2\n3 \n4 0.38\n5\n6\n7\n\nShortest-paths tree\n 5\n ^\n | 0\n | /\n |v\n 4\n\nedgeTo[]\n0 \n1\n2\n3 \n4 0->4 0.38\n5 4->5 0.35\n6\n7 \n\ndistTo[]\n0 0.00\n1\n2 \n3 \n4 0.38\n5 0.73\n6\n7\n\nShortest-paths tree\n 5\n ^\n | 7 0\n | ^ |\n |/ |\n 4 <-\n\nedgeTo[]\n0 \n1\n2\n3 \n4 0->4 0.38\n5 4->5 0.35\n6\n7 4->7 0.37\n\ndistTo[]\n0 0.00\n1\n2 \n3 \n4 0.38\n5 0.73\n6\n7 0.75\n\nShortest-paths tree\n 1\n ^\n /\n 5\n ^\n | 7 0\n | ^ |\n |/ |\n 4 <-\n\nedgeTo[]\n0 \n1 5->1 0.32\n2\n3 \n4 0->4 0.38\n5 4->5 0.35\n6\n7 4->7 0.37\n\ndistTo[]\n0 0.00\n1 1.05\n2 \n3 \n4 0.38\n5 0.73\n6\n7 0.75\n\nShortest-paths tree\n 1\n ^\n / 3\n 5 ^\n ^ /\n | 7 0\n | ^ |\n |/ |\n 4 <-\n\nedgeTo[]\n0 \n1 5->1 0.32\n2\n3 7->3 0.39\n4 0->4 0.38\n5 4->5 0.35\n6\n7 4->7 0.37\n\ndistTo[]\n0 0.00\n1 1.05\n2 \n3 1.14\n4 0.38\n5 0.73\n6\n7 0.75\n\nShortest-paths tree\n 1\n ^\n / 3\n 5 ^ \\\n ^ / \\\n | 7 0 \\\n | ^ | |\n |/ | v\n 4 <- 6\n\nedgeTo[]\n0 \n1 5->1 0.32\n2\n3 7->3 0.39\n4 0->4 0.38\n5 4->5 0.35\n6 3->6 0.52\n7 4->7 0.37\n\ndistTo[]\n0 0.00\n1 1.05\n2 \n3 1.14\n4 0.38\n5 0.73\n6 1.66\n7 0.75\n\nShortest-paths tree\n 1\n ^\n / 3\n 5 ^ \\\n ^ / \\\n | 7 0 2 \\\n | ^ | ^ |\n |/ | \\v\n 4 <- 6\n\nedgeTo[]\n0 \n1 5->1 0.32\n2 6->2 0.40\n3 7->3 0.39\n4 0->4 0.38\n5 4->5 0.35\n6 3->6 0.52\n7 4->7 0.37\n\ndistTo[]\n0 0.00\n1 1.05\n2 2.06\n3 1.14\n4 0.38\n5 0.73\n6 1.66\n7 0.75\n", "support_files": [], "metadata": {"number": "4.4.6", "chapter": 4, "chapter_title": "Graphs", "section": 4.4, "section_title": "Shortest Paths", "type": "Exercise", "code_execution": false}} {"question": "The table below, from an old published road map, purports to give the length of the shortest routes connecting the cities. It contains an error. Correct the table. Also, add a table that shows how to achieve the shortest routes.\n\n```text\n Providence Westerly New London Norwich\nProvidence - 53 54 48\nWesterly 53 - 18 101\nNew London 54 18 - 12\nNorwich 48 101 12 -\n```", "answer": "4.4.9\n\nThe error is in the length of the shortest path between Norwich and Westerly. It cannot be 101 because there is a shorter path (Norwich -> New London -> Westerly) of length 30.\n\nCorrected table\n Providence Westerly New London Norwich\nProvidence - 53 54 48\nWesterly 53 - 18 30\nNew London 54 18 - 12\nNorwich 48 30 12 -\n\nTable that shows how to achieve the shortest routes\n Providence Westerly New London Norwich\nProvidence - Providence->Westerly Providence->New London Providence->Norwich\nWesterly Westerly->Providence - Westerly->New London Westerly->New London->Norwich\nNew London New London->Providence New London->Westerly - New London->Norwich\nNorwich Norwich->Providence Norwich->New London->Westerly Norwich->New London -\n\nThanks to GenevaS (https://github.com/GenevaS) for suggesting a correction to the shortest path table.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/242\n", "support_files": [], "metadata": {"number": "4.4.9", "chapter": 4, "chapter_title": "Graphs", "section": 4.4, "section_title": "Shortest Paths", "type": "Exercise", "code_execution": false}} {"question": "Consider the edges in the digraph defined in EXERCISE 4.4.4 to be undirected edges such that each edge corresponds to equal-weight edges in both directions in the edge-weighted digraph. Answer EXERCISE 4.4.6 for this corresponding edge-weighted digraph.", "answer": "4.4.10\n\nShortest-paths tree\n 0\n\nedgeTo[]\n0\n1\n2\n3 \n4\n5\n6\n\ndistTo[]\n0 0.00\n1\n2\n3 \n4\n5\n6\n\nShortest-paths tree\n 2\n ^\n /\n 0\n\nedgeTo[]\n0\n1\n2 0->2 0.26\n3 \n4\n5\n6\n\ndistTo[]\n0 0.00\n1\n2 0.26\n3 \n4\n5\n6\n\nShortest-paths tree\n 2\n ^\n /\n 0\n /\n v\n 4\n\nedgeTo[]\n0\n1\n2 0->2 0.26\n3 \n4 0->4 0.38\n5\n6\n\ndistTo[]\n0 0.00\n1\n2 0.26\n3 \n4 0.38\n5\n6\n\nShortest-paths tree\n 2\n ^\n /\n 0\n / \\\n v v\n 4 6\n\nedgeTo[]\n0\n1\n2 0->2 0.26\n3 \n4 0->4 0.38\n5\n6 0->6 0.58\n\ndistTo[]\n0 0.00\n1\n2 0.26\n3 \n4 0.38\n5\n6 0.58\n\nShortest-paths tree\n 5\n ^ 2\n | ^\n | /\n | 0\n | / \\\n |v v\n 4 6\n\nedgeTo[]\n0\n1\n2 0->2 0.26\n3 \n4 0->4 0.38\n5 4->5 0.35\n6 0->6 0.58\n\ndistTo[]\n0 0.00\n1\n2 0.26\n3 \n4 0.38\n5 0.73\n6 0.58\n\nShortest-paths tree\n 5\n ^ 2\n | ^\n | / 3\n | 0 ^\n | / \\ |\n |v v |\n 4 6\n\nedgeTo[]\n0\n1\n2 0->2 0.26\n3 6->3 0.52\n4 0->4 0.38\n5 4->5 0.35\n6 0->6 0.58\n\ndistTo[]\n0 0.00\n1\n2 0.26\n3 1.10\n4 0.38\n5 0.73\n6 0.58\n\nShortest-paths tree\n 5->1\n ^ 2\n | ^\n | / 3\n | 0 ^\n | / \\ |\n |v v |\n 4 6\n\nedgeTo[]\n0\n1 5->1 0.32\n2 0->2 0.26\n3 6->3 0.52\n4 0->4 0.38\n5 4->5 0.35\n6 0->6 0.58\n\ndistTo[]\n0 0.00\n1 1.05\n2 0.26\n3 1.10\n4 0.38\n5 0.73\n6 0.58\n\nThanks to kyzooghost (https://github.com/kyzooghost) for noting that one edge was missing.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/274\n", "support_files": [], "metadata": {"number": "4.4.10", "chapter": 4, "chapter_title": "Graphs", "section": 4.4, "section_title": "Shortest Paths", "type": "Exercise", "code_execution": false}} {"question": "Use the memory-cost model of SECTION 1.4 to determine the amount of memory used by EdgeWeightedDigraph to represent a graph with V vertices and E edges.", "answer": "4.4.11\n\nDirectedEdge\n* object overhead -> 16 bytes\n* int value (vertex1) -> 4 bytes\n* int value (vertex2) -> 4 bytes\n* double value (weight) -> 8 bytes\nAmount of memory needed: 16 + 4 + 4 + 8 = 32 bytes\n\nNode\n* object overhead -> 16 bytes\n* extra overhead for reference to the enclosing instance -> 8 bytes\n* Item reference (item) -> 8 bytes\n* Node reference (next) -> 8 bytes\nAmount of memory needed: 16 + 8 + 8 + 8 = 40 bytes\n\nBag\n* object overhead -> 16 bytes\n* Node reference (first) -> 8 bytes\n* int value (size) -> 4 bytes\n* padding -> 4 bytes\n* N Nodes -> 40N bytes\n* DirectedEdge (item) -> 32N bytes\nAmount of memory needed: 16 + 8 + 4 + 4 + 40N + 32N = 72N + 32 bytes\n\nEdgeWeightedDigraph\n* object overhead -> 16 bytes\n* int value (V) -> 4 bytes\n* int value (E) -> 4 bytes\n* Bag[] reference (adj) -> 8 bytes\n* Bag[] (adj)\n object overhead -> 16 bytes\n int value (length) -> 4 bytes\n padding -> 4 bytes\n Bag references -> 8V\n Bag -> 72E + 32 bytes -> There are V Bags in total, and they have E nodes -> 72E + 32V\nAmount of memory needed: 16 + 4 + 4 + 8 + 16 + 4 + 4 + 8V + 72E + 32V = 72E + 40V + 56 bytes\n", "support_files": [], "metadata": {"number": "4.4.11", "chapter": 4, "chapter_title": "Graphs", "section": 4.4, "section_title": "Shortest Paths", "type": "Exercise", "code_execution": false}} {"question": "Adapt the DirectedCycle and Topological classes from SECTION 4.2 to use the EdgeWeightedDigraph and DirectedEdge APIs of this section, thus implementing EdgeWeightedCycleFinder and EdgeWeightedTopological classes.", "answer": "package chapter4.section4;\n\nimport chapter1.section3.Stack;\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 02/12/17.\n */\npublic class Exercise12 {\n\n public class EdgeWeightedCycleFinder {\n\n private boolean visited[];\n private DirectedEdge[] edgeTo;\n private Stack cycle; // vertices on a cycle (if one exists)\n private boolean[] onStack; // vertices on recursive call stack\n\n public EdgeWeightedCycleFinder(EdgeWeightedDigraph edgeWeightedDigraph) {\n onStack = new boolean[edgeWeightedDigraph.vertices()];\n edgeTo = new DirectedEdge[edgeWeightedDigraph.vertices()];\n visited = new boolean[edgeWeightedDigraph.vertices()];\n\n for (int vertex = 0; vertex < edgeWeightedDigraph.vertices(); vertex++) {\n if (!visited[vertex]) {\n dfs(edgeWeightedDigraph, vertex);\n }\n }\n }\n\n private void dfs(EdgeWeightedDigraph edgeWeightedDigraph, int vertex) {\n onStack[vertex] = true;\n visited[vertex] = true;\n\n for (DirectedEdge edge : edgeWeightedDigraph.adjacent(vertex)) {\n int neighbor = edge.to();\n\n if (hasCycle()) {\n return;\n } else if (!visited[neighbor]) {\n edgeTo[neighbor] = edge;\n dfs(edgeWeightedDigraph, neighbor);\n } else if (onStack[neighbor]) {\n cycle = new Stack<>();\n\n DirectedEdge edgeInCycle = edge;\n\n while (edgeInCycle.from() != neighbor) {\n cycle.push(edgeInCycle);\n edgeInCycle = edgeTo[edgeInCycle.from()];\n }\n\n cycle.push(edgeInCycle);\n return;\n }\n }\n onStack[vertex] = false;\n }\n\n public boolean hasCycle() {\n return cycle != null;\n }\n\n public Iterable cycle() {\n return cycle;\n }\n }\n\n public class EdgeWeightedTopological {\n\n private Iterable topologicalOrder;\n\n public EdgeWeightedTopological(EdgeWeightedDigraph edgeWeightedDigraph) {\n EdgeWeightedCycleFinder cycleFinder = new EdgeWeightedCycleFinder(edgeWeightedDigraph);\n\n if (!cycleFinder.hasCycle()) {\n DepthFirstOrder depthFirstOrder = new DepthFirstOrder(edgeWeightedDigraph);\n topologicalOrder = depthFirstOrder.reversePostOrder();\n }\n }\n\n public Iterable order() {\n return topologicalOrder;\n }\n\n public boolean isDAG() {\n return topologicalOrder != null;\n }\n }\n\n public static void main(String[] args) {\n Exercise12 exercise12 = new Exercise12();\n\n EdgeWeightedDigraph edgeWeightedDigraphWithCycle = new EdgeWeightedDigraph(8);\n edgeWeightedDigraphWithCycle.addEdge(new DirectedEdge(0, 1, 0.35));\n edgeWeightedDigraphWithCycle.addEdge(new DirectedEdge(1, 2, 0.35));\n edgeWeightedDigraphWithCycle.addEdge(new DirectedEdge(2, 3, 0.37));\n edgeWeightedDigraphWithCycle.addEdge(new DirectedEdge(3, 4, 0.28));\n edgeWeightedDigraphWithCycle.addEdge(new DirectedEdge(4, 1, 0.28));\n edgeWeightedDigraphWithCycle.addEdge(new DirectedEdge(6, 7, 0.32));\n edgeWeightedDigraphWithCycle.addEdge(new DirectedEdge(7, 5, 0.38));\n\n EdgeWeightedDigraph edgeWeightedDAG = new EdgeWeightedDigraph(5);\n edgeWeightedDAG.addEdge(new DirectedEdge(0, 1, 0.35));\n edgeWeightedDAG.addEdge(new DirectedEdge(1, 2, 0.22));\n edgeWeightedDAG.addEdge(new DirectedEdge(3, 4, 0.31));\n edgeWeightedDAG.addEdge(new DirectedEdge(4, 0, 0.29));\n\n StdOut.println(\"Cycle:\");\n EdgeWeightedCycleFinder edgeWeightedDirectedCycle =\n exercise12.new EdgeWeightedCycleFinder(edgeWeightedDigraphWithCycle);\n for (DirectedEdge edge : edgeWeightedDirectedCycle.cycle()) {\n StdOut.print(edge.from() + \"->\" + edge.to() + \" \");\n }\n StdOut.println(\"\\nExpected: 1->2 2->3 3->4 4->1 \");\n\n EdgeWeightedTopological topological = exercise12.new EdgeWeightedTopological(edgeWeightedDAG);\n StdOut.println(\"\\nTopological order:\");\n for (int vertex : topological.order()) {\n StdOut.print(vertex + \" \");\n }\n StdOut.println(\"\\nExpected: 3 4 0 1 2\");\n }\n}\n", "support_files": [], "metadata": {"number": "4.4.12", "chapter": 4, "chapter_title": "Graphs", "section": 4.4, "section_title": "Shortest Paths", "type": "Exercise", "code_execution": false}} {"question": "Show the paths that would be discovered by the two strawman approaches described on page 668 for the example tinyEWDn.txt shown on that page.", "answer": "4.4.14\n\nStrawman I\n\nMost negative edge weight = -1.40\n\nNew edge weights after adding 1.40 to all weights:\n\n4->5 1.75\n5->4 1.75\n4->7 1.77\n5->7 1.68\n7->5 1.68\n5->1 1.72\n0->4 1.78\n0->2 1.66\n7->3 1.79\n1->3 1.69\n2->7 1.74\n6->2 0.20\n3->6 1.92\n6->0 0.00\n6->4 0.15\n\nPaths discovered:\n\nShortest-paths tree\n 0\n\nedgeTo[]\n0\n1\n2\n3 \n4\n5\n6\n7\n\ndistTo[]\n0 0.00\n1\n2\n3 \n4\n5\n6\n7\n\nShortest-paths tree\n 2\n ^\n /\n 0\n\nedgeTo[]\n0\n1\n2 0->2 1.66\n3 \n4\n5\n6\n7\n\ndistTo[]\n0 0.00\n1\n2 1.66\n3 \n4\n5\n6\n7\n\nShortest-paths tree\n 2\n ^\n /\n 0\n /\n v\n 4\n\nedgeTo[]\n0\n1\n2 0->2 1.66\n3 \n4 0->4 1.78\n5\n6\n7\n\ndistTo[]\n0 0.00\n1\n2 1.66\n3 \n4 1.78\n5\n6\n7\n\nShortest-paths tree\n 7<-2\n ^\n /\n 0\n /\n v\n 4\n\nedgeTo[]\n0\n1\n2 0->2 1.66\n3 \n4 0->4 1.78\n5\n6\n7 2->7 1.74\n\ndistTo[]\n0 0.00\n1\n2 1.66\n3 \n4 1.78\n5\n6\n7 3.40\n\nShortest-paths tree\n 5\n ^ 7<-2\n | ^\n | /\n | 0\n | /\n \\ v\n 4\n\nedgeTo[]\n0\n1\n2 0->2 1.66\n3 \n4 0->4 1.78\n5 4->5 1.75\n6\n7 2->7 1.74\n\ndistTo[]\n0 0.00\n1\n2 1.66\n3 \n4 1.78\n5 3.53\n6\n7 3.40\n\nShortest-paths tree\n 3\n ^\n 5 /\n ^ 7<-2\n | ^\n | /\n | 0\n | /\n \\ v\n 4\n\nedgeTo[]\n0\n1\n2 0->2 1.66\n3 7->3 1.79\n4 0->4 1.78\n5 4->5 1.75\n6\n7 2->7 1.74\n\ndistTo[]\n0 0.00\n1\n2 1.66\n3 5.19\n4 1.78\n5 3.53\n6\n7 3.40\n\nShortest-paths tree\n 1\n ^ 3\n / ^\n 5 /\n ^ 7<-2\n | ^\n | /\n | 0\n | /\n \\ v\n 4\n\nedgeTo[]\n0\n1 5->1 1.72\n2 0->2 1.66\n3 7->3 1.79\n4 0->4 1.78\n5 4->5 1.75\n6\n7 2->7 1.74\n\ndistTo[]\n0 0.00\n1 5.25\n2 1.66\n3 5.19\n4 1.78\n5 3.53\n6\n7 3.40\n\nShortest-paths tree\n 1\n ^ 3\n / ^ \\\n 5 / \\\n ^ 7<-2 \\\n | ^ |\n | / |\n | 0 |\n | / |\n \\ v v\n 4 6\n\nedgeTo[]\n0\n1 5->1 1.72\n2 0->2 1.66\n3 7->3 1.79\n4 0->4 1.78\n5 4->5 1.75\n6 3->6 1.92\n7 2->7 1.74\n\ndistTo[]\n0 0.00\n1 5.25\n2 1.66\n3 5.19\n4 1.78\n5 3.53\n6 7.11\n7 3.40\n\nStrawman II\n\nPaths discovered:\n\nShortest-paths tree\n 0\n\nedgeTo[]\n0\n1\n2\n3\n4\n5\n6\n7\n\ndistTo[]\n0 0.00\n1\n2\n3\n4\n5\n6\n7\n\nShortest-paths tree\n 2\n ^\n /\n 0\n\nedgeTo[]\n0\n1\n2 0->2 0.26\n3 \n4\n5\n6\n7\n\ndistTo[]\n0 0.00\n1\n2 0.26\n3 \n4\n5\n6\n7\n\nShortest-paths tree\n 2\n ^\n /\n 0\n /\n v\n 4\n\nedgeTo[]\n0\n1\n2 0->2 0.26\n3 \n4 0->4 0.38\n5\n6\n7\n\ndistTo[]\n0 0.00\n1\n2 0.26\n3 \n4 0.38\n5\n6\n7\n\nShortest-paths tree\n 7<-2\n ^\n /\n 0\n /\n v\n 4\n\nedgeTo[]\n0\n1\n2 0->2 0.26\n3 \n4 0->4 0.38\n5\n6\n7 2->7 0.34\n\ndistTo[]\n0 0.00\n1\n2 0.26\n3 \n4 0.38\n5\n6\n7 0.60\n\nShortest-paths tree\n 5\n ^ 7<-2\n | ^\n | /\n | 0\n | /\n \\ v\n 4\n\nedgeTo[]\n0\n1\n2 0->2 0.26\n3 \n4 0->4 0.38\n5 4->5 0.35\n6\n7 2->7 0.34\n\ndistTo[]\n0 0.00\n1\n2 0.26\n3 \n4 0.38\n5 0.73\n6\n7 0.60\n\nShortest-paths tree\n 3\n ^\n 5 /\n ^ 7<-2\n | ^\n | /\n | 0\n | /\n \\ v\n 4\n\nedgeTo[]\n0\n1\n2 0->2 0.26\n3 7->3 0.39\n4 0->4 0.38\n5 4->5 0.35\n6\n7 2->7 0.34\n\ndistTo[]\n0 0.00\n1\n2 0.26\n3 0.99\n4 0.38\n5 0.73\n6\n7 0.60\n\nShortest-paths tree\n 1\n ^ 3\n / ^\n 5 /\n ^ 7<-2\n | ^\n | /\n | 0\n | /\n \\ v\n 4\n\nedgeTo[]\n0\n1 5->1 0.32\n2 0->2 0.26\n3 7->3 0.39\n4 0->4 0.38\n5 4->5 0.35\n6\n7 2->7 0.34\n\ndistTo[]\n0 0.00\n1 1.05\n2 0.26\n3 0.99\n4 0.38\n5 0.73\n6\n7 0.60\n\nShortest-paths tree\n 1\n ^ 3\n / ^ \\\n 5 / \\\n ^ 7<-2 \\\n | ^ |\n | / |\n | 0 |\n | / |\n \\ v v\n 4 6\n\nedgeTo[]\n0\n1 5->1 0.32\n2 0->2 0.26\n3 7->3 0.39\n4 0->4 0.38\n5 4->5 0.35\n6 3->6 0.52\n7 2->7 0.34\n\ndistTo[]\n0 0.00\n1 1.05\n2 0.26\n3 0.99\n4 0.38\n5 0.73\n6 1.51\n7 0.60\n\nShortest-paths tree\n 1\n ^ 3\n / ^ \\\n 5 / \\\n ^ 7<-2 \\\n | ^ |\n | / |\n | 0 |\n | |\n \\ v\n 4<------6\n\nedgeTo[]\n0\n1 5->1 0.32\n2 0->2 0.26\n3 7->3 0.39\n4 6->4 -1.25\n5 4->5 0.35\n6 3->6 0.52\n7 2->7 0.34\n\ndistTo[]\n0 0.00\n1 1.05\n2 0.26\n3 0.99\n4 0.26\n5 0.73\n6 1.51\n7 0.60\n\nShortest-paths tree\n 1\n ^ 3\n / ^ \\\n 5 / \\\n ^ 7<-2 \\\n | ^ |\n | / |\n | 0 |\n | |\n \\ v\n 4<------6\n\nedgeTo[]\n0\n1 5->1 0.32\n2 0->2 0.26\n3 7->3 0.39\n4 6->4 -1.25\n5 4->5 0.35\n6 3->6 0.52\n7 2->7 0.34\n\ndistTo[]\n0 0.00\n1 1.05\n2 0.26\n3 0.99\n4 0.26\n5 0.61\n6 1.51\n7 0.60\n\nShortest-paths tree\n 1\n ^ 3\n / ^ \\\n 5 / \\\n ^ 7<-2 \\\n | ^ |\n | / |\n | 0 |\n | |\n \\ v\n 4<------6\n\nedgeTo[]\n0\n1 5->1 0.32\n2 0->2 0.26\n3 7->3 0.39\n4 6->4 -1.25\n5 4->5 0.35\n6 3->6 0.52\n7 2->7 0.34\n\ndistTo[]\n0 0.00\n1 0.93\n2 0.26\n3 0.99\n4 0.26\n5 0.61\n6 1.51\n7 0.60\n", "support_files": [], "metadata": {"number": "4.4.14", "chapter": 4, "chapter_title": "Graphs", "section": 4.4, "section_title": "Shortest Paths", "type": "Exercise", "code_execution": false}} {"question": "Find the lowest-weight cycle (best arbitrage opportunity) in the rates example from the text:\n\n```text\nUSD 1 0.741 0.657 1.061 1.005\nEUR 1.349 1 0.888 1.433 1.366\nGBP 1.521 1.126 1 1.614 1.538\nCHF 0.942 0.698 0.619 1 0.953\nCAD 0.995 0.732 0.650 1.049 1\n```\n\nEdge weights are `-ln(rate)`.", "answer": "4.4.19\n\nThe lowest-weight cycle (best arbitrage opportunity) is the following:\n\nEUR 1.366 -> CAD\nCAD 0.995 -> USD\nUSD 0.741 -> EUR\n", "support_files": [], "metadata": {"number": "4.4.19", "chapter": 4, "chapter_title": "Graphs", "section": 4.4, "section_title": "Shortest Paths", "type": "Exercise", "code_execution": false}} {"question": "Find a currency-conversion table online or in a newspaper. Use it to build an arbitrage table. Note: Avoid tables that are derived (calculated) from a few values and that therefore do not give sufficiently accurate conversion information to be interesting. Extra credit: Make a killing in the money-exchange market!", "answer": "4.4.20\n\nBased on: http://www.xe.com/currencyconverter/\nDate: 2017-12-03 22:00 UTC\n\nCurrency-conversion table\n\n USD EUR GBP INR AUD\nUSD 1.00000 0.84279 0.74426 64.5471 1.31644\nEUR 1.18653 1.00000 0.88309 76.5871 1.56199\nGBP 1.34361 1.13239 1.00000 86.7263 1.76878\nINR 0.01549 0.01306 0.01153 1.00000 0.02039\nAUD 0.75963 0.64021 0.56536 49.0318 1.00000\n\nArbitrage table (all arbitrage opportunities = all negative cycles)\n\nUSD 1.31644 -> AUD\nAUD 0.75963 -> USD\n\nEUR 0.88309 -> GBP\nGBP 1.13239 -> EUR\n\nEUR 76.58710 -> INR\nINR 0.01306 -> EUR\n\nEUR 1.56199 -> AUD\nAUD 0.64021 -> EUR\n\nGBP 1.13239 -> EUR\nEUR 0.88309 -> GBP\n\nINR 0.01306 -> EUR\nEUR 76.58710 -> INR\n\nAUD 0.75963 -> USD\nUSD 1.31644 -> AUD\n\nAUD 0.64021 -> EUR\nEUR 1.56199 -> AUD\n\nUSD 0.74426 -> GBP\nGBP 1.76878 -> AUD\nAUD 0.75963 -> USD\n\nUSD 64.54710 -> INR\nINR 0.01306 -> EUR\nEUR 1.18653 -> USD\n\nUSD 1.31644 -> AUD\nAUD 0.64021 -> EUR\nEUR 1.18653 -> USD\n\nEUR 1.18653 -> USD\nUSD 64.54710 -> INR\nINR 0.01306 -> EUR\n\nEUR 1.18653 -> USD\nUSD 1.31644 -> AUD\nAUD 0.64021 -> EUR\n\nEUR 0.88309 -> GBP\nGBP 86.72630 -> INR\nINR 0.01306 -> EUR\n\nEUR 0.88309 -> GBP\nGBP 1.76878 -> AUD\nAUD 0.64021 -> EUR\n\nEUR 1.56199 -> AUD\nAUD 49.03180 -> INR\nINR 0.01306 -> EUR\n\nGBP 86.72630 -> INR\nINR 0.01306 -> EUR\nEUR 0.88309 -> GBP\n\nGBP 1.76878 -> AUD\nAUD 0.75963 -> USD\nUSD 0.74426 -> GBP\n\nGBP 1.76878 -> AUD\nAUD 0.64021 -> EUR\nEUR 0.88309 -> GBP\n\nINR 0.01306 -> EUR\nEUR 1.18653 -> USD\nUSD 64.54710 -> INR\n\nINR 0.01306 -> EUR\nEUR 0.88309 -> GBP\nGBP 86.72630 -> INR\n\nINR 0.01306 -> EUR\nEUR 1.56199 -> AUD\nAUD 49.03180 -> INR\n\nAUD 0.75963 -> USD\nUSD 0.74426 -> GBP\nGBP 1.76878 -> AUD\n\nAUD 0.64021 -> EUR\nEUR 1.18653 -> USD\nUSD 1.31644 -> AUD\n\nAUD 0.64021 -> EUR\nEUR 0.88309 -> GBP\nGBP 1.76878 -> AUD\n\nAUD 49.03180 -> INR\nINR 0.01306 -> EUR\nEUR 1.56199 -> AUD\n\nUSD 0.84279 -> EUR\nEUR 0.88309 -> GBP\nGBP 1.76878 -> AUD\nAUD 0.75963 -> USD\n\nUSD 0.74426 -> GBP\nGBP 1.13239 -> EUR\nEUR 1.56199 -> AUD\nAUD 0.75963 -> USD\n\nUSD 0.74426 -> GBP\nGBP 86.72630 -> INR\nINR 0.01306 -> EUR\nEUR 1.18653 -> USD\n\nUSD 64.54710 -> INR\nINR 0.01306 -> EUR\nEUR 0.88309 -> GBP\nGBP 1.34361 -> USD\n\nUSD 64.54710 -> INR\nINR 0.01306 -> EUR\nEUR 1.56199 -> AUD\nAUD 0.75963 -> USD\n\nUSD 1.31644 -> AUD\nAUD 0.64021 -> EUR\nEUR 0.88309 -> GBP\nGBP 1.34361 -> USD\n\nUSD 1.31644 -> AUD\nAUD 0.56536 -> GBP\nGBP 1.13239 -> EUR\nEUR 1.18653 -> USD\n\nUSD 1.31644 -> AUD\nAUD 49.03180 -> INR\nINR 0.01306 -> EUR\nEUR 1.18653 -> USD\n\nEUR 1.18653 -> USD\nUSD 0.74426 -> GBP\nGBP 86.72630 -> INR\nINR 0.01306 -> EUR\n\nEUR 1.18653 -> USD\nUSD 1.31644 -> AUD\nAUD 0.56536 -> GBP\nGBP 1.13239 -> EUR\n\nEUR 1.18653 -> USD\nUSD 1.31644 -> AUD\nAUD 49.03180 -> INR\nINR 0.01306 -> EUR\n\nEUR 0.88309 -> GBP\nGBP 1.34361 -> USD\nUSD 64.54710 -> INR\nINR 0.01306 -> EUR\n\nEUR 0.88309 -> GBP\nGBP 1.34361 -> USD\nUSD 1.31644 -> AUD\nAUD 0.64021 -> EUR\n\nEUR 0.88309 -> GBP\nGBP 1.76878 -> AUD\nAUD 0.75963 -> USD\nUSD 0.84279 -> EUR\n\nEUR 0.88309 -> GBP\nGBP 1.76878 -> AUD\nAUD 49.03180 -> INR\nINR 0.01306 -> EUR\n\nEUR 1.56199 -> AUD\nAUD 0.75963 -> USD\nUSD 0.74426 -> GBP\nGBP 1.13239 -> EUR\n\nEUR 1.56199 -> AUD\nAUD 0.75963 -> USD\nUSD 64.54710 -> INR\nINR 0.01306 -> EUR\n\nEUR 1.56199 -> AUD\nAUD 0.56536 -> GBP\nGBP 86.72630 -> INR\nINR 0.01306 -> EUR\n\nGBP 1.34361 -> USD\nUSD 64.54710 -> INR\nINR 0.01306 -> EUR\nEUR 0.88309 -> GBP\n\nGBP 1.34361 -> USD\nUSD 1.31644 -> AUD\nAUD 0.64021 -> EUR\nEUR 0.88309 -> GBP\n\nGBP 1.13239 -> EUR\nEUR 1.18653 -> USD\nUSD 1.31644 -> AUD\nAUD 0.56536 -> GBP\n\nGBP 1.13239 -> EUR\nEUR 1.56199 -> AUD\nAUD 0.75963 -> USD\nUSD 0.74426 -> GBP\n\nGBP 86.72630 -> INR\nINR 0.01306 -> EUR\nEUR 1.18653 -> USD\nUSD 0.74426 -> GBP\n\nGBP 86.72630 -> INR\nINR 0.01306 -> EUR\nEUR 1.56199 -> AUD\nAUD 0.56536 -> GBP\n\nGBP 1.76878 -> AUD\nAUD 0.75963 -> USD\nUSD 0.84279 -> EUR\nEUR 0.88309 -> GBP\n\nGBP 1.76878 -> AUD\nAUD 49.03180 -> INR\nINR 0.01306 -> EUR\nEUR 0.88309 -> GBP\n\nINR 0.01306 -> EUR\nEUR 1.18653 -> USD\nUSD 0.74426 -> GBP\nGBP 86.72630 -> INR\n\nINR 0.01306 -> EUR\nEUR 1.18653 -> USD\nUSD 1.31644 -> AUD\nAUD 49.03180 -> INR\n\nINR 0.01306 -> EUR\nEUR 0.88309 -> GBP\nGBP 1.34361 -> USD\nUSD 64.54710 -> INR\n\nINR 0.01306 -> EUR\nEUR 0.88309 -> GBP\nGBP 1.76878 -> AUD\nAUD 49.03180 -> INR\n\nINR 0.01306 -> EUR\nEUR 1.56199 -> AUD\nAUD 0.75963 -> USD\nUSD 64.54710 -> INR\n\nINR 0.01306 -> EUR\nEUR 1.56199 -> AUD\nAUD 0.56536 -> GBP\nGBP 86.72630 -> INR\n\nAUD 0.75963 -> USD\nUSD 0.84279 -> EUR\nEUR 0.88309 -> GBP\nGBP 1.76878 -> AUD\n\nAUD 0.75963 -> USD\nUSD 0.74426 -> GBP\nGBP 1.13239 -> EUR\nEUR 1.56199 -> AUD\n\nAUD 0.75963 -> USD\nUSD 64.54710 -> INR\nINR 0.01306 -> EUR\nEUR 1.56199 -> AUD\n\nAUD 0.64021 -> EUR\nEUR 0.88309 -> GBP\nGBP 1.34361 -> USD\nUSD 1.31644 -> AUD\n\nAUD 0.56536 -> GBP\nGBP 1.13239 -> EUR\nEUR 1.18653 -> USD\nUSD 1.31644 -> AUD\n\nAUD 0.56536 -> GBP\nGBP 86.72630 -> INR\nINR 0.01306 -> EUR\nEUR 1.56199 -> AUD\n\nAUD 49.03180 -> INR\nINR 0.01306 -> EUR\nEUR 1.18653 -> USD\nUSD 1.31644 -> AUD\n\nAUD 49.03180 -> INR\nINR 0.01306 -> EUR\nEUR 0.88309 -> GBP\nGBP 1.76878 -> AUD\n\nUSD 0.74426 -> GBP\nGBP 86.72630 -> INR\nINR 0.01306 -> EUR\nEUR 1.56199 -> AUD\nAUD 0.75963 -> USD\n\nUSD 0.74426 -> GBP\nGBP 1.76878 -> AUD\nAUD 49.03180 -> INR\nINR 0.01306 -> EUR\nEUR 1.18653 -> USD\n\nUSD 64.54710 -> INR\nINR 0.01306 -> EUR\nEUR 0.88309 -> GBP\nGBP 1.76878 -> AUD\nAUD 0.75963 -> USD\n\nUSD 64.54710 -> INR\nINR 0.01306 -> EUR\nEUR 1.56199 -> AUD\nAUD 0.56536 -> GBP\nGBP 1.34361 -> USD\n\nUSD 1.31644 -> AUD\nAUD 0.56536 -> GBP\nGBP 86.72630 -> INR\nINR 0.01306 -> EUR\nEUR 1.18653 -> USD\n\nUSD 1.31644 -> AUD\nAUD 49.03180 -> INR\nINR 0.01306 -> EUR\nEUR 0.88309 -> GBP\nGBP 1.34361 -> USD\n\nEUR 1.18653 -> USD\nUSD 0.74426 -> GBP\nGBP 1.76878 -> AUD\nAUD 49.03180 -> INR\nINR 0.01306 -> EUR\n\nEUR 1.18653 -> USD\nUSD 1.31644 -> AUD\nAUD 0.56536 -> GBP\nGBP 86.72630 -> INR\nINR 0.01306 -> EUR\n\nEUR 0.88309 -> GBP\nGBP 1.34361 -> USD\nUSD 1.31644 -> AUD\nAUD 49.03180 -> INR\nINR 0.01306 -> EUR\n\nEUR 0.88309 -> GBP\nGBP 1.76878 -> AUD\nAUD 0.75963 -> USD\nUSD 64.54710 -> INR\nINR 0.01306 -> EUR\n\nEUR 1.56199 -> AUD\nAUD 0.75963 -> USD\nUSD 0.74426 -> GBP\nGBP 86.72630 -> INR\nINR 0.01306 -> EUR\n\nEUR 1.56199 -> AUD\nAUD 0.56536 -> GBP\nGBP 1.34361 -> USD\nUSD 64.54710 -> INR\nINR 0.01306 -> EUR\n\nGBP 1.34361 -> USD\nUSD 64.54710 -> INR\nINR 0.01306 -> EUR\nEUR 1.56199 -> AUD\nAUD 0.56536 -> GBP\n\nGBP 1.34361 -> USD\nUSD 1.31644 -> AUD\nAUD 49.03180 -> INR\nINR 0.01306 -> EUR\nEUR 0.88309 -> GBP\n\nGBP 86.72630 -> INR\nINR 0.01306 -> EUR\nEUR 1.18653 -> USD\nUSD 1.31644 -> AUD\nAUD 0.56536 -> GBP\n\nGBP 86.72630 -> INR\nINR 0.01306 -> EUR\nEUR 1.56199 -> AUD\nAUD 0.75963 -> USD\nUSD 0.74426 -> GBP\n\nGBP 1.76878 -> AUD\nAUD 0.75963 -> USD\nUSD 64.54710 -> INR\nINR 0.01306 -> EUR\nEUR 0.88309 -> GBP\n\nGBP 1.76878 -> AUD\nAUD 49.03180 -> INR\nINR 0.01306 -> EUR\nEUR 1.18653 -> USD\nUSD 0.74426 -> GBP\n\nINR 0.01306 -> EUR\nEUR 1.18653 -> USD\nUSD 0.74426 -> GBP\nGBP 1.76878 -> AUD\nAUD 49.03180 -> INR\n\nINR 0.01306 -> EUR\nEUR 1.18653 -> USD\nUSD 1.31644 -> AUD\nAUD 0.56536 -> GBP\nGBP 86.72630 -> INR\n\nINR 0.01306 -> EUR\nEUR 0.88309 -> GBP\nGBP 1.34361 -> USD\nUSD 1.31644 -> AUD\nAUD 49.03180 -> INR\n\nINR 0.01306 -> EUR\nEUR 0.88309 -> GBP\nGBP 1.76878 -> AUD\nAUD 0.75963 -> USD\nUSD 64.54710 -> INR\n\nINR 0.01306 -> EUR\nEUR 1.56199 -> AUD\nAUD 0.75963 -> USD\nUSD 0.74426 -> GBP\nGBP 86.72630 -> INR\n\nINR 0.01306 -> EUR\nEUR 1.56199 -> AUD\nAUD 0.56536 -> GBP\nGBP 1.34361 -> USD\nUSD 64.54710 -> INR\n\nAUD 0.75963 -> USD\nUSD 0.74426 -> GBP\nGBP 86.72630 -> INR\nINR 0.01306 -> EUR\nEUR 1.56199 -> AUD\n\nAUD 0.75963 -> USD\nUSD 64.54710 -> INR\nINR 0.01306 -> EUR\nEUR 0.88309 -> GBP\nGBP 1.76878 -> AUD\n\nAUD 0.56536 -> GBP\nGBP 1.34361 -> USD\nUSD 64.54710 -> INR\nINR 0.01306 -> EUR\nEUR 1.56199 -> AUD\n\nAUD 0.56536 -> GBP\nGBP 86.72630 -> INR\nINR 0.01306 -> EUR\nEUR 1.18653 -> USD\nUSD 1.31644 -> AUD\n\nAUD 49.03180 -> INR\nINR 0.01306 -> EUR\nEUR 1.18653 -> USD\nUSD 0.74426 -> GBP\nGBP 1.76878 -> AUD\n\nAUD 49.03180 -> INR\nINR 0.01306 -> EUR\nEUR 0.88309 -> GBP\nGBP 1.34361 -> USD\nUSD 1.31644 -> AUD\n", "support_files": [], "metadata": {"number": "4.4.20", "chapter": 4, "chapter_title": "Graphs", "section": 4.4, "section_title": "Shortest Paths", "type": "Exercise", "code_execution": false}} {"question": "Show, in the style of the trace in the text, the process of computing the SPT with the Bellman-Ford algorithm for the edge-weighted digraph of EXERCISE 4.4.5.", "answer": "4.4.21\n\nEntries in queue for each pass have a * next to them.\nThe other entries in queue are for the next pass. \n\nShortest-paths tree\n 0\n /\n v\n 4\n\nqueue\n0 *\n4\n\nedgeTo[]\n0\n1\n2\n3 \n4 0->4 0.38\n5\n6\n7\n\ndistTo[]\n0 0.00\n1\n2\n3 \n4 0.38\n5\n6\n7\n\nShortest-paths tree\n 5\n ^\n | 7 0\n | ^ |\n |/ |\n 4 <-\n\nqueue\n4 *\n7\n5\n\nedgeTo[]\n0 \n1\n2\n3 \n4 0->4 0.38\n5 4->5 0.35\n6\n7 4->7 0.37\n\ndistTo[]\n0 0.00\n1\n2 \n3 \n4 0.38\n5 0.73\n6\n7 0.75\n\nShortest-paths tree\n 1\n ^\n / 3\n 5 ^\n ^ /\n | 7 0\n | ^ |\n |/ |\n 4 <-\n\nqueue\n7 *\n5 *\n3\n1\n\nedgeTo[]\n0 \n1 5->1 0.32\n2\n3 7->3 0.39\n4 0->4 0.38\n5 4->5 0.35\n6\n7 4->7 0.37\n\ndistTo[]\n0 0.00\n1 1.05\n2 \n3 1.14\n4 0.38\n5 0.73\n6\n7 0.75\n\nShortest-paths tree\n 1\n ^\n / 3\n 5 ^ \\\n ^ / \\\n | 7 0 \\\n | ^ | |\n |/ | v\n 4 <- 6\n\nqueue\n3 *\n1 *\n6\n\nedgeTo[]\n0 \n1 5->1 0.32\n2\n3 7->3 0.39\n4 0->4 0.38\n5 4->5 0.35\n6 3->6 0.52\n7 4->7 0.37\n\ndistTo[]\n0 0.00\n1 1.05\n2 \n3 1.14\n4 0.38\n5 0.73\n6 1.66\n7 0.75\n\nShortest-paths tree\n 1\n ^\n / 3\n 5 ^ \\\n ^ / \\\n | 7 0 2 \\\n | ^ | ^ |\n |/ | \\v\n 4 <- 6\n\nqueue\n6 *\n2\n\nedgeTo[]\n0 \n1 5->1 0.32\n2 6->2 0.40\n3 7->3 0.39\n4 0->4 0.38\n5 4->5 0.35\n6 3->6 0.52\n7 4->7 0.37\n\ndistTo[]\n0 0.00\n1 1.05\n2 2.06\n3 1.14\n4 0.38\n5 0.73\n6 1.66\n7 0.75\n\nShortest-paths tree\n 1\n ^\n / 3\n 5 ^ \\\n ^ / \\\n | 7 0 2 \\\n | ^ | ^ |\n |/ | \\v\n 4 <- 6\n\nqueue\n2 *\n\nedgeTo[]\n0 \n1 5->1 0.32\n2 6->2 0.40\n3 7->3 0.39\n4 0->4 0.38\n5 4->5 0.35\n6 3->6 0.52\n7 4->7 0.37\n\ndistTo[]\n0 0.00\n1 1.05\n2 2.06\n3 1.14\n4 0.38\n5 0.73\n6 1.66\n7 0.75\n\nShortest-paths tree\n 1\n ^\n / 3\n 5 ^ \\\n ^ / \\\n | 7 0 2 \\\n | ^ | ^ |\n |/ | \\v\n 4 <- 6\n\nqueue\n\n\nedgeTo[]\n0 \n1 5->1 0.32\n2 6->2 0.40\n3 7->3 0.39\n4 0->4 0.38\n5 4->5 0.35\n6 3->6 0.52\n7 4->7 0.37\n\ndistTo[]\n0 0.00\n1 1.05\n2 2.06\n3 1.14\n4 0.38\n5 0.73\n6 1.66\n7 0.75\n", "support_files": [], "metadata": {"number": "4.4.21", "chapter": 4, "chapter_title": "Graphs", "section": 4.4, "section_title": "Shortest Paths", "type": "Exercise", "code_execution": false}} {"question": "Multisource shortest paths. Develop an API and implementation that uses Dijkstra’s algorithm to solve the multisource shortest-paths problem on edge-weighted digraphs with positive edge weights: given a set of sources, find a shortest-paths forest that enables implementation of a method that returns to clients the shortest path from any source to each vertex. Hint: Add a dummy vertex with a zero-weight edge to each source, or initialize the priority queue with all sources, with their distTo[] entries set to 0.", "answer": "package chapter4.section4;\n\nimport chapter1.section3.Queue;\nimport chapter3.section5.HashSet;\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 07/12/17.\n */\npublic class Exercise24_MultisourceShortestPaths {\n\n public interface DijkstraMultisourceSPAPI {\n double distTo(int vertex);\n boolean hasPathTo(int vertex);\n Iterable pathTo(int vertex);\n }\n\n public class DijkstraMultisourceSP implements DijkstraMultisourceSPAPI {\n\n private DijkstraSP dijkstraSP;\n private int dummyVertexId;\n\n DijkstraMultisourceSP(EdgeWeightedDigraph edgeWeightedDigraph, HashSet sources) {\n\n EdgeWeightedDigraph edgeWeightedDigraphWithExtraSource =\n new EdgeWeightedDigraph(edgeWeightedDigraph.vertices() + 1);\n\n // Copy graph\n for (int vertex = 0; vertex < edgeWeightedDigraph.vertices(); vertex++) {\n for (DirectedEdge edge : edgeWeightedDigraph.adjacent(vertex)) {\n edgeWeightedDigraphWithExtraSource.addEdge(edge);\n }\n }\n\n // Add extra source connected to all sources\n dummyVertexId = edgeWeightedDigraphWithExtraSource.vertices() - 1;\n\n for (int source : sources.keys()) {\n edgeWeightedDigraphWithExtraSource.addEdge(new DirectedEdge(dummyVertexId, source, 0));\n }\n\n dijkstraSP = new DijkstraSP(edgeWeightedDigraphWithExtraSource, dummyVertexId);\n }\n\n public double distTo(int vertex) {\n return dijkstraSP.distTo(vertex);\n }\n\n public boolean hasPathTo(int vertex) {\n return dijkstraSP.hasPathTo(vertex);\n }\n\n public Iterable pathTo(int vertex) {\n if (!hasPathTo(vertex)) {\n return null;\n }\n Queue path = new Queue<>();\n for (DirectedEdge edge : dijkstraSP.pathTo(vertex)) {\n if (edge.from() != dummyVertexId) {\n path.enqueue(edge);\n }\n }\n return path;\n }\n\n }\n\n public static void main(String[] args) {\n EdgeWeightedDigraph edgeWeightedDigraph = new EdgeWeightedDigraph(8);\n edgeWeightedDigraph.addEdge(new DirectedEdge(4, 5, 0.35));\n edgeWeightedDigraph.addEdge(new DirectedEdge(5, 4, 0.35));\n edgeWeightedDigraph.addEdge(new DirectedEdge(4, 7, 0.37));\n edgeWeightedDigraph.addEdge(new DirectedEdge(5, 7, 0.28));\n edgeWeightedDigraph.addEdge(new DirectedEdge(7, 5, 0.28));\n edgeWeightedDigraph.addEdge(new DirectedEdge(5, 1, 0.32));\n edgeWeightedDigraph.addEdge(new DirectedEdge(0, 4, 0.38));\n edgeWeightedDigraph.addEdge(new DirectedEdge(0, 2, 0.26));\n edgeWeightedDigraph.addEdge(new DirectedEdge(7, 3, 0.39));\n edgeWeightedDigraph.addEdge(new DirectedEdge(1, 3, 0.29));\n edgeWeightedDigraph.addEdge(new DirectedEdge(2, 7, 0.34));\n edgeWeightedDigraph.addEdge(new DirectedEdge(6, 2, 0.40));\n edgeWeightedDigraph.addEdge(new DirectedEdge(3, 6, 0.52));\n edgeWeightedDigraph.addEdge(new DirectedEdge(6, 0, 0.58));\n edgeWeightedDigraph.addEdge(new DirectedEdge(6, 4, 0.93));\n\n HashSet sources = new HashSet<>();\n sources.add(0);\n sources.add(1);\n sources.add(7);\n\n DijkstraMultisourceSP dijkstraMultisourceSP =\n new Exercise24_MultisourceShortestPaths().new DijkstraMultisourceSP(edgeWeightedDigraph, sources);\n\n StdOut.println(\"Distance to 5: \" + dijkstraMultisourceSP.distTo(5) + \" Expected: 0.28\");\n StdOut.println(\"Has path to 5: \" + dijkstraMultisourceSP.hasPathTo(5) + \" Expected: true\");\n\n StdOut.print(\"Path to 5: \");\n\n for (DirectedEdge edge : dijkstraMultisourceSP.pathTo(5)) {\n StdOut.print(edge.from() + \"->\" + edge.to() + \" \");\n }\n StdOut.println(\"\\nExpected: 7->5\");\n\n StdOut.println(\"\\nDistance to 6: \" + dijkstraMultisourceSP.distTo(6) + \" Expected: 0.81\");\n StdOut.println(\"Has path to 6: \" + dijkstraMultisourceSP.hasPathTo(6) + \" Expected: true\");\n\n StdOut.print(\"Path to 6: \");\n\n for (DirectedEdge edge : dijkstraMultisourceSP.pathTo(6)) {\n StdOut.print(edge.from() + \"->\" + edge.to() + \" \");\n }\n StdOut.println(\"\\nExpected: 1->3 3->6\");\n }\n}\n", "support_files": [], "metadata": {"number": "4.4.24", "chapter": 4, "chapter_title": "Graphs", "section": 4.4, "section_title": "Shortest Paths", "type": "Creative Problem", "code_execution": false}} {"question": "Shortest paths in Euclidean graphs. Adapt our APIs to speed up Dijkstra’s algorithm in the case where it is known that vertices are points in the plane.", "answer": "package chapter4.section4;\n\nimport chapter1.section3.Bag;\nimport chapter1.section3.Stack;\nimport chapter2.section4.IndexMinPriorityQueue;\nimport edu.princeton.cs.algs4.StdDraw;\nimport edu.princeton.cs.algs4.StdOut;\nimport util.DrawUtilities;\nimport util.DrawUtilities.Coordinate;\n\nimport java.awt.*;\n\n/**\n * Created by Rene Argento on 07/12/17.\n */\n// Based on the article \"Shortest paths in euclidean graphs\" by Robert Sedgewick & Jeffrey Scott Vitter, 1985\n // And slides https://www.cs.princeton.edu/courses/archive/spr10/cos226/lectures/15-44ShortestPaths-2x2.pdf\n // And http://www.informit.com/articles/article.aspx?p=169575&seqNum=6\npublic class Exercise27_ShortestPathsInEuclideanGraphs {\n\n @SuppressWarnings(\"unchecked\")\n public class EuclideanEdgeWeightedDigraph implements EdgeWeightedDigraphInterface {\n public class Vertex {\n protected int id;\n private String name;\n protected Coordinate coordinates;\n\n Vertex(int id, double xCoordinate, double yCoordinate) {\n this(id, String.valueOf(id), xCoordinate, yCoordinate);\n }\n\n Vertex(int id, String name, double xCoordinate, double yCoordinate) {\n this.id = id;\n this.name = name;\n coordinates = new DrawUtilities().new Coordinate(xCoordinate, yCoordinate);\n }\n\n public void updateName(String name) {\n this.name = name;\n }\n }\n\n private final int vertices;\n private int edges;\n private Vertex[] allVertices;\n private Bag[] adjacent;\n\n public EuclideanEdgeWeightedDigraph(int vertices) {\n this.vertices = vertices;\n edges = 0;\n allVertices = new Vertex[vertices];\n adjacent = (Bag[]) new Bag[vertices];\n\n for (int vertex = 0; vertex < vertices; vertex++) {\n adjacent[vertex] = new Bag<>();\n }\n }\n\n public int vertices() {\n return vertices;\n }\n\n public int edgesCount() {\n return edges;\n }\n\n public int outdegree(int vertex) {\n return adjacent[vertex].size();\n }\n\n public Vertex getVertex(int vertexId) {\n return allVertices[vertexId];\n }\n\n public void addVertex(Vertex vertex) {\n allVertices[vertex.id] = vertex;\n }\n\n public void addEdge(DirectedEdge edge) {\n int vertexId1 = edge.from();\n int vertexId2 = edge.to();\n\n if (allVertices[vertexId1] == null || allVertices[vertexId2] == null) {\n throw new IllegalArgumentException(\"Vertex id not found\");\n }\n\n adjacent[vertexId1].add(edge);\n edges++;\n }\n\n public void show(double xScaleLow, double xScaleHigh, double yScaleLow, double yScaleHigh,\n double radiusOfCircleAroundVertex, double padding, double arrowLength) {\n StdDraw.setCanvasSize(500, 400);\n StdDraw.setXscale(xScaleLow, xScaleHigh);\n StdDraw.setYscale(yScaleLow, yScaleHigh);\n\n StdDraw.setPenRadius(0.002D);\n\n for (int vertexId = 0; vertexId < vertices; vertexId++) {\n if (allVertices[vertexId] != null) {\n double xCoordinate = allVertices[vertexId].coordinates.getXCoordinate();\n double yCoordinate = allVertices[vertexId].coordinates.getYCoordinate();\n\n StdDraw.setPenColor(Color.WHITE);\n StdDraw.filledCircle(xCoordinate, yCoordinate, radiusOfCircleAroundVertex);\n\n StdDraw.setPenColor(Color.BLACK);\n StdDraw.circle(xCoordinate, yCoordinate, radiusOfCircleAroundVertex);\n\n StdDraw.setPenColor(Color.BLUE);\n StdDraw.text(xCoordinate, yCoordinate, allVertices[vertexId].name);\n }\n }\n\n StdDraw.setPenColor(Color.BLACK);\n\n for (int vertexId = 0; vertexId < vertices; vertexId++) {\n for (DirectedEdge edge : adjacent(vertexId)) {\n int otherVertexId = edge.to();\n Vertex neighborVertex = allVertices[otherVertexId];\n\n DrawUtilities.drawArrow(allVertices[vertexId].coordinates, neighborVertex.coordinates, padding,\n arrowLength);\n }\n }\n }\n\n public Iterable adjacent(int vertexId) {\n return adjacent[vertexId];\n }\n\n public Iterable edges() {\n Bag edges = new Bag<>();\n\n for (int vertex = 0; vertex < vertices; vertex++) {\n for (DirectedEdge edge : adjacent[vertex]) {\n edges.add(edge);\n }\n }\n return edges;\n }\n\n public EuclideanEdgeWeightedDigraph reverse() {\n EuclideanEdgeWeightedDigraph reverse = new EuclideanEdgeWeightedDigraph(vertices);\n\n for (int vertex = 0; vertex < vertices; vertex++) {\n for (DirectedEdge edge : adjacent(vertex)) {\n int neighbor = edge.to();\n reverse.addEdge(new DirectedEdge(neighbor, vertex, edge.weight()));\n }\n }\n return reverse;\n }\n\n @Override\n public String toString() {\n StringBuilder stringBuilder = new StringBuilder();\n\n for (int vertex = 0; vertex < vertices(); vertex++) {\n stringBuilder.append(vertex).append(\": \");\n\n for (DirectedEdge neighbor : adjacent(vertex)) {\n stringBuilder.append(neighbor).append(\" \");\n }\n stringBuilder.append(\"\\n\");\n }\n return stringBuilder.toString();\n }\n }\n\n public class DijkstraSPEuclideanGraph {\n private DirectedEdge[] edgeTo; // last edge on path to vertex\n private double[] distTo; // length of path to vertex\n private IndexMinPriorityQueue priorityQueue;\n\n private int source;\n private boolean shortestDistanceComputed[]; // used to avoid recomputing shortest distances to the same vertex\n private double finalDistanceTo[]; // length of path to a vertex that has already been computed\n private EuclideanEdgeWeightedDigraph euclideanEdgeWeightedDigraph;\n\n public DijkstraSPEuclideanGraph(EuclideanEdgeWeightedDigraph euclideanEdgeWeightedDigraph, int source) {\n priorityQueue = new IndexMinPriorityQueue<>(euclideanEdgeWeightedDigraph.vertices());\n\n shortestDistanceComputed = new boolean[euclideanEdgeWeightedDigraph.vertices()];\n finalDistanceTo = new double[euclideanEdgeWeightedDigraph.vertices()];\n this.euclideanEdgeWeightedDigraph = euclideanEdgeWeightedDigraph;\n this.source = source;\n }\n\n // O(V) due to the use of the Euclidean Heuristic\n private void computeSourceSinkShortestPath(int target) {\n edgeTo = new DirectedEdge[euclideanEdgeWeightedDigraph.vertices()];\n\n distTo = new double[euclideanEdgeWeightedDigraph.vertices()];\n for (int vertex = 0; vertex < euclideanEdgeWeightedDigraph.vertices(); vertex++) {\n distTo[vertex] = Double.POSITIVE_INFINITY;\n }\n\n double distanceFromSourceToTarget = getDistanceBetweenVertices(source, target);\n\n distTo[source] = distanceFromSourceToTarget;\n priorityQueue.insert(source, distanceFromSourceToTarget);\n\n while (!priorityQueue.isEmpty()) {\n int vertexToRelax = priorityQueue.deleteMin();\n\n if (vertexToRelax == target) {\n break;\n }\n\n relax(euclideanEdgeWeightedDigraph, vertexToRelax, target);\n }\n\n finalDistanceTo[target] = distTo[target];\n }\n\n // O(degree(V))\n private void relax(EuclideanEdgeWeightedDigraph euclideanEdgeWeightedDigraph, int vertex, int target) {\n double distanceFromVertexToTarget = getDistanceBetweenVertices(vertex, target);\n\n for (DirectedEdge edge : euclideanEdgeWeightedDigraph.adjacent(vertex)) {\n int neighbor = edge.to();\n\n // Euclidean heuristic\n double distanceFromNeighborToTarget = getDistanceBetweenVertices(neighbor, target);\n\n double distanceToTargetPassingThroughNeighbor = distTo[vertex] + edge.weight()\n + distanceFromNeighborToTarget - distanceFromVertexToTarget;\n\n if (distTo[neighbor] > distanceToTargetPassingThroughNeighbor) {\n distTo[neighbor] = distanceToTargetPassingThroughNeighbor;\n edgeTo[neighbor] = edge;\n\n if (priorityQueue.contains(neighbor)) {\n priorityQueue.decreaseKey(neighbor, distTo[neighbor]);\n } else {\n priorityQueue.insert(neighbor, distTo[neighbor]);\n }\n }\n }\n }\n\n private double getDistanceBetweenVertices(int vertex1, int vertex2) {\n EuclideanEdgeWeightedDigraph.Vertex point1 = euclideanEdgeWeightedDigraph.getVertex(vertex1);\n EuclideanEdgeWeightedDigraph.Vertex point2 = euclideanEdgeWeightedDigraph.getVertex(vertex2);\n\n return Math.sqrt(Math.pow(point1.coordinates.getXCoordinate() - point2.coordinates.getXCoordinate(), 2) +\n Math.pow(point1.coordinates.getYCoordinate() - point2.coordinates.getYCoordinate(), 2));\n }\n\n // O(V)\n public double distTo(int vertex) {\n if (!shortestDistanceComputed[vertex]) {\n computeSourceSinkShortestPath(vertex);\n shortestDistanceComputed[vertex] = true;\n }\n return finalDistanceTo[vertex];\n }\n\n // O(V)\n public boolean hasPathTo(int vertex) {\n if (!shortestDistanceComputed[vertex]) {\n computeSourceSinkShortestPath(vertex);\n shortestDistanceComputed[vertex] = true;\n }\n return finalDistanceTo[vertex] < Double.POSITIVE_INFINITY;\n }\n\n // O(V)\n public Iterable pathTo(int vertex) {\n if (!shortestDistanceComputed[vertex]) {\n computeSourceSinkShortestPath(vertex);\n shortestDistanceComputed[vertex] = true;\n }\n if (!hasPathTo(vertex)) {\n return null;\n }\n\n Stack path = new Stack<>();\n for (DirectedEdge edge = edgeTo[vertex]; edge != null; edge = edgeTo[edge.from()]) {\n path.push(edge);\n }\n return path;\n }\n }\n\n private double getDistanceBetweenVertices(EuclideanEdgeWeightedDigraph.Vertex vertex1,\n EuclideanEdgeWeightedDigraph.Vertex vertex2) {\n return Math.sqrt(Math.pow(vertex1.coordinates.getXCoordinate() - vertex2.coordinates.getXCoordinate(), 2) +\n Math.pow(vertex1.coordinates.getYCoordinate() - vertex2.coordinates.getYCoordinate(), 2));\n }\n\n public static void main(String[] args) {\n Exercise27_ShortestPathsInEuclideanGraphs shortestPathsInEuclideanGraphs =\n new Exercise27_ShortestPathsInEuclideanGraphs();\n\n EuclideanEdgeWeightedDigraph euclideanEdgeWeightedDigraph =\n shortestPathsInEuclideanGraphs.new EuclideanEdgeWeightedDigraph(7);\n\n EuclideanEdgeWeightedDigraph.Vertex vertex0 = euclideanEdgeWeightedDigraph.new Vertex(0, 6.1, 1.3);\n EuclideanEdgeWeightedDigraph.Vertex vertex1 = euclideanEdgeWeightedDigraph.new Vertex(1, 7.2, 2.5);\n EuclideanEdgeWeightedDigraph.Vertex vertex2 = euclideanEdgeWeightedDigraph.new Vertex(2, 8.4, 1.3);\n EuclideanEdgeWeightedDigraph.Vertex vertex3 = euclideanEdgeWeightedDigraph.new Vertex(3, 8.4, 15.3);\n EuclideanEdgeWeightedDigraph.Vertex vertex4 = euclideanEdgeWeightedDigraph.new Vertex(4, 6.1, 15.3);\n EuclideanEdgeWeightedDigraph.Vertex vertex5 = euclideanEdgeWeightedDigraph.new Vertex(5, 7.2, 5.2);\n EuclideanEdgeWeightedDigraph.Vertex vertex6 = euclideanEdgeWeightedDigraph.new Vertex(6, 7.2, 8.4);\n\n euclideanEdgeWeightedDigraph.addVertex(vertex0);\n euclideanEdgeWeightedDigraph.addVertex(vertex1);\n euclideanEdgeWeightedDigraph.addVertex(vertex2);\n euclideanEdgeWeightedDigraph.addVertex(vertex3);\n euclideanEdgeWeightedDigraph.addVertex(vertex4);\n euclideanEdgeWeightedDigraph.addVertex(vertex5);\n euclideanEdgeWeightedDigraph.addVertex(vertex6);\n\n double distanceFromVertex0ToVertex1 = shortestPathsInEuclideanGraphs.getDistanceBetweenVertices(vertex0, vertex1);\n double distanceFromVertex2ToVertex1 = shortestPathsInEuclideanGraphs.getDistanceBetweenVertices(vertex2, vertex1);\n double distanceFromVertex0ToVertex2 = shortestPathsInEuclideanGraphs.getDistanceBetweenVertices(vertex0, vertex2);\n double distanceFromVertex3ToVertex6 = shortestPathsInEuclideanGraphs.getDistanceBetweenVertices(vertex3, vertex6);\n double distanceFromVertex4ToVertex6 = shortestPathsInEuclideanGraphs.getDistanceBetweenVertices(vertex4, vertex6);\n double distanceFromVertex3ToVertex4 = shortestPathsInEuclideanGraphs.getDistanceBetweenVertices(vertex3, vertex4);\n double distanceFromVertex1ToVertex5 = shortestPathsInEuclideanGraphs.getDistanceBetweenVertices(vertex1, vertex5);\n double distanceFromVertex5ToVertex6 = shortestPathsInEuclideanGraphs.getDistanceBetweenVertices(vertex5, vertex6);\n\n euclideanEdgeWeightedDigraph.addEdge(new DirectedEdge(0, 1, distanceFromVertex0ToVertex1));\n euclideanEdgeWeightedDigraph.addEdge(new DirectedEdge(2, 1, distanceFromVertex2ToVertex1));\n euclideanEdgeWeightedDigraph.addEdge(new DirectedEdge(0, 2, distanceFromVertex0ToVertex2));\n euclideanEdgeWeightedDigraph.addEdge(new DirectedEdge(3, 6, distanceFromVertex3ToVertex6));\n euclideanEdgeWeightedDigraph.addEdge(new DirectedEdge(4, 6, distanceFromVertex4ToVertex6));\n euclideanEdgeWeightedDigraph.addEdge(new DirectedEdge(3, 4, distanceFromVertex3ToVertex4));\n euclideanEdgeWeightedDigraph.addEdge(new DirectedEdge(1, 5, distanceFromVertex1ToVertex5));\n euclideanEdgeWeightedDigraph.addEdge(new DirectedEdge(5, 6, distanceFromVertex5ToVertex6));\n\n DijkstraSPEuclideanGraph dijkstraSPEuclideanGraph =\n shortestPathsInEuclideanGraphs.new DijkstraSPEuclideanGraph(euclideanEdgeWeightedDigraph, 0);\n\n euclideanEdgeWeightedDigraph.show(0, 15, 0, 20,\n 0.5, 0.08, 0.5);\n\n for (int vertex = 0; vertex < euclideanEdgeWeightedDigraph.vertices(); vertex++) {\n StdOut.printf(\"Distance to vertex %d: %.2f\\n\", vertex, dijkstraSPEuclideanGraph.distTo(vertex));\n }\n\n StdOut.println(\"\\nExpected distances\");\n StdOut.println(\"Vertex 0: 0.0\");\n StdOut.println(\"Vertex 1: 1.63\");\n StdOut.println(\"Vertex 2: 2.30\");\n StdOut.println(\"Vertex 3: Infinity\");\n StdOut.println(\"Vertex 4: Infinity\");\n StdOut.println(\"Vertex 5: 4.33\");\n StdOut.println(\"Vertex 6: 7.53\");\n\n for (int vertex = 0; vertex < euclideanEdgeWeightedDigraph.vertices(); vertex++) {\n StdOut.print(\"\\nPath from vertex 0 to vertex \" + vertex + \": \");\n\n if (dijkstraSPEuclideanGraph.hasPathTo(vertex)) {\n for (DirectedEdge edge : dijkstraSPEuclideanGraph.pathTo(vertex)) {\n StdOut.print(edge.from() + \"->\" + edge.to() + \" \");\n }\n } else {\n StdOut.print(\"There is no path to vertex \" + vertex);\n }\n }\n\n StdOut.println(\"\\n\\nExpected paths\");\n StdOut.println(\"Vertex 0: \");\n StdOut.println(\"Vertex 1: 0->1\");\n StdOut.println(\"Vertex 2: 0->2\");\n StdOut.println(\"Vertex 3: There is no path to vertex 3\");\n StdOut.println(\"Vertex 4 There is no path to vertex 4\");\n StdOut.println(\"Vertex 5: 0->1 1->5\");\n StdOut.println(\"Vertex 6: 0->1 1->5 5->6\");\n }\n}\n\n\nCorrection for the path cache: `distTo(v)` and `hasPathTo(v)` cache only the distance for each target, but `pathTo(v)` reconstructs from the mutable `edgeTo[]` left by the most recent target computation. Store a path per target when `computeSourceSinkShortestPath(vertex)` finishes, for example `Iterable[] finalPathTo`, and have `pathTo(vertex)` return `finalPathTo[vertex]`. Otherwise a later query can return a path from the wrong source-sink computation.\n", "support_files": [], "metadata": {"number": "4.4.27", "chapter": 4, "chapter_title": "Graphs", "section": 4.4, "section_title": "Shortest Paths", "type": "Creative Problem", "code_execution": false}} {"question": "Longest paths in DAGs. Develop an implementation AcyclicLP that can solve the longest-paths problem in edge-weighted DAGs, as described in PROPOSITION T.", "answer": "package chapter4.section4;\n\nimport chapter1.section3.Stack;\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 08/12/17.\n */\npublic class Exercise28_LongestPathsInDAGs {\n\n public class AcyclicLP {\n\n private AcyclicSP acyclicSP;\n\n public AcyclicLP(EdgeWeightedDigraph edgeWeightedDigraph, int source) {\n EdgeWeightedDigraph negatedEdgesDigraph = new EdgeWeightedDigraph(edgeWeightedDigraph.vertices());\n\n for (int vertex = 0; vertex < edgeWeightedDigraph.vertices(); vertex++) {\n for (DirectedEdge edge : edgeWeightedDigraph.adjacent(vertex)) {\n DirectedEdge negatedEdge = new DirectedEdge(edge.from(), edge.to(), edge.weight() * -1);\n negatedEdgesDigraph.addEdge(negatedEdge);\n }\n }\n\n acyclicSP = new AcyclicSP(negatedEdgesDigraph, source);\n }\n\n public double distTo(int vertex) {\n if (acyclicSP.distTo(vertex) == 0) {\n return 0;\n }\n\n return acyclicSP.distTo(vertex) * -1;\n }\n\n public boolean hasPathTo(int vertex) {\n return acyclicSP.hasPathTo(vertex);\n }\n\n public Iterable pathTo(int vertex) {\n if (!hasPathTo(vertex)) {\n return null;\n }\n Stack reverse = new Stack<>();\n for (DirectedEdge edge : acyclicSP.pathTo(vertex)) {\n reverse.push(new DirectedEdge(edge.from(), edge.to(), -edge.weight()));\n }\n Stack path = new Stack<>();\n for (DirectedEdge edge : reverse) {\n path.push(edge);\n }\n return path;\n }\n }\n\n public static void main(String[] args) {\n EdgeWeightedDigraph edgeWeightedDigraph = new EdgeWeightedDigraph(9);\n edgeWeightedDigraph.addEdge(new DirectedEdge(0, 1, 1));\n edgeWeightedDigraph.addEdge(new DirectedEdge(0, 2, 2));\n edgeWeightedDigraph.addEdge(new DirectedEdge(1, 3, 3));\n edgeWeightedDigraph.addEdge(new DirectedEdge(3, 4, -3));\n edgeWeightedDigraph.addEdge(new DirectedEdge(3, 5, 4));\n edgeWeightedDigraph.addEdge(new DirectedEdge(4, 6, 1));\n edgeWeightedDigraph.addEdge(new DirectedEdge(5, 6, 2));\n edgeWeightedDigraph.addEdge(new DirectedEdge(6, 7, 2));\n\n AcyclicLP acyclicLP = new Exercise28_LongestPathsInDAGs().new AcyclicLP(edgeWeightedDigraph, 0);\n\n int furthestVertex = -1;\n double longestDistance = Double.NEGATIVE_INFINITY;\n\n for (int vertex = 0; vertex < edgeWeightedDigraph.vertices(); vertex++) {\n if (acyclicLP.distTo(vertex) > longestDistance) {\n longestDistance = acyclicLP.distTo(vertex);\n furthestVertex = vertex;\n }\n }\n\n StdOut.println(\"Dist to 1: \" + acyclicLP.distTo(1) + \" Expected: 1.0\");\n StdOut.println(\"Dist to 8: \" + acyclicLP.distTo(8) + \" Expected: -Infinity\");\n\n StdOut.print(\"\\nLongest path: \");\n\n for (DirectedEdge edge : acyclicLP.pathTo(furthestVertex)) {\n StdOut.print(edge.from() + \"->\" + edge.to() + \" \");\n }\n\n StdOut.println(\"\\nExpected: 0->1 1->3 3->5 5->6 6->7\");\n }\n}\n", "support_files": [], "metadata": {"number": "4.4.28", "chapter": 4, "chapter_title": "Graphs", "section": 4.4, "section_title": "Shortest Paths", "type": "Creative Problem", "code_execution": false}} {"question": "All-pairs shortest path in graphs with no negative cycles. Articulate an API like the one implemented on page 656 for the all-pairs shortest-paths problem in graphs with no negative cycles. Develop an implementation that runs a version of Bellman-Ford to identify weights pi[v] such that for any edge v->w, the edge weight plus the difference between pi[v] and pi[w] is nonnegative. Then use these weights to reweight the graph, so that Dijkstra’s algorithm is effective for finding all shortest paths in the reweighted graph.", "answer": "package chapter4.section4;\n\nimport chapter1.section3.Stack;\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 09/12/17.\n */\n// Johnson's algorithm\npublic class Exercise30_AllPairsShortestPathsDigraphsWithoutNegativeCycles {\n\n public interface AllPairsShortestPathsDigraphsWithoutNegativeCyclesInterface {\n\n Iterable path(int source, int target);\n double dist(int source, int target);\n boolean hasPathTo(int source, int target);\n }\n\n // O(V * E lg V)\n public class AllPairsShortestPathsDigraphsWithoutNegativeCycles\n implements AllPairsShortestPathsDigraphsWithoutNegativeCyclesInterface {\n\n private double[][] distances;\n private DirectedEdge[][] edgeTo;\n\n AllPairsShortestPathsDigraphsWithoutNegativeCycles(EdgeWeightedDigraph edgeWeightedDigraph) {\n distances = new double[edgeWeightedDigraph.vertices()][edgeWeightedDigraph.vertices()];\n edgeTo = new DirectedEdge[edgeWeightedDigraph.vertices()][edgeWeightedDigraph.vertices()];\n double[] newWeight = new double[edgeWeightedDigraph.vertices()];\n\n // 0 - Initialize all distances to Double.POSITIVE_INFINITY\n for (int vertex = 0; vertex < edgeWeightedDigraph.vertices(); vertex++) {\n for (int neighbor = 0; neighbor < edgeWeightedDigraph.vertices(); neighbor++) {\n distances[vertex][neighbor] = Double.POSITIVE_INFINITY;\n }\n }\n\n // 1- Add a new vertex to the graph, connected to all other vertices through edges of weight 0\n // O(V + E)\n EdgeWeightedDigraph edgeWeightedDigraphWithSource = new EdgeWeightedDigraph(edgeWeightedDigraph.vertices() + 1);\n for (int vertex = 0; vertex < edgeWeightedDigraph.vertices(); vertex++) {\n for (DirectedEdge edge : edgeWeightedDigraph.adjacent(vertex)) {\n edgeWeightedDigraphWithSource.addEdge(edge);\n }\n }\n\n int newVertexId = edgeWeightedDigraph.vertices();\n\n for (int vertex = 0; vertex < edgeWeightedDigraph.vertices(); vertex++) {\n edgeWeightedDigraphWithSource.addEdge(new DirectedEdge(newVertexId, vertex, 0));\n }\n\n // 2- Run Bellman-Ford to get the distances from the new vertex to every other vertex.\n // Also check if there is any negative cycle\n // O(V * E)\n BellmanFordSP bellmanFordSP = new BellmanFordSP(edgeWeightedDigraphWithSource, newVertexId);\n\n if (bellmanFordSP.hasNegativeCycle()) {\n throw new IllegalArgumentException(\"Graph has a negative cycle\");\n }\n\n // 3- Compute new weights, which are the distance from the new vertex to every other vertex\n // O(V)\n for (int vertex = 0; vertex < edgeWeightedDigraph.vertices(); vertex++) {\n newWeight[vertex] = bellmanFordSP.distTo(vertex);\n }\n\n // 4- Generate a new graph with the new weights\n // O(V + E)\n EdgeWeightedDigraph edgeWeightedDigraphWithNewWeights = new EdgeWeightedDigraph(edgeWeightedDigraph.vertices());\n for (int vertex = 0; vertex < edgeWeightedDigraph.vertices(); vertex++) {\n for (DirectedEdge edge : edgeWeightedDigraph.adjacent(vertex)) {\n double edgeWeight = edge.weight() + newWeight[edge.from()] - newWeight[edge.to()];\n edgeWeightedDigraphWithNewWeights.addEdge(new DirectedEdge(edge.from(), edge.to(), edgeWeight));\n }\n }\n\n // 5- Run Dijkstra to compute all pairs shortest paths on the new graph.\n // Also compute the real all-pairs-shortest-path distances by adjusting the new weights\n // O(V * E lg V) + O(V^2) = O(V * E lg V)\n for (int source = 0; source < edgeWeightedDigraph.vertices(); source++) {\n DijkstraSP dijkstraSP = new DijkstraSP(edgeWeightedDigraphWithNewWeights, source);\n\n for (int target = 0; target < edgeWeightedDigraph.vertices(); target++) {\n double realShortestPathDistance = dijkstraSP.distTo(target) - newWeight[source] + newWeight[target];\n distances[source][target] = realShortestPathDistance;\n\n DirectedEdge currentEdge = dijkstraSP.edgeTo(target);\n\n if (currentEdge == null) {\n continue;\n }\n\n int vertexFrom = currentEdge.from();\n int vertexTo = currentEdge.to();\n double realWeight = currentEdge.weight() - newWeight[vertexFrom] + newWeight[vertexTo];\n\n DirectedEdge realEdgeTo = new DirectedEdge(vertexFrom, vertexTo, realWeight);\n edgeTo[source][target] = realEdgeTo;\n }\n }\n }\n\n @Override\n public Iterable path(int source, int target) {\n if (!hasPathTo(source, target)) {\n return null;\n }\n\n Stack path = new Stack<>();\n for (DirectedEdge edge = edgeTo[source][target]; edge != null; edge = edgeTo[source][edge.from()]) {\n path.push(edge);\n }\n\n return path;\n }\n\n @Override\n public double dist(int source, int target) {\n return distances[source][target];\n }\n\n @Override\n public boolean hasPathTo(int source, int target) {\n return distances[source][target] != Double.POSITIVE_INFINITY;\n }\n }\n\n public static void main(String[] args) {\n Exercise30_AllPairsShortestPathsDigraphsWithoutNegativeCycles exercise30_allPairsShortestPathsDigraphsWithoutNegativeCycles =\n new Exercise30_AllPairsShortestPathsDigraphsWithoutNegativeCycles();\n\n EdgeWeightedDigraph edgeWeightedDigraph = new EdgeWeightedDigraph(6);\n edgeWeightedDigraph.addEdge(new DirectedEdge(0, 1, -2));\n edgeWeightedDigraph.addEdge(new DirectedEdge(1, 2, -1));\n edgeWeightedDigraph.addEdge(new DirectedEdge(2, 0, 4));\n edgeWeightedDigraph.addEdge(new DirectedEdge(2, 3, -3));\n edgeWeightedDigraph.addEdge(new DirectedEdge(2, 4, 2));\n edgeWeightedDigraph.addEdge(new DirectedEdge(5, 3, -4));\n edgeWeightedDigraph.addEdge(new DirectedEdge(5, 4, 1));\n\n AllPairsShortestPathsDigraphsWithoutNegativeCycles allPairsShortestPathsDigraphsWithoutNegativeCycles\n = exercise30_allPairsShortestPathsDigraphsWithoutNegativeCycles\n .new AllPairsShortestPathsDigraphsWithoutNegativeCycles(edgeWeightedDigraph);\n\n double[][] expectedDistances = {\n {0, -2, -3, -6, 1, Double.POSITIVE_INFINITY},\n {3, 0, -1, -4, 1, Double.POSITIVE_INFINITY},\n {4, 2, 0, -3, 2, Double.POSITIVE_INFINITY},\n {Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY,\n 0, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY},\n {Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY,\n Double.POSITIVE_INFINITY, 0, Double.POSITIVE_INFINITY},\n {Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY,\n -4, 1, 0}\n };\n\n for (int source = 0; source < edgeWeightedDigraph.vertices(); source++) {\n for (int target = 0; target < edgeWeightedDigraph.vertices(); target++) {\n StdOut.println(\"Distance from \" + source + \" to \" + target + \": \" +\n allPairsShortestPathsDigraphsWithoutNegativeCycles.dist(source, target)\n + \" Expected: \" + expectedDistances[source][target]);\n }\n }\n\n StdOut.println();\n\n for (int source = 0; source < edgeWeightedDigraph.vertices(); source++) {\n for (int target = 0; target < edgeWeightedDigraph.vertices(); target++) {\n StdOut.print(\"Shortest path from \" + source + \" to \" + target + \": \");\n\n if (!allPairsShortestPathsDigraphsWithoutNegativeCycles.hasPathTo(source, target)) {\n StdOut.println(\"No path exists\");\n continue;\n }\n\n for (DirectedEdge edge : allPairsShortestPathsDigraphsWithoutNegativeCycles.path(source, target)) {\n StdOut.print(edge.from() + \"->\" + edge.to() + \" (\" + edge.weight() + \") \");\n }\n\n StdOut.println();\n }\n }\n\n StdOut.println(\"\\nExpected:\");\n StdOut.println(\"Shortest path from 0 to 0: \\n\" +\n \"Shortest path from 0 to 1: 0->1 (-2.0) \\n\" +\n \"Shortest path from 0 to 2: 0->1 (-2.0) 1->2 (-1.0) \\n\" +\n \"Shortest path from 0 to 3: 0->1 (-2.0) 1->2 (-1.0) 2->3 (-3.0) \\n\" +\n \"Shortest path from 0 to 4: 0->1 (-2.0) 1->2 (-1.0) 2->4 (2.0) \\n\" +\n \"Shortest path from 0 to 5: No path exists\\n\" +\n \"Shortest path from 1 to 0: 1->2 (-1.0) 2->0 (4.0) \\n\" +\n \"Shortest path from 1 to 1: \\n\" +\n \"Shortest path from 1 to 2: 1->2 (-1.0) \\n\" +\n \"Shortest path from 1 to 3: 1->2 (-1.0) 2->3 (-3.0) \\n\" +\n \"Shortest path from 1 to 4: 1->2 (-1.0) 2->4 (2.0) \\n\" +\n \"Shortest path from 1 to 5: No path exists\\n\" +\n \"Shortest path from 2 to 0: 2->0 (4.0) \\n\" +\n \"Shortest path from 2 to 1: 2->0 (4.0) 0->1 (-2.0) \\n\" +\n \"Shortest path from 2 to 2: \\n\" +\n \"Shortest path from 2 to 3: 2->3 (-3.0) \\n\" +\n \"Shortest path from 2 to 4: 2->4 (2.0) \\n\" +\n \"Shortest path from 2 to 5: No path exists\\n\" +\n \"Shortest path from 3 to 0: No path exists\\n\" +\n \"Shortest path from 3 to 1: No path exists\\n\" +\n \"Shortest path from 3 to 2: No path exists\\n\" +\n \"Shortest path from 3 to 3: \\n\" +\n \"Shortest path from 3 to 4: No path exists\\n\" +\n \"Shortest path from 3 to 5: No path exists\\n\" +\n \"Shortest path from 4 to 0: No path exists\\n\" +\n \"Shortest path from 4 to 1: No path exists\\n\" +\n \"Shortest path from 4 to 2: No path exists\\n\" +\n \"Shortest path from 4 to 3: No path exists\\n\" +\n \"Shortest path from 4 to 4: \\n\" +\n \"Shortest path from 4 to 5: No path exists\\n\" +\n \"Shortest path from 5 to 0: No path exists\\n\" +\n \"Shortest path from 5 to 1: No path exists\\n\" +\n \"Shortest path from 5 to 2: No path exists\\n\" +\n \"Shortest path from 5 to 3: 5->3 (-4.0) \\n\" +\n \"Shortest path from 5 to 4: 5->4 (1.0) \\n\" +\n \"Shortest path from 5 to 5: \");\n }\n}\n", "support_files": [], "metadata": {"number": "4.4.30", "chapter": 4, "chapter_title": "Graphs", "section": 4.4, "section_title": "Shortest Paths", "type": "Creative Problem", "code_execution": false}} {"question": "All-pairs shortest path on a line. Given a weighted line graph (undirected connected graph, all vertices of degree 2, except two endpoints which have degree 1), devise an algorithm that preprocesses the graph in linear time and can return the distance of the shortest path between any two vertices in constant time.", "answer": "package chapter4.section4;\n\nimport chapter1.section3.Queue;\nimport chapter4.section3.Edge;\nimport chapter4.section3.EdgeWeightedGraph;\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 09/12/17.\n */\npublic class Exercise31_AllPairsShortestPathsOnALine {\n\n public class AllPairsShortestPathsOnALine {\n\n private double[] distanceFromSource;\n\n AllPairsShortestPathsOnALine(EdgeWeightedGraph edgeWeightedGraph) {\n\n boolean isLineGraph = true;\n int numberOfVerticesWithDegree1 = 0;\n int sourceVertex = -1;\n\n // Find one of the two sources\n for (int vertex = 0; vertex < edgeWeightedGraph.vertices(); vertex++) {\n int outdegree = 0;\n\n for (Edge edge : edgeWeightedGraph.adjacent(vertex)) {\n if (edge.weight() < 0) {\n throw new IllegalArgumentException(\"Edge weights cannot be negative\");\n }\n\n outdegree++;\n }\n\n if (outdegree == 1) {\n if (sourceVertex == -1) {\n sourceVertex = vertex;\n }\n\n numberOfVerticesWithDegree1++;\n } else if (outdegree == 0 || outdegree > 2) {\n isLineGraph = false;\n break;\n }\n }\n\n if (numberOfVerticesWithDegree1 != 2) {\n isLineGraph = false;\n }\n\n if (!isLineGraph) {\n throw new IllegalArgumentException(\"Graph is not a line graph\");\n }\n\n distanceFromSource = new double[edgeWeightedGraph.vertices()];\n boolean[] visited = new boolean[edgeWeightedGraph.vertices()];\n\n for (int vertex = 0; vertex < distanceFromSource.length; vertex++) {\n distanceFromSource[vertex] = Double.POSITIVE_INFINITY;\n }\n\n // Do a breadth-first-search to compute the distances from the source in O(V + E)\n Queue queue = new Queue<>();\n queue.enqueue(sourceVertex);\n visited[sourceVertex] = true;\n\n distanceFromSource[sourceVertex] = 0;\n\n while (!queue.isEmpty()) {\n int currentVertex = queue.dequeue();\n\n for (Edge edge : edgeWeightedGraph.adjacent(currentVertex)) {\n int neighbor = edge.other(currentVertex);\n\n if (!visited[neighbor]) {\n distanceFromSource[neighbor] = distanceFromSource[currentVertex] + edge.weight();\n queue.enqueue(neighbor);\n visited[neighbor] = true;\n }\n }\n }\n }\n\n public double dist(int source, int target) {\n return Math.abs(distanceFromSource[source] - distanceFromSource[target]);\n }\n }\n\n public static void main(String[] args) {\n EdgeWeightedGraph edgeWeightedGraph = new EdgeWeightedGraph(5);\n edgeWeightedGraph.addEdge(new Edge(0, 1, 2));\n edgeWeightedGraph.addEdge(new Edge(1, 2, 3));\n edgeWeightedGraph.addEdge(new Edge(2, 3, 4));\n edgeWeightedGraph.addEdge(new Edge(3, 4, 1));\n\n AllPairsShortestPathsOnALine allPairsShortestPathsOnALine =\n new Exercise31_AllPairsShortestPathsOnALine().new AllPairsShortestPathsOnALine(edgeWeightedGraph);\n\n double[][] expectedDistances = {\n {0, 2, 5, 9, 10},\n {2, 0, 3, 7, 8},\n {5, 3, 0, 4, 5},\n {9, 7, 4, 0, 1},\n {10, 8, 5, 1, 0}\n };\n\n for (int source = 0; source < edgeWeightedGraph.vertices(); source++) {\n for (int target = 0; target < edgeWeightedGraph.vertices(); target++) {\n StdOut.println(\"Distance from \" + source + \" to \" + target + \": \" +\n allPairsShortestPathsOnALine.dist(source, target)\n + \" Expected: \" + expectedDistances[source][target]);\n }\n }\n }\n}\n", "support_files": [], "metadata": {"number": "4.4.31", "chapter": 4, "chapter_title": "Graphs", "section": 4.4, "section_title": "Shortest Paths", "type": "Creative Problem", "code_execution": false}} {"question": "Shortest path in a grid. Given an N-by-N matrix of positive integers, find the shortest path from the (0, 0) entry to the (N-1, N-1) entry, where the length of the path is the sum of the integers in the path. Repeat the problem but assume you can only move right and down.", "answer": "package chapter4.section4;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 10/12/17.\n */\npublic class Exercise33_ShortestPathInAGrid {\n\n public Iterable shortestPathInGridAll4Directions(double[][] matrix) {\n EdgeWeightedDigraph edgeWeightedDigraph = new EdgeWeightedDigraph(matrix.length * matrix[0].length);\n\n for (int row = 0; row < matrix.length; row++) {\n for (int column = 0; column < matrix[0].length; column++) {\n\n int currentCellIndex = getCellIndex(matrix, row, column);\n\n int[] neighborRows = {-1, 0, 0, 1};\n int[] neighborColumns = {0, -1, 1, 0};\n\n for (int i = 0; i < neighborRows.length; i++) {\n int neighborRow = row + neighborRows[i];\n int neighborColumn = column + neighborColumns[i];\n\n if (isValidCell(matrix, neighborRow, neighborColumn)) {\n int neighborCellIndex = getCellIndex(matrix, neighborRow, neighborColumn);\n edgeWeightedDigraph.addEdge(new DirectedEdge(currentCellIndex, neighborCellIndex,\n matrix[neighborRow][neighborColumn]));\n }\n }\n }\n }\n\n int targetCell = matrix.length * matrix.length - 1;\n\n DijkstraSP dijkstraSP = new DijkstraSP(edgeWeightedDigraph, 0);\n return dijkstraSP.pathTo(targetCell);\n }\n\n public Iterable shortestPathInGridOnlyRightOrDown(double[][] matrix) {\n EdgeWeightedDigraph edgeWeightedDigraph = new EdgeWeightedDigraph(matrix.length * matrix[0].length);\n\n for (int row = 0; row < matrix.length; row++) {\n for (int column = 0; column < matrix[0].length; column++) {\n\n int currentCellIndex = getCellIndex(matrix, row, column);\n\n int[] neighborRows = {0, 1};\n int[] neighborColumns = {1, 0};\n\n for (int i = 0; i < neighborRows.length; i++) {\n int neighborRow = row + neighborRows[i];\n int neighborColumn = column + neighborColumns[i];\n\n if (isValidCell(matrix, neighborRow, neighborColumn)) {\n int neighborCellIndex = getCellIndex(matrix, neighborRow, neighborColumn);\n edgeWeightedDigraph.addEdge(new DirectedEdge(currentCellIndex, neighborCellIndex,\n matrix[neighborRow][neighborColumn]));\n }\n }\n }\n }\n\n int targetCell = matrix.length * matrix.length - 1;\n\n DijkstraSP dijkstraSP = new DijkstraSP(edgeWeightedDigraph, 0);\n return dijkstraSP.pathTo(targetCell);\n }\n\n private boolean isValidCell(double[][] matrix, int row, int column) {\n return row >= 0 && row < matrix.length && column >= 0 && column < matrix[0].length;\n }\n\n private int getCellIndex(double[][] matrix, int row, int column) {\n return matrix.length * row + column;\n }\n\n public static void main(String[] args) {\n Exercise33_ShortestPathInAGrid shortestPathInAGrid = new Exercise33_ShortestPathInAGrid();\n\n StdOut.println(\"Moving either up, down, left or right:\");\n double[][] matrix1 = {\n {0, 1},\n {3, 1}\n };\n\n StdOut.print(\"Path: \");\n Iterable shortestPath1 = shortestPathInAGrid.shortestPathInGridAll4Directions(matrix1);\n for (DirectedEdge edge : shortestPath1) {\n StdOut.print(edge.from() + \"->\" + edge.to() + \" \");\n }\n StdOut.println(\"\\nExpected: 0->1 1->3\");\n\n double[][] matrix2 = {\n {0, 2, 1},\n {1, 3, 2},\n {4, 2, 5}\n };\n\n StdOut.print(\"\\nPath: \");\n Iterable shortestPath2 = shortestPathInAGrid.shortestPathInGridAll4Directions(matrix2);\n for (DirectedEdge edge : shortestPath2) {\n StdOut.print(edge.from() + \"->\" + edge.to() + \" \");\n }\n StdOut.println(\"\\nExpected: 0->1 1->2 2->5 5->8\");\n\n double[][] matrix3 = {\n {0, 4, 10, 10, 10},\n {1, 8, 1, 1, 1},\n {1, 8, 1, 10, 1},\n {1, 1, 1, 10, 1},\n {10, 10, 10, 10, 2}\n };\n\n StdOut.print(\"\\nPath: \");\n Iterable shortestPath3 = shortestPathInAGrid.shortestPathInGridAll4Directions(matrix3);\n for (DirectedEdge edge : shortestPath3) {\n StdOut.print(edge.from() + \"->\" + edge.to() + \" \");\n }\n StdOut.println(\"\\nExpected: 0->5 5->10 10->15 15->16 16->17 17->12 12->7 7->8 8->9 9->14 14->19 19->24\");\n\n StdOut.println(\"\\nMoving only right and down:\");\n StdOut.print(\"Path: \");\n\n Iterable shortestPath4 = shortestPathInAGrid.shortestPathInGridOnlyRightOrDown(matrix3);\n for (DirectedEdge edge : shortestPath4) {\n StdOut.print(edge.from() + \"->\" + edge.to() + \" \");\n }\n StdOut.println(\"\\nExpected: 0->5 5->6 6->7 7->8 8->9 9->14 14->19 19->24\");\n }\n}\n", "support_files": [], "metadata": {"number": "4.4.33", "chapter": 4, "chapter_title": "Graphs", "section": 4.4, "section_title": "Shortest Paths", "type": "Creative Problem", "code_execution": false}} {"question": "Bitonic shortest path. Given a digraph, find a bitonic shortest path from s to every other vertex (if one exists). A path is bitonic if there is an intermediate vertex v such that the edges on the path from s to v are strictly increasing and the edges on the path from v to t are strictly decreasing. The path should be simple (no repeated vertices).", "answer": "package chapter4.section4;\n\nimport chapter2.section4.PriorityQueueResize;\nimport chapter3.section4.SeparateChainingHashTable;\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.*;\n\n/**\n * Created by Rene Argento on 10/12/17.\n */\n// If we didn't need a simple path (if repeated vertices were allowed), it would be possible to\n // 1- relax all edges in ascending order, starting from vertex s, to get the shortest ascending distance from it\n // to all other vertices.\n // 2- for every vertex v: relax all edges in descending order starting from v to get the shortest descending distance\n // from it to all other vertices.\n // 3- test all combinations of ascending order paths and descending order paths to get the shortest bitonic path\n // (based on http://tryalgo.org/en/shortest-paths/2016/06/25/bitonic-shortest-path/ )\n\n // Since we need simple paths, the algorithm can be simplified to just relaxing all edges in ascending order\n // from s to all other vertices and then relaxing all edges again, in descending order from s to all other vertices\npublic class Exercise35_BitonicShortestPath {\n\n public class Path implements Comparable {\n\n private Path previousPath;\n private DirectedEdge directedEdge;\n private double weight;\n private boolean isDescending;\n private int numberOfEdges;\n private HashSet verticesInPath;\n\n Path(DirectedEdge directedEdge) {\n this.directedEdge = directedEdge;\n weight = directedEdge.weight();\n verticesInPath = new HashSet<>();\n verticesInPath.add(directedEdge.from());\n verticesInPath.add(directedEdge.to());\n\n numberOfEdges = 1;\n }\n\n Path(Path previousPath, DirectedEdge directedEdge) {\n this(directedEdge);\n this.previousPath = previousPath;\n\n weight += previousPath.weight();\n numberOfEdges += previousPath.numberOfEdges;\n\n verticesInPath = new HashSet<>(previousPath.verticesInPath);\n verticesInPath.add(directedEdge.to());\n\n if (previousPath != null && previousPath.directedEdge.weight() > directedEdge.weight()) {\n isDescending = true;\n }\n }\n\n public boolean containsVertex(int vertex) {\n return verticesInPath.contains(vertex);\n }\n\n public double weight() {\n return weight;\n }\n\n public boolean isDescending() {\n return isDescending;\n }\n\n public int numberOfEdges() {\n return numberOfEdges;\n }\n\n public Iterable getPath() {\n LinkedList path = new LinkedList<>();\n\n Path iterator = previousPath;\n\n while (iterator != null && iterator.directedEdge != null) {\n path.addFirst(iterator.directedEdge);\n\n iterator = iterator.previousPath;\n }\n path.add(directedEdge);\n\n return path;\n }\n\n @Override\n public int compareTo(Path other) {\n if (this.weight < other.weight) {\n return -1;\n } else if (this.weight > other.weight) {\n return 1;\n } else {\n return 0;\n }\n }\n }\n\n public class VertexInformation {\n\n private DirectedEdge[] edges;\n private int edgeIteratorPosition;\n\n VertexInformation(DirectedEdge[] edges) {\n this.edges = edges;\n edgeIteratorPosition = 0;\n }\n\n public void incrementEdgeIteratorPosition() {\n edgeIteratorPosition++;\n }\n\n public DirectedEdge[] getEdges() {\n return edges;\n }\n\n public int getEdgeIteratorPosition() {\n return edgeIteratorPosition;\n }\n }\n\n public class BitonicSP {\n\n private Path[] bitonicPathTo; // bitonic path to vertex\n\n // O(P lg P), where P is the number of paths in the digraph\n // Includes optimization to prune paths that are not bitonic, ie. ascending + descending + ascending\n // or descending + ascending\n public BitonicSP(EdgeWeightedDigraph edgeWeightedDigraph, int source) {\n\n bitonicPathTo = new Path[edgeWeightedDigraph.vertices()];\n\n // 1- Relax edges in ascending order to get a monotonic increasing shortest path\n Comparator edgesComparator = new Comparator() {\n @Override\n public int compare(DirectedEdge edge1, DirectedEdge edge2) {\n if (edge1.weight() > edge2.weight()) {\n return -1;\n } else if (edge1.weight() < edge2.weight()) {\n return 1;\n } else {\n return 0;\n }\n }\n };\n\n List allCurrentPaths = new ArrayList<>();\n\n relaxAllEdgesInSpecificOrder(edgeWeightedDigraph, source, edgesComparator, allCurrentPaths,true);\n\n // 2- Relax edges in descending order to get a monotonic decreasing shortest path\n edgesComparator = new Comparator() {\n @Override\n public int compare(DirectedEdge edge1, DirectedEdge edge2) {\n if (edge1.weight() < edge2.weight()) {\n return -1;\n } else if (edge1.weight() > edge2.weight()) {\n return 1;\n } else {\n return 0;\n }\n }\n };\n\n relaxAllEdgesInSpecificOrder(edgeWeightedDigraph, source, edgesComparator, allCurrentPaths, false);\n }\n\n private void relaxAllEdgesInSpecificOrder(EdgeWeightedDigraph edgeWeightedDigraph, int source,\n Comparator edgesComparator, List allCurrentPaths,\n boolean isAscendingOrder) {\n\n // Create a map with vertices as keys and sorted outgoing edges as values\n SeparateChainingHashTable verticesInformation = new SeparateChainingHashTable<>();\n for (int vertex = 0; vertex < edgeWeightedDigraph.vertices(); vertex++) {\n DirectedEdge[] edges = new DirectedEdge[edgeWeightedDigraph.outdegree(vertex)];\n\n int edgeIndex = 0;\n for (DirectedEdge edge : edgeWeightedDigraph.adjacent(vertex)) {\n edges[edgeIndex++] = edge;\n }\n\n Arrays.sort(edges, edgesComparator);\n\n verticesInformation.put(vertex, new VertexInformation(edges));\n }\n\n PriorityQueueResize priorityQueue = new PriorityQueueResize<>(PriorityQueueResize.Orientation.MIN);\n\n // If we are relaxing edges for the first time, add the initial paths to the priority queue\n if (isAscendingOrder) {\n VertexInformation sourceVertexInformation = verticesInformation.get(source);\n while (sourceVertexInformation.getEdgeIteratorPosition() < sourceVertexInformation.getEdges().length) {\n DirectedEdge edge = sourceVertexInformation.getEdges()[sourceVertexInformation.getEdgeIteratorPosition()];\n sourceVertexInformation.incrementEdgeIteratorPosition();\n\n Path path = new Path(edge);\n priorityQueue.insert(path);\n\n allCurrentPaths.add(path);\n }\n }\n\n // If we are relaxing edges for the second time, add all existing ascending paths to the priority queue\n if (!allCurrentPaths.isEmpty()) {\n for (Path currentPath : allCurrentPaths) {\n priorityQueue.insert(currentPath);\n }\n }\n\n while (!priorityQueue.isEmpty()) {\n Path currentShortestPath = priorityQueue.deleteTop();\n\n DirectedEdge currentEdge = currentShortestPath.directedEdge;\n\n int nextVertexInPath = currentEdge.to();\n VertexInformation nextVertexInformation = verticesInformation.get(nextVertexInPath);\n\n // Edge case: a bitonic path consisting of 2 edges of the same weight.\n // s to v with only one edge is strictly increasing, v to t with only one edge is strictly decreasing\n boolean isEdgeCase = false;\n\n if (currentShortestPath.numberOfEdges() == 2\n && currentEdge.weight() == currentShortestPath.previousPath.directedEdge.weight()) {\n isEdgeCase = true;\n }\n\n if ((currentShortestPath.isDescending() || isEdgeCase)\n && (currentShortestPath.weight() < bitonicPathDistTo(nextVertexInPath)\n || bitonicPathTo[nextVertexInPath] == null)) {\n bitonicPathTo[nextVertexInPath] = currentShortestPath;\n }\n\n double weightInPreviousEdge = currentEdge.weight();\n\n while (nextVertexInformation.getEdgeIteratorPosition() < nextVertexInformation.getEdges().length) {\n DirectedEdge edge =\n verticesInformation.get(nextVertexInPath).getEdges()[nextVertexInformation.getEdgeIteratorPosition()];\n\n boolean isEdgeInEdgeCase = currentShortestPath.numberOfEdges() == 1\n && edge.weight() == weightInPreviousEdge;\n\n if (!isEdgeInEdgeCase && ((isAscendingOrder && edge.weight() <= weightInPreviousEdge)\n || (!isAscendingOrder && edge.weight() >= weightInPreviousEdge))) {\n break;\n }\n\n nextVertexInformation.incrementEdgeIteratorPosition();\n\n if (currentShortestPath.containsVertex(edge.to())) {\n continue;\n }\n\n Path path = new Path(currentShortestPath, edge);\n priorityQueue.insert(path);\n\n // If we are relaxing edges for the first time, store the ascending paths so they can be further\n // relaxed when computing the descending paths on the second relaxation\n if (isAscendingOrder) {\n allCurrentPaths.add(path);\n }\n }\n }\n }\n\n public double bitonicPathDistTo(int vertex) {\n if (hasBitonicPathTo(vertex)) {\n return bitonicPathTo[vertex].weight();\n } else {\n return Double.POSITIVE_INFINITY;\n }\n }\n\n public boolean hasBitonicPathTo(int vertex) {\n return bitonicPathTo[vertex] != null;\n }\n\n public Iterable bitonicPathTo(int vertex) {\n if (!hasBitonicPathTo(vertex)) {\n return null;\n }\n\n return bitonicPathTo[vertex].getPath();\n }\n }\n\n public static void main(String[] args) {\n EdgeWeightedDigraph edgeWeightedDigraph = new EdgeWeightedDigraph(13);\n edgeWeightedDigraph.addEdge(new DirectedEdge(0, 1, 4));\n edgeWeightedDigraph.addEdge(new DirectedEdge(1, 2, 5));\n edgeWeightedDigraph.addEdge(new DirectedEdge(2, 3, 4));\n edgeWeightedDigraph.addEdge(new DirectedEdge(3, 4, 1));\n edgeWeightedDigraph.addEdge(new DirectedEdge(1, 5, 5));\n edgeWeightedDigraph.addEdge(new DirectedEdge(5, 6, 3));\n edgeWeightedDigraph.addEdge(new DirectedEdge(6, 7, 8));\n edgeWeightedDigraph.addEdge(new DirectedEdge(0, 8, 2));\n edgeWeightedDigraph.addEdge(new DirectedEdge(8, 9, 1));\n edgeWeightedDigraph.addEdge(new DirectedEdge(1, 2, 4));\n\n // With the following 3 edges, there is now a shortest monotonic ascending path from 0 to 3:\n // 0->1 (1.0) 1->2 (2.0) 2->3 (3.0)\n // but it is not bitonic, so it should not be selected\n edgeWeightedDigraph.addEdge(new DirectedEdge(0, 1, 1));\n edgeWeightedDigraph.addEdge(new DirectedEdge(1, 2, 2));\n edgeWeightedDigraph.addEdge(new DirectedEdge(2, 3, 3));\n\n // Edge case: a bitonic path consisting of 2 edges of the same weight\n // 0->10 (3.0) 10->11 (3.0)\n // Should be in the final solution\n edgeWeightedDigraph.addEdge(new DirectedEdge(0, 10, 3));\n edgeWeightedDigraph.addEdge(new DirectedEdge(10, 11, 3));\n\n // Not an edge case: 3 edges of the same weight in the path\n // 0->10 (3.0) 10->11 (3.0) 11->12 (3.0)\n // Should not be in the final solution\n edgeWeightedDigraph.addEdge(new DirectedEdge(11, 12, 3));\n\n Exercise35_BitonicShortestPath.BitonicSP bitonicSP =\n new Exercise35_BitonicShortestPath().new BitonicSP(edgeWeightedDigraph, 0);\n\n StdOut.print(\"Bitonic shortest paths: \");\n\n for (int vertex = 0; vertex < edgeWeightedDigraph.vertices(); vertex++) {\n StdOut.print(\"\\nPath from vertex 0 to vertex \" + vertex + \": \");\n\n if (bitonicSP.hasBitonicPathTo(vertex)) {\n for (DirectedEdge edge : bitonicSP.bitonicPathTo(vertex)) {\n StdOut.print(edge.from() + \"->\" + edge.to() + \" (\" + edge.weight() + \") \");\n }\n } else {\n StdOut.print(\"There is no bitonic path to vertex \" + vertex);\n }\n }\n\n StdOut.println(\"\\n\\nExpected bitonic paths\");\n StdOut.println(\"Vertex 0: There is no bitonic path to vertex 0\"); // There is a path but it is not bitonic\n StdOut.println(\"Vertex 1: There is no bitonic path to vertex 1\"); // There is a path but it is not bitonic\n StdOut.println(\"Vertex 2: 0->1 (4.0) 1->2 (2.0)\");\n StdOut.println(\"Vertex 3: 0->1 (1.0) 1->2 (4.0) 2->3 (3.0)\");\n StdOut.println(\"Vertex 4: 0->1 (1.0) 1->2 (2.0) 2->3 (3.0) 3->4 (1.0)\");\n StdOut.println(\"Vertex 5: There is no bitonic path to vertex 5\"); // There is a path but it is not bitonic\n StdOut.println(\"Vertex 6: 0->1 (1.0) 1->5 (5.0) 5->6 (3.0)\");\n StdOut.println(\"Vertex 7: There is no bitonic path to vertex 7\"); // There is a path but it is not bitonic\n StdOut.println(\"Vertex 8: There is no bitonic path to vertex 8\"); // There is a path but it is not bitonic\n StdOut.println(\"Vertex 9: 0->8 (2.0) 8->9 (1.0)\");\n StdOut.println(\"Vertex 10: There is no bitonic path to vertex 10\"); // There is a path but it is not bitonic\n StdOut.println(\"Vertex 11: 0->10 (3.0) 10->11 (3.0)\"); // An edge case\n StdOut.println(\"Vertex 12: There is no bitonic path to vertex 12\"); // There is a path but it is not bitonic\n\n double[] expectedDistances = {\n Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, 6, 8, 7, Double.POSITIVE_INFINITY,\n 9, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, 3, Double.POSITIVE_INFINITY,\n 6, Double.POSITIVE_INFINITY\n };\n\n for (int vertex = 0; vertex < edgeWeightedDigraph.vertices(); vertex++) {\n StdOut.print(\"\\nDistance to vertex \" + vertex + \": \" + bitonicSP.bitonicPathDistTo(vertex)\n + \" Expected: \" + expectedDistances[vertex]);\n }\n }\n}\n", "support_files": [], "metadata": {"number": "4.4.35", "chapter": 4, "chapter_title": "Graphs", "section": 4.4, "section_title": "Shortest Paths", "type": "Creative Problem", "code_execution": false}} {"question": "Give a trace for LSD string sort for the keys\n no is th ti fo al go pe to co to th ai of th pa", "answer": "5.1.2\n\nTrace for LSD string sort (same model as used in the book):\n\ninput d=1 d=0 output\nno pa ai ai\nis pe al al\nth of co co\nti th fo fo\nfo th go go\nal th is is\ngo ti no no\npe ai of of\nto al pa pa\nco no pe pe\nto fo th th\nth go th th\nai to th th\nof co ti ti\nth to to to\npa is to to\n", "support_files": [], "metadata": {"number": "5.1.2", "chapter": 5, "chapter_title": "Strings", "section": 5.1, "section_title": "String Sorts", "type": "Exercise", "code_execution": false}} {"question": "Give a trace for MSD string sort for the keys\n no is th ti fo al go pe to co to th ai of th pa", "answer": "5.1.3\n\nAccording to ASC II values, indices of chars 'a' through 'z' start at 97.\nBut this trace indices follow the book convention of 'a' starting at 0.\n\nTrace for MSD string sort (same model as used in the book):\n\nTop level of sort(array, 0, 15, 0):\n\ninput\n0 no\n1 is\n2 th\n3 ti\n4 fo\n5 al\n6 go\n7 pe\n8 to\n9 co\n10 to\n11 th\n12 ai\n13 of\n14 th\n15 pa\n\nd=0\nCount frequencies\n0 0\n1 0\n2 a 2\n3 b 0\n4 c 1\n5 d 0\n6 e 0\n7 f 1\n8 g 1\n9 h 0\n10 i 1\n11 j 0\n12 k 0\n13 l 0\n14 m 0\n15 n 1\n16 o 1\n17 p 2\n18 q 0\n19 r 0\n20 s 0\n21 t 6\n22 u 0\n23 v 0\n24 x 0\n25 w 0\n26 y 0\n27 z 0\n\nTransform counts to indices\n0 0\n1 0\n2 a 2\n3 b 2\n4 c 3\n5 d 3\n6 e 3\n7 f 4\n8 g 5\n9 h 5\n10 i 6\n11 j 6\n12 k 6\n13 l 6\n14 m 6\n15 n 7\n16 o 8\n17 p 10\n18 q 10\n19 r 10\n20 s 10\n21 t 16\n22 u 16\n23 v 16\n24 x 16\n25 w 16\n26 y 16\n27 z 16\n\nDistribute and copy back\n0 al\n1 ai\n2 co\n3 fo\n4 go\n5 is\n6 no\n7 of\n8 pe\n9 pa\n10 th\n11 ti\n12 to\n13 to\n14 th\n15 th\n\nIndices at completion of distribute phase\n0 0\n1 2\n2 a 2\n3 b 3\n4 c 3\n5 d 3\n6 e 4\n7 f 5\n8 g 5\n9 h 6\n10 i 6\n11 j 6\n12 k 6\n13 l 6\n14 m 7\n15 n 8\n16 o 10\n17 p 10\n18 q 10\n19 r 10\n20 s 16\n21 t 16\n22 u 16\n23 v 16\n24 x 16\n25 w 16\n26 y 16\n27 z 16\n\nRecursively sort subarrays\nsort(a, 0, 1, 1);\nsort(a, 2, 1, 1);\nsort(a, 2, 2, 1);\nsort(a, 3, 2, 1);\nsort(a, 3, 2, 1);\nsort(a, 3, 3, 1);\nsort(a, 4, 4, 1);\nsort(a, 5, 4, 1);\nsort(a, 5, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 6, 1);\nsort(a, 7, 7, 1);\nsort(a, 8, 9, 1);\nsort(a, 10, 9, 1);\nsort(a, 10, 9, 1);\nsort(a, 10, 9, 1);\nsort(a, 10, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\n\nSorted result\n0 ai\n1 al\n2 co\n3 fo\n4 go\n5 is\n6 no\n7 of\n8 pa\n9 pe\n10 th\n11 th\n12 th\n13 ti\n14 to\n15 to\n\nTrace of recursive calls for MSD string sort (no cutoff for small subarrays, subarrays of size 0 and 1 omitted)\n\ninput __ __ output\nno al ai ai ai ai \nis ai al al al al\nth co -- co co co\nti fo co fo fo fo\nfo go fo go go go\nal is go is is is\ngo no is no no no\npe of no of of of\nto pe of -- pa pa\nco pa pe pa pe pe\nto th pa pe -- th\nth ti th -- th th\nai to ti th th th\nof to to ti th ti\nth th to to ti to\npa th th to to to\n -- th th to\n th --\n", "support_files": [], "metadata": {"number": "5.1.3", "chapter": 5, "chapter_title": "Strings", "section": 5.1, "section_title": "String Sorts", "type": "Exercise", "code_execution": false}} {"question": "Give a trace for 3-way string quicksort for the keys\n no is th ti fo al go pe to co to th ai of th pa", "answer": "5.1.4\n\nTrace for 3-way string quicksort (same model as used in the book):\n\n -- -- --\n0 no is ai ai ai ai\n1 is ai co al -- al\n2 th co fo -- al co\n3 ti fo al fo -- fo\n4 fo al go go co go\n5 al go -- co -- is\n6 go -- is -- fo no\n7 pe no -- is -- of\n8 to -- no -- go pa\n9 co to -- no -- pe\n10 to pe pe -- is th\n11 th to of of -- th\n12 ai th pa -- no th\n13 of ti -- pe -- ti\n14 th of th pa of to\n15 pa th ti -- -- to\n pa to th pa \n th th th --\n to th pe\n th -- --\n -- to th\n to th\n ti th\n --\n ti\n --\n to\n to\n --\n", "support_files": [], "metadata": {"number": "5.1.4", "chapter": 5, "chapter_title": "Strings", "section": 5.1, "section_title": "String Sorts", "type": "Exercise", "code_execution": false}} {"question": "Give a trace for MSD string sort for the keys\n now is the time for all good people to come to the aid of", "answer": "5.1.5\n\nAccording to ASC II values, indices of chars 'a' through 'z' start at 97.\nBut this trace indices follow the book convention of 'a' starting at 0.\n\nTrace for MSD string sort (same model as used in the book):\n\nTop level of sort(array, 0, 13, 0):\n\ninput\n0 now\n1 is\n2 the\n3 time\n4 for\n5 all\n6 good\n7 people\n8 to\n9 come\n10 to\n11 the\n12 aid\n13 of\n\nd=0\nCount frequencies\n0 0\n1 0\n2 a 2\n3 b 0\n4 c 1\n5 d 0\n6 e 0\n7 f 1\n8 g 1\n9 h 0\n10 i 1\n11 j 0\n12 k 0\n13 l 0\n14 m 0\n15 n 1\n16 o 1\n17 p 1\n18 q 0\n19 r 0\n20 s 0\n21 t 5\n22 u 0\n23 v 0\n24 x 0\n25 w 0\n26 y 0\n27 z 0\n\nTransform counts to indices\n0 0\n1 0\n2 a 2\n3 b 2\n4 c 3\n5 d 3\n6 e 3\n7 f 4\n8 g 5\n9 h 5\n10 i 6\n11 j 6\n12 k 6\n13 l 6\n14 m 6\n15 n 7\n16 o 8\n17 p 9\n18 q 9\n19 r 9\n20 s 9\n21 t 14\n22 u 14\n23 v 14\n24 x 14\n25 w 14\n26 y 14\n27 z 14\n\nDistribute and copy back\n0 all\n1 aid\n2 come\n3 for\n4 good\n5 is\n6 now\n7 of\n8 people\n9 the\n10 time\n11 to\n12 to\n13 the\n\nIndices at completion of distribute phase\n0 0\n1 2\n2 a 2\n3 b 3\n4 c 3\n5 d 3\n6 e 4\n7 f 5\n8 g 5\n9 h 6\n10 i 6\n11 j 6\n12 k 6\n13 l 6\n14 m 7\n15 n 8\n16 o 9\n17 p 9\n18 q 9\n19 r 9\n20 s 14\n21 t 14\n22 u 14\n23 v 14\n24 x 14\n25 w 14\n26 y 14\n27 z 14\n\nRecursively sort subarrays\nsort(a, 0, 1, 1);\nsort(a, 2, 1, 1);\nsort(a, 2, 2, 1);\nsort(a, 3, 2, 1);\nsort(a, 3, 2, 1);\nsort(a, 3, 3, 1);\nsort(a, 4, 4, 1);\nsort(a, 5, 4, 1);\nsort(a, 5, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 6, 1);\nsort(a, 7, 7, 1);\nsort(a, 8, 8, 1);\nsort(a, 9, 8, 1);\nsort(a, 9, 8, 1);\nsort(a, 9, 8, 1);\nsort(a, 9, 13, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\n\nSorted result\n0 aid\n1 all\n2 come\n3 for\n4 good\n5 is\n6 now\n7 of\n8 people\n9 the\n10 the\n11 time\n12 to\n13 to\n\nTrace of recursive calls for MSD string sort (no cutoff for small subarrays, subarrays of size 0 and 1 omitted)\n\ninput ____ ___ output \nnow all aid aid aid aid \nis aid all all all all\nthe come --- come come come\ntime for come for for for\nfor good for good good good\nall is good is is is\ngood now is now now now\npeople of now of of of\nto people of people people people\ncome the people --- --- the\nto time the the the the\nthe to time the the time\naid to to time --- to\nof the to to time to\n ---- the to to\n --- to\n", "support_files": [], "metadata": {"number": "5.1.5", "chapter": 5, "chapter_title": "Strings", "section": 5.1, "section_title": "String Sorts", "type": "Exercise", "code_execution": false}} {"question": "Give a trace for 3-way string quicksort for the keys\n now is the time for all good people to come to the aid of", "answer": "5.1.6\n\nTrace for 3-way string quicksort (same model as used in the book):\n\n ---- --- --- ---\n0 now is aid aid aid aid aid\n1 is aid come all --- --- all\n2 the come for --- all all come\n3 time for all for --- --- for\n4 for all good good come come good\n5 all good ---- come ---- ---- is\n6 good --- is ---- for for now\n7 people now --- is ---- ---- of\n8 to --- now --- good good people\n9 come to --- now ---- ---- the\n10 to people people --- is is the\n11 the to of of --- --- time\n12 aid the --- ------ now now to\n13 of time to people --- --- to\n of the ------ of of\n the time the ------ ------\n to time people people\n the the ------ ------\n --- ---- the the\n to the the\n to ---- ----\n ---- time time\n ---- ----\n to to\n to to\n -- --\n", "support_files": [], "metadata": {"number": "5.1.6", "chapter": 5, "chapter_title": "Strings", "section": 5.1, "section_title": "String Sorts", "type": "Exercise", "code_execution": false}} {"question": "Give the number of characters examined by MSD string sort and 3-way string quicksort for a file of N keys a, aa, aaa, aaaa, aaaaa, . . .", "answer": "5.1.8\n\nBoth MSD string sort and 3-way string quicksort examine all characters in the N keys.\nThat number is equal to 1 + 2 + ... + N = (N^2 + N) / 2 characters.\nMSD string sort, however, generates (R - 1) * N empty subarrays (an empty subarray for all digits in R other than 'a', in every pass) while 3-way string quicksort generates 2N empty subarrays (empty subarrays for digits smaller than 'a' and for digits higher than 'a', or empty subarrays for digits smaller than '-1' and for digits equal to '-1', in every pass).\n\nMSD string sort trace (no cutoff for small subarrays, subarrays of size 0 and 1 omitted):\n\ninput ----\na a a a a a a\naa aa ---- aa aa aa aa\naaa aaa aa ---- aaa aaa aaa\naaaa aaaa aaa aaa ---- aaaa aaaa\n... ... aaaa aaaa aaaa ---- ...\n ---- ... ... ... ...\n ---- ---- ---- ----\n\n3-way string quicksort trace:\n\ninput ----\na a a a a a a\naa aa ---- aa aa aa aa\naaa aaa aa ---- aaa aaa aaa\naaaa aaaa aaa aaa ---- aaaa aaaa\n... ... aaaa aaaa aaaa ---- ...\n ---- ... ... ... ...\n ---- ---- ---- ----\n", "support_files": [], "metadata": {"number": "5.1.8", "chapter": 5, "chapter_title": "Strings", "section": 5.1, "section_title": "String Sorts", "type": "Exercise", "code_execution": false}} {"question": "What is the total number of characters examined by 3-way string quicksort when sorting N fixed-length strings (all of length W), in the worst case?", "answer": "5.1.10\n\nThe total number of characters examined by 3-way string quicksort when sorting N fixed-length strings (all of length W) in the worst case is O(N * W * R).\n\nThis can be seen with a recurrence relation T(W).\n\nThe base case T(1) is when all the strings have length 1.\nAn example with R = 3 is { \"a\", \"b\", \"c\" }.\nIn the worst case they are in reverse order.\nFor example: { \"c\", \"b\", \"a\" }.\nIn this case we only remove one string from the list in each pass.\nIf we consider N = R^W (in this case, W = 1), the number of comparisons is equal to:\nCharacters examined = Sum[i=0..R] i\nCharacters examined = R * (R + 1) / 2\n\nTo build the worst case for strings of length 2 (T(2)), we take each string from T(1) and append it to the end of each character in R.\nSo for single character strings \"a\", \"b\", \"c\", with R = 3, the two character list is: \"aa\", \"ab\", \"ac\", \"ba\", \"bb\", \"bc\", \"ca\", \"cb\", \"cc\".\nThe list can then be split into R groups: one for each character in R that is a prefix to every string of length W - 1.\nDuring the partitioning phase all strings that start with \"a\" will be in the same partition and the algorithm will do the same process as in T(1) because removing the first character 'a' will lead to the same 1-length strings { \"c\", \"b\", \"a\" } as before.\nThe same thing happens for strings starting with \"b\" and \"c\".\nSo, for R = 3, the algorithm will check 3 * R + 2 * R + R characters in the first position of the strings (which is 3 + 2 + 1 characters times R groups).\nThen it will check the second characters in the strings in each of the R groups.\n\nFor T(W), where W > 2, the list will then again be split into R groups: one for each character in R that is a prefix to every string of length W - 2.\nQuicksort will then remove R strings from the list in each partition.\nIt will then check R * T(W - 1) more characters for each of those groups.\nThis gives the recurrence T(W) = (R^(W - 1) * Sum[i=0..R] R - i) + R * T(W - 1), which simplifies to:\nT(W) = R^(W + 1) + R^W + R * T(W - 1)\n -----------------\n 2\nSolving the recurrence gives us:\nT(W) = W * (R^W) * (R + 1)\n ---------------------\n 2\nSubstituting N = R^W:\nT(W) = W * N * (R + 1)\n -----------------\n 2\nWhich is O(N * W * R).\n\nThanks to dragon-dreamer (https://github.com/dragon-dreamer) for finding a more accurate worst case.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/153\nThanks to GenevaS (https://github.com/GenevaS) for finding a more accurate worst case.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/245\n", "support_files": [], "metadata": {"number": "5.1.10", "chapter": 5, "chapter_title": "Strings", "section": 5.1, "section_title": "String Sorts", "type": "Exercise", "code_execution": false}} {"question": "Hybrid sort. Investigate the idea of using standard MSD string sort for large arrays, in order to get the advantage of multiway partitioning, and 3-way string quicksort for smaller arrays, in order to avoid the negative effects of large numbers of empty bins.", "answer": "5.1.13 - Hybrid sort\n\nIdea: using standard MSD string sort for large arrays, in order to get the advantage of multiway partitioning, and 3-way string quicksort for smaller arrays, in order to avoid the negative effects of large numbers of empty bins.\n\nThis idea will work well for random strings because, in general, the higher the number of keys to be sorted, the higher the number of non-empty subarrays generated on each pass of MSD string sort. Such scenario would work well due to the advantage of having multiway partitioning.\nHowever, MSD string sort will still generate a large number of empty subarrays if there is a large number of equal keys (or a large number of keys with long common prefixes).\n\n3-way string quicksort will avoid the negative effects of large numbers of empty bins not only for smaller arrays, but also for large arrays, while also having the benefit of using less space than MSD string sort since it does not require space for frequency counts or for an auxiliary array. On the other hand, it envolves more data movement than MSD string sort when the number of nonempty subarrays is large because it has to do a series of 3-way partitions to get the effect of the multiway partition. This would not be a problem in the hybrid sort if there were many equal keys in smaller arrays, since 3-way string quicksort would be the algorithm of choice in such situation.\n\nOverall, hybrid sort would be a good choice for random strings. However, a version of hybrid sort that chooses between MSD string sort and 3-way string quicksort based on the percentage of equal keys (choosing MSD string sort if there is a low percentage of equal keys and choosing 3-way string quicksort if there is a high number of equal keys) would be more effective than a version that makes the choice based on the number of keys.\n", "support_files": [], "metadata": {"number": "5.1.13", "chapter": 5, "chapter_title": "Strings", "section": 5.1, "section_title": "String Sorts", "type": "Creative Problem", "code_execution": false}} {"question": "In-place key-indexed counting. Develop a version of key-indexed counting that uses only a constant amount of extra space. Prove that your version is stable or provide a counterexample.", "answer": "// Exercise17_InPlaceKeyIndexedCounting.java\npackage chapter5.section1;\n\nimport edu.princeton.cs.algs4.StdOut;\nimport util.ArrayUtil;\n\nimport java.util.StringJoiner;\n\n/**\n * Created by Rene Argento on 13/01/18.\n */\npublic class Exercise17_InPlaceKeyIndexedCounting {\n\n private class Element implements Comparable {\n String value;\n int originalIndex;\n\n Element(String value, int originalIndex) {\n this.value = value;\n this.originalIndex = originalIndex;\n }\n\n @Override\n public int compareTo(Element other) {\n return this.value.compareTo(other.value);\n }\n }\n\n public class LeastSignificantDigitInPlace {\n\n public void lsdSort(Element[] array, int stringsLength) {\n\n int alphabetSize = 256; // Extended ASCII characters\n\n for (int digit = stringsLength - 1; digit >= 0; digit--) {\n // Sort by key-indexed counting on digitTh char\n\n // Compute frequency counts\n int count[] = new int[alphabetSize + 1];\n int[] startIndex = new int[alphabetSize + 1];\n\n for (int i = 0; i < array.length; i++) {\n int digitIndex = array[i].value.charAt(digit);\n count[digitIndex + 1]++;\n startIndex[digitIndex + 1]++;\n }\n\n // Transform counts to indices\n for (int r = 0; r < alphabetSize; r++) {\n count[r + 1] += count[r];\n startIndex[r + 1] += startIndex[r];\n }\n\n // Distribute\n for (int i = 0; i < array.length; i++) {\n\n // Continue placing items in the correct place until array[i] is in the correct place\n while (true) {\n int digitIndex = array[i].value.charAt(digit);\n\n // Do not move items that are already in the correct place\n if (startIndex[digitIndex] <= i && i < count[digitIndex]) {\n break;\n }\n\n int newIndex = count[digitIndex]++;\n ArrayUtil.exchange(array, i, newIndex);\n }\n }\n }\n }\n }\n\n public class MostSignificantDigitInPlace {\n private int alphabetSize = 256; // Extended ASCII characters; radix\n private final int CUTOFF_FOR_SMALL_SUBARRAYS = 15;\n\n public void msdSort(Element[] array) {\n sort(array, 0, array.length - 1, 0);\n }\n\n private void sort(Element[] array, int low, int high, int digit) {\n // Do not use Insertion sort in this case to prove that the sort is not stable\n\n // Sort from array[low] to array[high], starting at the digitTh character\n// if (low + CUTOFF_FOR_SMALL_SUBARRAYS >= high) {\n// InsertionSort insertionSort = new InsertionSort();\n// insertionSort.sort(array, low, high, digit);\n// return;\n// }\n\n if (low > high) {\n return;\n }\n\n // Compute frequency counts\n int[] count = new int[alphabetSize + 2];\n int[] startIndex = new int[alphabetSize + 2];\n\n for (int i = low; i <= high; i++) {\n int digitIndex = charAt(array[i].value, digit) + 2;\n count[digitIndex]++;\n startIndex[digitIndex]++;\n }\n\n // Transform counts to indices\n for (int r = 0; r < alphabetSize + 1; r++) {\n count[r + 1] += count[r];\n startIndex[r + 1] += startIndex[r];\n }\n\n // Distribute\n for (int i = low; i <= high; i++) {\n\n // Continue placing items in the correct place until array[i] is in the correct place\n while (true) {\n int digitIndex = charAt(array[i].value, digit) + 1;\n\n // Do not move items that are already in the correct place\n if (startIndex[digitIndex] + low <= i && i < count[digitIndex] + low) {\n break;\n }\n\n int newIndex = count[digitIndex]++;\n ArrayUtil.exchange(array, i, newIndex + low);\n }\n }\n\n // Recursively sort for each character value\n for (int r = 0; r < alphabetSize; r++) {\n sort(array, low + count[r], low + count[r + 1] - 1,digit + 1);\n }\n }\n\n private int charAt(String string, int digit) {\n if (digit < string.length()) {\n return string.charAt(digit);\n } else {\n return -1;\n }\n }\n\n // Insertion sort for Strings whose first digit characters are equal\n public class InsertionSort {\n\n public void sort(Element[] array, int low, int high, int digit) {\n // Sort from array[low] to array[high], starting at the digitTh character\n for (int i = low; i <= high; i++) {\n for (int j = i; j > low && less(array[j].value, array[j - 1].value, digit); j--) {\n ArrayUtil.exchange(array, j, j - 1);\n }\n }\n }\n\n private boolean less(String string1, String string2, int digit) {\n for (int i = digit; i < Math.min(string1.length(), string2.length()); i++) {\n if (string1.charAt(i) < string2.charAt(i)) {\n return true;\n } else if (string1.charAt(i) > string2.charAt(i)) {\n return false;\n }\n }\n return string1.length() < string2.length();\n }\n }\n }\n\n public static void main(String[] args) {\n Exercise17_InPlaceKeyIndexedCounting inPlaceKeyIndexedCounting = new Exercise17_InPlaceKeyIndexedCounting();\n\n StdOut.println(\"In-place LSD tests\\n\");\n LeastSignificantDigitInPlace leastSignificantDigitInplace =\n inPlaceKeyIndexedCounting.new LeastSignificantDigitInPlace();\n\n Element[] array1 = new Element[13];\n array1[0] = inPlaceKeyIndexedCounting.new Element(\"4PGC938\", 0);\n array1[1] = inPlaceKeyIndexedCounting.new Element(\"2IYE230\", 1);\n array1[2] = inPlaceKeyIndexedCounting.new Element(\"3CIO720\", 2);\n array1[3] = inPlaceKeyIndexedCounting.new Element(\"1ICK750\", 3);\n array1[4] = inPlaceKeyIndexedCounting.new Element(\"1OHV845\", 4);\n array1[5] = inPlaceKeyIndexedCounting.new Element(\"4JZY524\", 5);\n array1[6] = inPlaceKeyIndexedCounting.new Element(\"1ICK750\", 6);\n array1[7] = inPlaceKeyIndexedCounting.new Element(\"3CIO720\", 7);\n array1[8] = inPlaceKeyIndexedCounting.new Element(\"1OHV845\", 8);\n array1[9] = inPlaceKeyIndexedCounting.new Element(\"1OHV845\", 9);\n array1[10] = inPlaceKeyIndexedCounting.new Element(\"2RLA629\", 10);\n array1[11] = inPlaceKeyIndexedCounting.new Element(\"2RLA629\", 11);\n array1[12] = inPlaceKeyIndexedCounting.new Element(\"3ATW723\", 12);\n\n int stringsLength1 = 7;\n leastSignificantDigitInplace.lsdSort(array1, stringsLength1);\n\n StringJoiner sortedArray1 = new StringJoiner(\" \");\n\n for (Element element : array1) {\n sortedArray1.add(element.value);\n }\n StdOut.println(\"Sorted array 1 with lost of stability\");\n StdOut.println(sortedArray1);\n StdOut.println(\"Expected if there was no lost of stability: \\n\" +\n \"1ICK750 1ICK750 1OHV845 1OHV845 1OHV845 2IYE230 2RLA629 2RLA629 3ATW723 3CIO720 3CIO720 \" +\n \"4JZY524 4PGC938\");\n\n Element[] array2 = new Element[3];\n array2[0] = inPlaceKeyIndexedCounting.new Element(\"CAA\", 0);\n array2[1] = inPlaceKeyIndexedCounting.new Element(\"ABB\", 1);\n array2[2] = inPlaceKeyIndexedCounting.new Element(\"ABB\", 2);\n\n int stringsLength2 = 3;\n leastSignificantDigitInplace.lsdSort(array2, stringsLength2);\n\n StringJoiner sortedArray2 = new StringJoiner(\"\\n\");\n\n for (Element element : array2) {\n sortedArray2.add(\"Element: \" + element.value + \" Original index: \" + element.originalIndex);\n }\n StdOut.println(\"\\nSorted array 2 with lost of stability\");\n StdOut.println(sortedArray2);\n\n leastSignificantDigitInplace.lsdSort(array2, 3);\n\n StdOut.println(\"\\nIn-place MSD tests\\n\");\n\n MostSignificantDigitInPlace mostSignificantDigitInplace =\n inPlaceKeyIndexedCounting.new MostSignificantDigitInPlace();\n\n Element[] array3 = new Element[18];\n array3[0] = inPlaceKeyIndexedCounting.new Element(\"Rene\", 0);\n array3[1] = inPlaceKeyIndexedCounting.new Element(\"Argento\", 1);\n array3[2] = inPlaceKeyIndexedCounting.new Element(\"Arg\", 2);\n array3[3] = inPlaceKeyIndexedCounting.new Element(\"Alg\", 3);\n array3[4] = inPlaceKeyIndexedCounting.new Element(\"Algorithms\", 4);\n array3[5] = inPlaceKeyIndexedCounting.new Element(\"LSD\", 5);\n array3[6] = inPlaceKeyIndexedCounting.new Element(\"MSD\", 6);\n array3[7] = inPlaceKeyIndexedCounting.new Element(\"3WayStringQuickSort\", 7);\n array3[8] = inPlaceKeyIndexedCounting.new Element(\"Dijkstra\", 8);\n array3[9] = inPlaceKeyIndexedCounting.new Element(\"Floyd\", 9);\n array3[10] = inPlaceKeyIndexedCounting.new Element(\"Warshall\", 10);\n array3[11] = inPlaceKeyIndexedCounting.new Element(\"Johnson\", 11);\n array3[12] = inPlaceKeyIndexedCounting.new Element(\"Sedgewick\", 12);\n array3[13] = inPlaceKeyIndexedCounting.new Element(\"Wayne\", 13);\n array3[14] = inPlaceKeyIndexedCounting.new Element(\"Bellman\", 14);\n array3[15] = inPlaceKeyIndexedCounting.new Element(\"Ford\", 15);\n array3[16] = inPlaceKeyIndexedCounting.new Element(\"BFS\", 16);\n array3[17] = inPlaceKeyIndexedCounting.new Element(\"DFS\", 17);\n\n mostSignificantDigitInplace.msdSort(array3);\n\n StringJoiner sortedArray3 = new StringJoiner(\" \");\n\n for (Element element : array3) {\n sortedArray3.add(element.value);\n }\n StdOut.println(\"Sorted array 3\");\n StdOut.println(sortedArray3);\n StdOut.println(\"Expected: \\n3WayStringQuickSort Alg Algorithms Arg Argento BFS Bellman DFS Dijkstra Floyd Ford \" +\n \"Johnson LSD MSD Rene Sedgewick Warshall Wayne\\n\");\n\n Element[] array4 = new Element[3];\n array4[0] = inPlaceKeyIndexedCounting.new Element(\"CAA\", 0);\n array4[1] = inPlaceKeyIndexedCounting.new Element(\"ABB\", 1);\n array4[2] = inPlaceKeyIndexedCounting.new Element(\"ABB\", 2);\n\n mostSignificantDigitInplace.msdSort(array4);\n\n StringJoiner sortedArray4 = new StringJoiner(\"\\n\");\n\n for (Element element : array4) {\n sortedArray4.add(\"Element: \" + element.value + \" Original index: \" + element.originalIndex);\n }\n StdOut.println(\"Sorted array 4 with lost of stability\");\n StdOut.println(sortedArray4);\n }\n}\n\nAdditional notes/results:\n5.1.17 - In-place key-indexed counting\n\nLSD and MSD sorts that use only a constant amount of extra space are not stable.\n\nCounterexample for LSD sort:\n\nThe array [\"4PGC938\", \"2IYE230\", \"3CIO720\", \"1ICK750\", \"1OHV845\", \"4JZY524\", \"1ICK750\", \"3CIO720\", \"1OHV845\", \"1OHV845\", \"2RLA629\", \"2RLA629\", \"3ATW723\"] after being sorted by in-place LSD becomes:\n[\"1OHV845\", \"1OHV845\", \"1OHV845\", \"1ICK750\", \"1ICK750\", \"2RLA629\", \"2IYE230\", \"2RLA629\", \"3ATW723\", \"3CIO720\", \"3CIO720\", \"4PGC938\", \"4JZY524\"]\nIf it were sorted by non-in-place LSD the output would be:\n[\"1ICK750\", \"1ICK750\", \"1OHV845\", \"1OHV845\", \"1OHV845\", \"2IYE230\", \"2RLA629\", \"2RLA629\", \"3ATW723\", \"3CIO720\", \"3CIO720\", \"4JZY524\", \"4PGC938\"]\n\nCounterexample for both LSD and MSD sorts:\n\nThe array [\"CAA\" (index 0), \"ABB\" (index 1), \"ABB\" (index 2)] after being sorted by either in-place LSD or in-place MSD becomes:\n[\"ABB\" (original index 2), \"ABB\" (original index 1), \"CAA\" (original index 0)]\nIf it were sorted by non-in-place LSD or MSD the output would be:\n[\"ABB\" (original index 1), \"ABB\" (original index 2), \"CAA\" (original index 0)]", "support_files": [], "metadata": {"number": "5.1.17", "chapter": 5, "chapter_title": "Strings", "section": 5.1, "section_title": "String Sorts", "type": "Creative Problem", "code_execution": false}} {"question": "Timings. Compare the running times of MSD string sort and 3-way string quicksort, using various key generators. For fixed-length keys, include LSD string sort.", "answer": "5.1.22 - Timings\n\nRunning 10 experiments with 1000000 strings for random decimal keys (with fixed-length of 10 characters), random CA license plates, random fixed-length words (with fixed-length of 10 characters) and random variable length items (with given values 'A' and 'B'). The cutoff for small subarrays used in Most-Significant-Digit sort was equal to 15.\n\n Random string type | Sort type | Average time spent\n Decimal keys Least-Significant-Digit 2.30\n Decimal keys Most-Significant-Digit 0.45\n Decimal keys 3-way string quicksort 0.32\n CA license plates Least-Significant-Digit 1.48\n CA license plates Most-Significant-Digit 0.41\n CA license plates 3-way string quicksort 0.33\n Fixed length words Least-Significant-Digit 2.52\n Fixed length words Most-Significant-Digit 0.28\n Fixed length words 3-way string quicksort 0.35\n Variable length items Most-Significant-Digit 1.80\n Variable length items 3-way string quicksort 0.55\n\nThe experiment results show that for all random string types, LSD sort had the worst results.\nFor random decimal keys, random CA license plates and random variable length items 3-way string quicksort had the best results.\nFor random fixed-length words, MSD had the best running time.\nHaving to always scan all characters in all keys may explain why LSD sort had the slowest running times when sorting all random string types. 3-way string quicksort may have had good results because it does not create a high number of empty subarrays, as MSD sort does, and because it can handle well keys with long common prefixes (which are likely to happen in random decimal keys, random CA license plates and random variable length items).\nRandom fixed-length words are less likely to have long common prefixes (because all their characters are in the range [40, 125]), which may explain why MSD sort had better results than both LSD sort and 3-way string quicksort during their sort.\n", "support_files": [], "metadata": {"number": "5.1.22", "chapter": 5, "chapter_title": "Strings", "section": 5.1, "section_title": "String Sorts", "type": "Experiment", "code_execution": false}} {"question": "Array accesses. Compare the number of array accesses used by MSD string sort and 3-way string sort, using various key generators. For fixed-length keys, include LSD string sort.", "answer": "5.1.23 - Array accesses\n\nRunning 10 experiments with 1000000 strings for random decimal keys (with fixed-length of 10 characters), random CA license plates, random fixed-length words (with fixed-length of 10 characters) and random variable length items (with given values 'A' and 'B'). The cutoff for small subarrays used in Most-Significant-Digit sort was equal to 15.\n\n Random string type | Sort type | Number of array accesses\n Decimal keys Least-Significant-Digit 40000000\n Decimal keys Most-Significant-Digit 35443947\n Decimal keys 3-way string quicksort 78124405\n CA license plates Least-Significant-Digit 28000000\n CA license plates Most-Significant-Digit 25703588\n CA license plates 3-way string quicksort 82889002\n Fixed length words Least-Significant-Digit 40000000\n Fixed length words Most-Significant-Digit 14841196\n Fixed length words 3-way string quicksort 95310075\n Variable length items Most-Significant-Digit 72121457\n Variable length items 3-way string quicksort 97523400\n\nThe experiment results show that for all random string types, 3-way string quicksort accessed the array more times than LSD and MSD sort; LSD sort accessed the array more times than MSD sort; and MSD sort had the lowest number of array accesses.\nA possible explanation for these results is the fact that 3-way string quicksort accesses the array 4 times for each exchange operation, which leads to more array accesses than both LSD and MSD sorts, that do not make inplace exchanges.\nLSD sort will always access the array 4 * N * W times, where N is the number of strings and W is the length of the strings (which is equivalent to 4 array accesses for each character in the keys) and MSD sort will only access the array while the strings have common prefixes, which explains why MSD sort has the lowest number of array accesses of all sort types.\n", "support_files": [], "metadata": {"number": "5.1.23", "chapter": 5, "chapter_title": "Strings", "section": 5.1, "section_title": "String Sorts", "type": "Experiment", "code_execution": false}} {"question": "Rightmost character accessed. Compare the position of the rightmost character accessed for MSD string sort and 3-way string quicksort, using various key generators.", "answer": "5.1.24 - Rightmost character accessed\n\nRunning 1 experiment with 1000000 strings for random decimal keys (with fixed-length of 10 characters), random CA license plates, random fixed-length words (with fixed-length of 10 characters) and random variable length items (with given values 'A' and 'B'). The cutoff for small subarrays used in Most-Significant-Digit sort was equal to 15.\n\n Random string type | Sort type | Rightmost character accessed\n Decimal keys Most-Significant-Digit 9\n Decimal keys 3-way string quicksort 9\n CA license plates Most-Significant-Digit 6\n CA license plates 3-way string quicksort 6\n Fixed length words Most-Significant-Digit 5\n Fixed length words 3-way string quicksort 5\n Variable length items Most-Significant-Digit 20\n Variable length items 3-way string quicksort 20\n\nIn all experiments the rightmost character position accessed in MSD sort and in 3-way string quicksort was the same, which shows that both algorithms scan the same characters.\n", "support_files": [], "metadata": {"number": "5.1.24", "chapter": 5, "chapter_title": "Strings", "section": 5.1, "section_title": "String Sorts", "type": "Experiment", "code_execution": false}} {"question": "Draw the TST that results when the keys\n no is th ti fo al go pe to co to th ai of th pa\nare inserted in that order into an initially empty TST.", "answer": "5.2.2\n\nTernary search trie after insertion of keys:\nno is th ti fo al go pe to co to th ai of th pa\n\nEmpty TST:\n\nInsert: no\n n\n/|\\\n o\n/|\\\n\nInsert: is\n n\n / | \\\n i o\n /|\\ /|\\\n s\n /|\\\n\nInsert: th\n n\n / | \\\n i o t\n /|\\ /|\\ /|\\\n s h\n /|\\ /|\\\n\nInsert: ti\n n\n / | \\\n i o t\n /|\\ /|\\ /|\\\n s h\n /|\\ /|\\\n i\n /|\\\n\nInsert: fo\n n\n / | \\\n i o t\n / | \\ /|\\ /|\\\n f s h\n/|\\ /|\\ /|\\\n o i\n/|\\ /|\\\n\nInsert: al\n n\n / | \\\n i o t\n / | \\ /|\\ /|\\\n f s h\n / |\\ /|\\ /|\\\n a o i\n/|\\ /|\\ /|\\\n l\n/|\\\n\nInsert: go\n n\n / | \\\n i o t\n / | \\ /|\\ /|\\\n f s h\n / | \\ /|\\ /|\\\n a o g i\n/|\\ /|\\ /|\\ /|\\\n l o\n/|\\ /|\\\n\nInsert: pe\n n\n / | \\\n i o t\n / | \\ /|\\ / | \\\n f s p h\n / | \\ /|\\ /|\\ /|\\\n a o g e i\n/|\\ /|\\ /|\\ /|\\ /|\\\n l o\n/|\\ /|\\\n\nInsert: to\n n\n / | \\\n i o t\n / | \\ /|\\ / | \\\n f s p h\n / | \\ /|\\ /|\\ /|\\\n a o g e i\n/|\\ /|\\ /|\\ /|\\ /|\\\n l o o\n/|\\ /|\\ /|\\\n\nInsert: co\n n\n / | \\\n i o t\n / | \\ /|\\ / | \\\n f s p h\n / | \\ /|\\ /|\\ /|\\\n a o g e i\n/| \\ /|\\ /|\\ /|\\ /|\\\n l c o o\n/|\\ /|\\ /|\\ /|\\\n o\n /|\\\n\nInsert: to\n n\n / | \\\n i o t\n / | \\ /|\\ / | \\\n f s p h\n / | \\ /|\\ /|\\ /|\\\n a o g e i\n/| \\ /|\\ /|\\ /|\\ /|\\\n l c o o\n/|\\ /|\\ /|\\ /|\\\n o\n /|\\\n\nInsert: th\n n\n / | \\\n i o t\n / | \\ /|\\ / | \\\n f s p h\n / | \\ /|\\ /|\\ /|\\\n a o g e i\n/| \\ /|\\ /|\\ /|\\ /|\\\n l c o o\n/|\\ /|\\ /|\\ /|\\\n o\n /|\\\n\nInsert: ai\n n\n / | \\\n i o t\n / | \\ /|\\ / | \\\n f s p h\n / | \\ /|\\ /|\\ /|\\\n a o g e i\n /| \\ /|\\ /|\\ /|\\ /|\\\n l c o o\n /|\\ /|\\ /|\\ /|\\\n i o\n/|\\ /|\\\n\nInsert: of\n n\n / | \\\n i o t\n / | \\ /|\\ / | \\\n f s p h\n / | \\ /|\\ / |\\ /|\\\n a o g o e i\n /| \\ /|\\ /|\\ /|\\ /|\\ /|\\\n l c o f o\n /|\\ /|\\ /|\\ /|\\ /|\\\n i o\n/|\\ /|\\\n\nInsert: th\n n\n / | \\\n i o t\n / | \\ /|\\ / | \\\n f s p h\n / | \\ /|\\ / |\\ /|\\\n a o g o e i\n /| \\ /|\\ /|\\ /|\\ /|\\ /|\\\n l c o f o\n /|\\ /|\\ /|\\ /|\\ /|\\\n i o\n/|\\ /|\\\n\nInsert: pa\n n\n / | \\\n i o t\n / | \\ /|\\ / | \\\n f s p h\n / | \\ /|\\ / |\\ /|\\\n a o g o e i\n /| \\ /|\\ /|\\ /|\\ /|\\ /|\\\n l c o f a o\n /|\\ /|\\ /|\\ /|\\ /|\\ /|\\\n i o\n/|\\ /|\\\n", "support_files": [], "metadata": {"number": "5.2.2", "chapter": 5, "chapter_title": "Strings", "section": 5.2, "section_title": "Tries", "type": "Exercise", "code_execution": false}} {"question": "Draw the R-way trie that results when the keys\n now is the time for all good people to come to the aid of\nare inserted in that order into an initially empty trie (do not draw null links).", "answer": "5.2.3\n\nR-way trie after insertion of keys:\nnow is the time for all good people to come to the aid of\n\nEmpty trie:\nO\n\nInsert: now\nO\n|\nn\n|\no\n|\nw\n\nInsert: is\n O\n / \\\ni n\n| |\ns o\n |\n w\n\nInsert: the\n O\n / | \\\ni n t\n| | |\ns o h\n | |\n w e\n\nInsert: time\n O\n / | \\\ni n t\n| | /|\ns o h i\n | | |\n w e m\n |\n e\n\nInsert: for\n O\n / / | \\\n f i n t\n | | | /|\n o s o h i\n | | | |\n r w e m\n |\n e\n\nInsert: all\n O\n / / / | \\\n a f i n t\n | | | | /|\n l o s o h i\n | | | | |\n l r w e m\n |\n e\n\nInsert: good\n O\n / / / / | \\\n a f g i n t\n | | | | | /|\n l o o s o h i\n | | | | | |\n l r o w e m\n | |\n d e\n\nInsert: people\n O\n / / / / | \\ \\\n a f g i n p t\n | | | | | | /|\n l o o s o e h i\n | | | | | | |\n l r o w o e m\n | | |\n d p e\n |\n l\n |\n e\n\nInsert: to\n O\n / / / / | \\ \\\n a f g i n p t\n | | | | | | /|\\\n l o o s o e h i o\n | | | | | | |\n l r o w o e m\n | | |\n d p e\n |\n l\n |\n e\n\nInsert: come\n O\n / / / / / | \\ \\\n a c f g i n p t\n | | | | | | | /|\\\n l o o o s o e h i o\n | | | | | | | |\n l m r o w o e m\n | | | |\n e d p e\n |\n l\n |\n e\n\nInsert: to\n O\n / / / / / | \\ \\\n a c f g i n p t\n | | | | | | | /|\\\n l o o o s o e h i o\n | | | | | | | |\n l m r o w o e m\n | | | |\n e d p e\n |\n l\n |\n e\n\nInsert: the\n O\n / / / / / | \\ \\\n a c f g i n p t\n | | | | | | | /|\\\n l o o o s o e h i o\n | | | | | | | |\n l m r o w o e m\n | | | |\n e d p e\n |\n l\n |\n e\n\nInsert: aid\n O\n / / / / / | \\ \\\n a c f g i n p t\n /| | | | | | | /|\\\ni l o o o s o e h i o\n| | | | | | | | |\nd l m r o w o e m\n | | | |\n e d p e\n |\n l\n |\n e\n\nInsert: of\n O\n / / / / / | \\ \\ \\\n a c f g i n o p t\n /| | | | | | | | /|\\\ni l o o o s o f e h i o\n| | | | | | | | |\nd l m r o w o e m\n | | | |\n e d p e\n |\n l\n |\n e\n", "support_files": [], "metadata": {"number": "5.2.3", "chapter": 5, "chapter_title": "Strings", "section": 5.2, "section_title": "Tries", "type": "Exercise", "code_execution": false}} {"question": "Draw the TST that results when the keys\n now is the time for all good people to come to the aid of\nare inserted in that order into an initially empty TST.", "answer": "5.2.4\n\nTernary search trie after insertion of keys:\nnow is the time for all good people to come to the aid of\n\nEmpty TST:\n\nInsert: now\n n\n/|\\\n o\n/|\\\n w\n/|\\\n\nInsert: is\n n\n / | \\\n i o\n /|\\ /|\\\n s w\n /|\\ /|\\\n\nInsert: the\n n\n / | \\\n i o t\n /|\\ /|\\ /|\\\n s w h\n /|\\ /|\\ /|\\\n e\n /|\\\n\nInsert: time\n n\n / | \\\n i o t\n /|\\ /|\\ /|\\\n s w h\n /|\\ /|\\ / | \\\n e i\n /|\\ /|\\\n m\n /|\\\n e\n /|\\\n\nInsert: for\n n\n / | \\\n i o t\n / |\\ /|\\ /|\\\n f s w h\n/|\\ /|\\ /|\\ / | \\\n o e i\n/|\\ /|\\ /|\\\n r m\n/|\\ /|\\\n e\n /|\\\n\nInsert: all\n n\n / | \\\n i o t\n / |\\ /|\\ /|\\\n f s w h\n / |\\ /|\\ /|\\ / | \\\n a o e i\n/|\\ /|\\ /|\\ /|\\\n l r m\n/|\\ /|\\ /|\\\n l e\n/|\\ /|\\\n\nInsert: good\n n\n / | \\\n i o t\n / |\\ /|\\ /|\\\n f s w h\n / | \\ /|\\ /|\\ / | \\\n a o g e i\n/|\\ /|\\ /|\\ /|\\ /|\\\n l r o m\n/|\\ /|\\ /|\\ /|\\\n l o e\n/|\\ /|\\ /|\\\n d\n /|\\\n\nInsert: people\n n\n / | \\\n i o t\n / |\\ /|\\ / |\\\n f s w p h\n / | \\ /|\\ /|\\ /|\\ / | \\\n a o g e e i\n/|\\ /|\\ /|\\ /|\\ /|\\ /|\\\n l r o o m\n/|\\ /|\\ /|\\ /|\\ /|\\\n l o p e\n/|\\ /|\\ /|\\ /|\\\n d l\n /|\\ /|\\\n e\n /|\\\n\nInsert: to\n n\n / | \\\n i o t\n / |\\ /|\\ / |\\\n f s w p h\n / | \\ /|\\ /|\\ /|\\ / | \\\n a o g e e i\n/|\\ /|\\ /|\\ /|\\ /|\\ / | \\\n l r o o m o\n/|\\ /|\\ /|\\ /|\\ /|\\ /|\\\n l o p e\n/|\\ /|\\ /|\\ /|\\\n d l\n /|\\ /|\\\n e\n /|\\\n\nInsert: come\n n\n / | \\\n i o t\n / |\\ /|\\ / |\\\n f s w p h\n / | \\ /|\\ /|\\ /|\\ / | \\\n a o g e e i\n/| \\ /|\\ /|\\ /|\\ /|\\ / | \\\n l c r o o m o\n/|\\ | /|\\ /|\\ /|\\ /|\\ /|\\\n l o o p e\n/|\\ /|\\ /|\\ /|\\ /|\\\n m d l\n /|\\ /|\\ /|\\\n e e\n /|\\ /|\\\n\nInsert: to\n n\n / | \\\n i o t\n / |\\ /|\\ / |\\\n f s w p h\n / | \\ /|\\ /|\\ /|\\ / | \\\n a o g e e i\n/| \\ /|\\ /|\\ /|\\ /|\\ / | \\\n l c r o o m o\n/|\\ | /|\\ /|\\ /|\\ /|\\ /|\\\n l o o p e\n/|\\ /|\\ /|\\ /|\\ /|\\\n m d l\n /|\\ /|\\ /|\\\n e e\n /|\\ /|\\\n\nInsert: the\n n\n / | \\\n i o t\n / |\\ /|\\ / |\\\n f s w p h\n / | \\ /|\\ /|\\ /|\\ / | \\\n a o g e e i\n/| \\ /|\\ /|\\ /|\\ /|\\ / | \\\n l c r o o m o\n/|\\ | /|\\ /|\\ /|\\ /|\\ /|\\\n l o o p e\n/|\\ /|\\ /|\\ /|\\ /|\\\n m d l\n /|\\ /|\\ /|\\\n e e\n /|\\ /|\\\n\nInsert: aid\n n\n / | \\\n i o t\n / |\\ /|\\ / |\\\n f s w p h\n / | \\ /|\\ /|\\ /|\\ / | \\\n a o g e e i\n | \\ /|\\ /|\\ /|\\ /|\\ / | \\\n l c r o o m o\n /|\\ | /|\\ /|\\ /|\\ /|\\ /|\\\n i l o o p e\n/|\\ /|\\ /|\\ /|\\ /|\\ /|\\\n d m d l\n/|\\ /|\\ /|\\ /|\\\n e e\n /|\\ /|\\\n\n\nInsert: of\n n\n / | \\\n i o t\n / |\\ /|\\ / |\\\n f s w p h\n / | \\ /|\\ /|\\ / |\\ / | \\\n a o g o e e i\n | \\ /|\\ /|\\ /|\\ /|\\ /|\\ / | \\\n l c r o f o m o\n /|\\ | /|\\ /|\\ /|\\ /|\\ /|\\ /|\\\n i l o o p e\n/|\\ /|\\ /|\\ /|\\ /|\\ /|\\\n d m d l\n/|\\ /|\\ /|\\ /|\\\n e e\n /|\\ /|\\\n", "support_files": [], "metadata": {"number": "5.2.4", "chapter": 5, "chapter_title": "Strings", "section": 5.2, "section_title": "Tries", "type": "Exercise", "code_execution": false}} {"question": "Develop nonrecursive versions of TrieST and TST.", "answer": "package chapter5.section2;\n\nimport chapter1.section3.Queue;\nimport chapter1.section3.Stack;\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.StringJoiner;\n\n/**\n * Created by Rene Argento on 26/01/18.\n */\n// Thanks to joe63 (https://github.com/joe63) for reporting a bug on the longestPrefixOf() method.\n// https://github.com/reneargento/algorithms-sedgewick-wayne/issues/279\npublic class Exercise5 {\n\n @SuppressWarnings(\"unchecked\")\n public static class TrieIterative {\n private static final int R = 256; // radix\n private Node root = new Node();\n\n private static class Node {\n private Object value;\n private Node[] next = new Node[R];\n private int size;\n }\n\n private class NodeWithInformation {\n private Node node;\n private StringBuilder prefix;\n private int digit;\n private boolean mustBeEqualDigit;\n\n NodeWithInformation(Node node, StringBuilder prefix) {\n this.node = node;\n this.prefix = prefix;\n }\n\n NodeWithInformation(Node node, StringBuilder prefix, int digit, boolean mustBeEqualDigit) {\n this.node = node;\n this.prefix = prefix;\n this.digit = digit;\n this.mustBeEqualDigit = mustBeEqualDigit;\n }\n }\n\n public int size() {\n return size(root);\n }\n\n private int size(Node node) {\n if (node == null) {\n return 0;\n }\n return node.size;\n }\n\n public boolean isEmpty() {\n return size() == 0;\n }\n\n public boolean contains(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n return get(key) != null;\n }\n\n public Value get(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n if (key.length() == 0) {\n throw new IllegalArgumentException(\"Key must have a positive length\");\n }\n\n Node node = getNode(key);\n if (node == null) {\n return null;\n }\n return (Value) node.value;\n }\n\n private Node getNode(String key) {\n Node currentNode = root;\n int digit = 0;\n\n while (currentNode != null) {\n if (digit == key.length()) {\n break;\n }\n char nextChar = key.charAt(digit); // Use digitTh key char to identify subtrie.\n currentNode = currentNode.next[nextChar];\n digit++;\n }\n return currentNode;\n }\n\n public void put(String key, Value value) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n if (value == null) {\n delete(key);\n return;\n }\n\n boolean isNewKey = !contains(key);\n Node parent = root;\n Node currentNode = root;\n int digit = 0;\n char nextChar = key.charAt(0);\n\n while (digit <= key.length()) {\n if (currentNode == null) {\n currentNode = new Node();\n parent.next[nextChar] = currentNode;\n }\n parent = currentNode;\n\n if (isNewKey) {\n currentNode.size = currentNode.size + 1;\n }\n if (digit == key.length()) {\n currentNode.value = value;\n return;\n }\n nextChar = key.charAt(digit); // Use digitTh key char to identify subtrie.\n currentNode = currentNode.next[nextChar];\n digit++;\n }\n }\n\n public void delete(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n if (!contains(key)) {\n return;\n }\n Node parent;\n Node currentNode = root;\n int digit = 0;\n\n while (currentNode != null) {\n parent = currentNode;\n currentNode.size = currentNode.size - 1;\n\n if (digit == key.length()) {\n currentNode.value = null;\n return;\n } else {\n char nextChar = key.charAt(digit);\n currentNode = currentNode.next[nextChar];\n\n if (currentNode != null && currentNode.size == 1) {\n parent.next[nextChar] = null;\n return;\n }\n digit++;\n }\n }\n }\n\n public Iterable keys() {\n return keysWithPrefix(\"\");\n }\n\n public Iterable keysWithPrefix(String prefix) {\n if (prefix == null) {\n throw new IllegalArgumentException(\"Prefix cannot be null\");\n }\n\n Queue keysWithPrefix = new Queue<>();\n Node nodeWithPrefix = getNode(prefix);\n\n if (nodeWithPrefix == null) {\n return keysWithPrefix;\n }\n\n Stack stack = new Stack<>();\n stack.push(new NodeWithInformation(nodeWithPrefix, new StringBuilder(prefix)));\n\n while (!stack.isEmpty()) {\n NodeWithInformation currentNodeWithInformation = stack.pop();\n Node currentNode = currentNodeWithInformation.node;\n StringBuilder currentPrefix = currentNodeWithInformation.prefix;\n\n if (currentNode.value != null) {\n keysWithPrefix.enqueue(currentPrefix.toString());\n }\n\n // Since we are using a stack to iterate over all keys, start with the last letters in order to get\n // keys in alphabetical order\n for (char nextChar = R - 1; true; nextChar--) {\n if (currentNode.next[nextChar] != null) {\n stack.push(new NodeWithInformation(currentNode.next[nextChar],\n new StringBuilder(currentPrefix).append(nextChar)));\n }\n // nextChar value never becomes less than zero in the for loop, so we need this extra validation\n if (nextChar == 0) {\n break;\n }\n }\n }\n return keysWithPrefix;\n }\n\n public Iterable keysThatMatch(String pattern) {\n if (pattern == null) {\n throw new IllegalArgumentException(\"Pattern cannot be null\");\n }\n Queue keysThatMatch = new Queue<>();\n\n Stack stack = new Stack<>();\n stack.push(new NodeWithInformation(root, new StringBuilder()));\n\n while (!stack.isEmpty()) {\n NodeWithInformation currentNodeWithInformation = stack.pop();\n Node currentNode = currentNodeWithInformation.node;\n StringBuilder currentPrefix = currentNodeWithInformation.prefix;\n\n int digit = currentPrefix.length();\n if (digit == pattern.length() && currentNode.value != null) {\n keysThatMatch.enqueue(currentPrefix.toString());\n }\n\n if (digit == pattern.length()) {\n continue;\n }\n char nextCharInPattern = pattern.charAt(digit);\n\n for (char nextChar = R - 1; true; nextChar--) {\n if (nextCharInPattern == '.' || nextCharInPattern == nextChar) {\n if (currentNode.next[nextChar] != null) {\n stack.push(new NodeWithInformation(currentNode.next[nextChar],\n new StringBuilder(currentPrefix).append(nextChar)));\n }\n }\n\n // nextChar value never becomes less than zero in the for loop, so we need this extra validation\n if (nextChar == 0) {\n break;\n }\n }\n }\n return keysThatMatch;\n }\n\n public String longestPrefixOf(String query) {\n if (query == null) {\n throw new IllegalArgumentException(\"Query cannot be null\");\n }\n\n if (isEmpty()) {\n return null;\n }\n\n Node currentNode = root;\n int length = 0;\n int digit = 0;\n\n while (currentNode != null) {\n if (currentNode.value != null) {\n length = digit;\n }\n\n if (digit == query.length()) {\n break;\n }\n char nextChar = query.charAt(digit);\n\n if (currentNode.next[nextChar] != null) {\n currentNode = currentNode.next[nextChar];\n digit++;\n } else {\n break;\n }\n }\n return query.substring(0, length);\n }\n\n // Ordered methods\n\n // Returns the highest key in the symbol table smaller than or equal to key.\n public String floor(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n if (isEmpty()) {\n return null;\n }\n\n String lastKeyFound = null;\n\n Stack stack = new Stack<>();\n stack.push(new NodeWithInformation(root, new StringBuilder()));\n\n while (!stack.isEmpty()) {\n NodeWithInformation currentNodeWithInformation = stack.pop();\n Node currentNode = currentNodeWithInformation.node;\n StringBuilder currentPrefix = currentNodeWithInformation.prefix;\n int currentDigit = currentNodeWithInformation.digit;\n\n if (currentDigit == 0) {\n currentNodeWithInformation.mustBeEqualDigit = true;\n }\n boolean mustBeEqualDigit = currentNodeWithInformation.mustBeEqualDigit;\n\n // Highest keys will be on the top of the stack\n if (currentNode.value != null) {\n String currentKey = currentPrefix.toString();\n\n if (lastKeyFound != null && currentKey.compareTo(lastKeyFound) < 0) {\n return lastKeyFound;\n }\n lastKeyFound = currentPrefix.toString();\n }\n\n char rightChar;\n\n if (mustBeEqualDigit && currentDigit < key.length()) {\n rightChar = key.charAt(currentDigit);\n } else {\n rightChar = R - 1;\n }\n\n for (char nextChar = 0; nextChar <= rightChar; nextChar++) {\n if (currentNode.next[nextChar] != null) {\n if (nextChar < rightChar) {\n mustBeEqualDigit = false;\n } else if (currentNodeWithInformation.mustBeEqualDigit && nextChar == rightChar) {\n mustBeEqualDigit = true;\n }\n\n String currentKey = currentPrefix + String.valueOf(nextChar);\n if (currentKey.compareTo(key) > 0) {\n continue;\n }\n stack.push(new NodeWithInformation(currentNode.next[nextChar],\n new StringBuilder(currentPrefix).append(nextChar), currentDigit + 1, mustBeEqualDigit));\n }\n }\n }\n return lastKeyFound;\n }\n\n // Returns the smallest key in the symbol table greater than or equal to key.\n public String ceiling(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n if (isEmpty()) {\n return null;\n }\n Stack stack = new Stack<>();\n stack.push(new NodeWithInformation(root, new StringBuilder()));\n\n while (!stack.isEmpty()) {\n NodeWithInformation currentNodeWithInformation = stack.pop();\n Node currentNode = currentNodeWithInformation.node;\n StringBuilder currentPrefix = currentNodeWithInformation.prefix;\n int currentDigit = currentNodeWithInformation.digit;\n\n if (currentDigit == 0) {\n currentNodeWithInformation.mustBeEqualDigit = true;\n }\n\n boolean mustBeEqualDigit = currentNodeWithInformation.mustBeEqualDigit;\n\n // Lowest keys will be on the top of the stack\n if (currentNode.value != null && currentPrefix.toString().compareTo(key) >= 0) {\n return currentPrefix.toString();\n }\n char leftChar;\n\n if (mustBeEqualDigit && currentDigit < key.length()) {\n leftChar = key.charAt(currentDigit);\n } else {\n leftChar = 0;\n }\n\n for (char nextChar = R - 1; true; nextChar--) {\n if (currentNode.next[nextChar] != null) {\n if (nextChar > leftChar) {\n mustBeEqualDigit = false;\n } else if (currentNodeWithInformation.mustBeEqualDigit && nextChar == leftChar) {\n mustBeEqualDigit = true;\n }\n stack.push(new NodeWithInformation(currentNode.next[nextChar],\n new StringBuilder(currentPrefix).append(nextChar), currentDigit + 1, mustBeEqualDigit));\n }\n\n if (nextChar == leftChar) {\n break;\n }\n }\n }\n return null;\n }\n\n public String select(int index) {\n if (index < 0 || index >= size()) {\n throw new IllegalArgumentException(\"Index cannot be negative and must be lower than trie size\");\n }\n Node currentNode = root;\n StringBuilder prefix = new StringBuilder();\n\n while (currentNode != null) {\n if (currentNode.value != null) {\n index--;\n\n // Found the key with the target index\n if (index == -1) {\n return prefix.toString();\n }\n }\n\n for (char nextChar = 0; nextChar < R; nextChar++) {\n if (currentNode.next[nextChar] != null) {\n\n if (index - size(currentNode.next[nextChar]) < 0) {\n currentNode = currentNode.next[nextChar];\n prefix.append(nextChar);\n break;\n } else {\n index = index - size(currentNode.next[nextChar]);\n }\n }\n }\n }\n return null;\n }\n\n public int rank(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n Node currentNode = root;\n int digit = 0;\n int size = 0;\n\n while (currentNode != null) {\n if (digit == key.length()) {\n return size;\n }\n\n // If a prefix key was found, add 1 to rank\n if (currentNode.value != null) {\n if (digit < key.length()) {\n size++;\n } else {\n return size;\n }\n }\n char currentChar = key.charAt(digit);\n\n for (char nextChar = 0; nextChar < currentChar; nextChar++) {\n size += size(currentNode.next[nextChar]);\n }\n\n currentNode = currentNode.next[currentChar];\n digit++;\n }\n return size;\n }\n\n public String min() {\n if (isEmpty()) {\n return null;\n }\n\n Node currentNode = root;\n StringBuilder prefix = new StringBuilder();\n boolean hasNextCharacter = true;\n\n while (hasNextCharacter) {\n hasNextCharacter = false;\n\n for (char nextChar = 0; nextChar < R; nextChar++) {\n if (currentNode.next[nextChar] != null) {\n currentNode = currentNode.next[nextChar];\n prefix.append(nextChar);\n\n if (currentNode.value != null) {\n return prefix.toString();\n }\n hasNextCharacter = true;\n break;\n }\n }\n }\n return null;\n }\n\n public String max() {\n if (isEmpty()) {\n return null;\n }\n\n Node currentNode = root;\n StringBuilder prefix = new StringBuilder();\n String maxKey = null;\n boolean hasNextCharacter = true;\n\n while (hasNextCharacter) {\n hasNextCharacter = false;\n\n for (char nextChar = R - 1; true; nextChar--) {\n if (currentNode.next[nextChar] != null) {\n currentNode = currentNode.next[nextChar];\n prefix.append(nextChar);\n\n if (currentNode.value != null) {\n maxKey = prefix.toString();\n }\n\n hasNextCharacter = true;\n break;\n }\n // nextChar value never becomes less than zero in the for loop, so we need this extra validation\n if (nextChar == 0) {\n break;\n }\n }\n }\n return maxKey;\n }\n\n public void deleteMin() {\n if (isEmpty()) {\n return;\n }\n String minKey = min();\n delete(minKey);\n }\n\n public void deleteMax() {\n if (isEmpty()) {\n return;\n }\n String maxKey = max();\n delete(maxKey);\n }\n }\n\n public static class TernarySearchTrieIterative {\n private int size;\n private Node root;\n\n private class Node {\n private char character;\n private Value value;\n private int size;\n\n private Node left;\n private Node middle;\n private Node right;\n }\n\n private class NodeWithInformation {\n private Node node;\n private StringBuilder prefix;\n private int digit;\n\n NodeWithInformation(Node node, StringBuilder prefix) {\n this.node = node;\n this.prefix = prefix;\n }\n\n NodeWithInformation(Node node, int digit) {\n this.node = node;\n this.digit = digit;\n }\n\n NodeWithInformation(Node node, StringBuilder prefix, int digit) {\n this.node = node;\n this.prefix = prefix;\n this.digit = digit;\n }\n }\n\n private enum Direction {\n LEFT, MIDDLE, RIGHT;\n }\n\n public int size() {\n return size;\n }\n\n public boolean isEmpty() {\n return size() == 0;\n }\n\n public boolean contains(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n return get(key) != null;\n }\n\n public Value get(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n if (key.length() == 0) {\n throw new IllegalArgumentException(\"Key must have a positive length\");\n }\n\n Node node = getNode(key);\n if (node == null) {\n return null;\n }\n return node.value;\n }\n\n private Node getNode(String key) {\n Node currentNode = root;\n int digit = 0;\n\n while (digit != key.length()) {\n if (currentNode == null) {\n return null;\n }\n char currentChar = key.charAt(digit);\n\n if (currentChar < currentNode.character) {\n currentNode = currentNode.left;\n } else if (currentChar > currentNode.character) {\n currentNode = currentNode.right;\n } else if (digit < key.length() - 1) {\n currentNode = currentNode.middle;\n digit++;\n } else {\n return currentNode;\n }\n }\n return null;\n }\n\n public void put(String key, Value value) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n if (value == null) {\n delete(key);\n return;\n }\n boolean isNewKey = !contains(key);\n int digit = 0;\n\n // Special case: putting the first key in the TST\n if (root == null) {\n root = new Node();\n root.character = key.charAt(digit);\n\n if (key.length() == 1) {\n root.value = value;\n root.size = 1;\n return;\n }\n }\n\n Node parent = null;\n Node currentNode = root;\n Direction direction = Direction.LEFT;\n\n while (digit != key.length()) {\n char currentChar = key.charAt(digit);\n\n if (currentNode == null) {\n currentNode = new Node();\n currentNode.character = currentChar;\n\n updateParentReference(parent, currentNode, direction);\n }\n parent = currentNode;\n\n if (currentChar < currentNode.character) {\n currentNode = currentNode.left;\n direction = Direction.LEFT;\n } else if (currentChar > currentNode.character) {\n currentNode = currentNode.right;\n direction = Direction.RIGHT;\n } else if (digit < key.length() - 1) {\n if (isNewKey) {\n currentNode.size = currentNode.size + 1;\n }\n currentNode = currentNode.middle;\n digit++;\n direction = Direction.MIDDLE;\n } else {\n currentNode.value = value;\n\n if (isNewKey) {\n currentNode.size = currentNode.size + 1;\n size++;\n }\n digit++;\n direction = Direction.MIDDLE;\n }\n }\n }\n\n private void updateParentReference(Node parent, Node currentNode, Direction direction) {\n switch (direction) {\n case LEFT: parent.left = currentNode;\n break;\n case MIDDLE: parent.middle = currentNode;\n break;\n case RIGHT: parent.right = currentNode;\n break;\n }\n }\n\n public void delete(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n if (!contains(key)) {\n return;\n }\n int digit = 0;\n\n // Special case: deleting root\n if (root.character == key.charAt(0)\n && root.size == 1) {\n if (root.left == null && root.right == null) {\n root = null;\n } else if (root.left == null) {\n root = root.right;\n } else if (root.right == null) {\n root = root.left;\n } else {\n Node aux = root;\n root = min(aux.right);\n root.right = deleteMin(aux.right);\n root.left = aux.left;\n }\n return;\n }\n\n Node parent = null;\n Node currentNode = root;\n Direction direction = Direction.MIDDLE;\n\n while (digit != key.length()) {\n char currentChar = key.charAt(digit);\n\n if (currentChar == currentNode.character && currentNode.size == 1) {\n if (currentNode.left == null && currentNode.right == null) {\n updateParentReference(parent, null, direction);\n } else if (currentNode.left == null) {\n updateParentReference(parent, currentNode.right, direction);\n } else if (currentNode.right == null) {\n updateParentReference(parent, currentNode.left, direction);\n } else {\n Node aux = currentNode;\n currentNode = min(aux.right);\n currentNode.right = deleteMin(aux.right);\n currentNode.left = aux.left;\n }\n break;\n }\n parent = currentNode;\n\n if (currentChar < currentNode.character) {\n currentNode = currentNode.left;\n direction = Direction.LEFT;\n } else if (currentChar > currentNode.character) {\n currentNode = currentNode.right;\n direction = Direction.RIGHT;\n } else {\n if (digit == key.length() - 1) {\n currentNode.value = null;\n }\n\n currentNode.size = currentNode.size - 1;\n\n digit++;\n currentNode = currentNode.middle;\n direction = Direction.MIDDLE;\n }\n }\n size--;\n }\n\n public Iterable keys() {\n return collect(root, new StringBuilder());\n }\n\n public Iterable keysWithPrefix(String prefix) {\n if (prefix == null) {\n throw new IllegalArgumentException(\"Prefix cannot be null\");\n }\n Queue keysWithPrefix = new Queue<>();\n\n Node nodeWithPrefix = getNode(prefix);\n\n if (nodeWithPrefix == null) {\n return keysWithPrefix;\n }\n if (nodeWithPrefix.value != null) {\n keysWithPrefix.enqueue(prefix);\n }\n Queue otherKeys = collect(nodeWithPrefix.middle, new StringBuilder(prefix));\n\n for (String key : otherKeys) {\n keysWithPrefix.enqueue(key);\n }\n return keysWithPrefix;\n }\n\n private Queue collect(Node node, StringBuilder prefix) {\n Queue queue = new Queue<>();\n\n Stack stack = new Stack<>();\n stack.push(new NodeWithInformation(node, new StringBuilder(prefix)));\n\n while (!stack.isEmpty()) {\n NodeWithInformation currentNodeWithInformation = stack.pop();\n Node currentNode = currentNodeWithInformation.node;\n StringBuilder currentPrefix = currentNodeWithInformation.prefix;\n\n StringBuilder prefixWithCharacter = new StringBuilder(currentPrefix).append(currentNode.character);\n\n if (currentNode.value != null) {\n queue.enqueue(prefixWithCharacter.toString());\n }\n if (currentNode.right != null) {\n stack.push(new NodeWithInformation(currentNode.right, currentPrefix));\n }\n if (currentNode.middle != null) {\n stack.push(new NodeWithInformation(currentNode.middle, prefixWithCharacter));\n }\n if (currentNode.left != null) {\n stack.push(new NodeWithInformation(currentNode.left, currentPrefix));\n }\n }\n return queue;\n }\n\n public Iterable keysThatMatch(String pattern) {\n if (pattern == null) {\n throw new IllegalArgumentException(\"Pattern cannot be null\");\n }\n\n if (isEmpty()) {\n return new Queue<>();\n }\n Queue keysThatMatch = new Queue<>();\n\n Stack stack = new Stack<>();\n stack.push(new NodeWithInformation(root, new StringBuilder()));\n\n while (!stack.isEmpty()) {\n NodeWithInformation currentNodeWithInformation = stack.pop();\n Node currentNode = currentNodeWithInformation.node;\n StringBuilder currentPrefix = currentNodeWithInformation.prefix;\n\n StringBuilder prefixWithCharacter = new StringBuilder(currentPrefix).append(currentNode.character);\n\n int digit = currentPrefix.length();\n char nextCharInPattern = pattern.charAt(digit);\n\n if (nextCharInPattern == '.' || nextCharInPattern > currentNode.character) {\n if (currentNode.right != null) {\n stack.push(new NodeWithInformation(currentNode.right, currentPrefix));\n }\n }\n\n if (nextCharInPattern == '.' || nextCharInPattern == currentNode.character) {\n if (digit == pattern.length() - 1 && currentNode.value != null) {\n keysThatMatch.enqueue(prefixWithCharacter.toString());\n } else if (digit < pattern.length() - 1 && currentNode.middle != null) {\n stack.push(new NodeWithInformation(currentNode.middle, prefixWithCharacter));\n }\n }\n if (nextCharInPattern == '.' || nextCharInPattern < currentNode.character) {\n if (currentNode.left != null) {\n stack.push(new NodeWithInformation(currentNode.left, currentPrefix));\n }\n }\n }\n return keysThatMatch;\n }\n\n public String longestPrefixOf(String query) {\n if (query == null) {\n throw new IllegalArgumentException(\"Query cannot be null\");\n }\n int length = search(query);\n return query.substring(0, length);\n }\n\n private int search(String query) {\n Stack stack = new Stack<>();\n stack.push(new NodeWithInformation(root, 0));\n int length = 0;\n\n while (!stack.isEmpty()) {\n NodeWithInformation currentNodeWithInformation = stack.pop();\n Node currentNode = currentNodeWithInformation.node;\n int currentDigit = currentNodeWithInformation.digit;\n\n char nextChar = query.charAt(currentDigit);\n\n if (currentNode.value != null && currentNode.character == query.charAt(currentDigit)) {\n length = currentDigit + 1;\n }\n\n if (nextChar < currentNode.character && currentNode.left != null) {\n stack.push(new NodeWithInformation(currentNode.left, currentDigit));\n } else if (nextChar > currentNode.character && currentNode.right != null) {\n stack.push(new NodeWithInformation(currentNode.right, currentDigit));\n } else {\n if (nextChar == currentNode.character) {\n if (currentDigit < query.length() - 1 && currentNode.middle != null) {\n stack.push(new NodeWithInformation(currentNode.middle, currentDigit + 1));\n } else {\n return length;\n }\n }\n }\n }\n return length;\n }\n\n // Ordered methods\n\n // Returns the highest key in the symbol table smaller than or equal to key.\n public String floor(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n Stack stack = new Stack<>();\n stack.push(new NodeWithInformation(root, new StringBuilder(), 0));\n String lastKeyFound = null;\n boolean mustBeEqualDigit = true;\n\n while (!stack.isEmpty()) {\n NodeWithInformation currentNodeWithInformation = stack.pop();\n Node currentNode = currentNodeWithInformation.node;\n StringBuilder currentPrefix = currentNodeWithInformation.prefix;\n int currentDigit = currentNodeWithInformation.digit;\n\n StringBuilder prefixWithCharacter = new StringBuilder(currentPrefix).append(currentNode.character);\n\n char currentChar;\n if (currentDigit < key.length() && mustBeEqualDigit) {\n currentChar = key.charAt(currentDigit);\n } else {\n currentChar = Character.MAX_VALUE;\n mustBeEqualDigit = false;\n }\n\n if (currentChar < currentNode.character && currentNode.left != null && mustBeEqualDigit) {\n stack.push(new NodeWithInformation(currentNode.left, currentPrefix, currentDigit));\n } else if (!mustBeEqualDigit || currentChar >= currentNode.character) {\n // Optimization: if current prefix is higher than the search key, left is the only way to go\n if (prefixWithCharacter.toString().compareTo(key) > 0) {\n\n if (currentNode.left != null) {\n stack.push(new NodeWithInformation(currentNode.left, currentPrefix, currentDigit));\n }\n continue;\n }\n\n if (mustBeEqualDigit && currentChar > currentNode.character) {\n mustBeEqualDigit = false;\n }\n\n if (currentNode.value != null) {\n lastKeyFound = prefixWithCharacter.toString();\n }\n\n if (!mustBeEqualDigit && currentNode.right != null) {\n stack.push(new NodeWithInformation(currentNode.right, currentPrefix, currentDigit));\n }\n\n if (currentNode.middle != null) {\n stack.push(new NodeWithInformation(currentNode.middle, prefixWithCharacter, currentDigit + 1));\n }\n }\n }\n return lastKeyFound;\n }\n\n // Returns the smallest key in the symbol table greater than or equal to key.\n public String ceiling(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n Stack stack = new Stack<>();\n stack.push(new NodeWithInformation(root, new StringBuilder(), 0));\n boolean mustBeEqualDigit = true;\n\n while (!stack.isEmpty()) {\n NodeWithInformation currentNodeWithInformation = stack.pop();\n Node currentNode = currentNodeWithInformation.node;\n StringBuilder currentPrefix = currentNodeWithInformation.prefix;\n int currentDigit = currentNodeWithInformation.digit;\n\n StringBuilder prefixWithCharacter = new StringBuilder(currentPrefix).append(currentNode.character);\n\n char currentChar;\n if (currentDigit < key.length() && mustBeEqualDigit) {\n currentChar = key.charAt(currentDigit);\n } else {\n currentChar = 0;\n mustBeEqualDigit = false;\n }\n\n if (currentChar > currentNode.character && currentNode.right != null && mustBeEqualDigit) {\n stack.push(new NodeWithInformation(currentNode.right, currentPrefix, currentDigit));\n } else if (currentChar <= currentNode.character) {\n if (mustBeEqualDigit && currentChar < currentNode.character) {\n mustBeEqualDigit = false;\n }\n\n if (currentNode.value != null && prefixWithCharacter.toString().compareTo(key) >= 0) {\n return prefixWithCharacter.toString();\n }\n\n if (currentNode.right != null) {\n stack.push(new NodeWithInformation(currentNode.right, currentPrefix, currentDigit));\n }\n\n if (currentNode.middle != null) {\n stack.push(new NodeWithInformation(currentNode.middle, prefixWithCharacter, currentDigit + 1));\n }\n\n if (!mustBeEqualDigit && currentNode.left != null) {\n stack.push(new NodeWithInformation(currentNode.left, currentPrefix, currentDigit));\n }\n }\n }\n return null;\n }\n\n public String select(int index) {\n if (index < 0 || index >= size()) {\n throw new IllegalArgumentException(\"Index cannot be negative and must be lower than TST size\");\n }\n\n boolean found = false;\n String key = null;\n StringBuilder prefix = new StringBuilder();\n Node currentNode = root;\n\n while (!found) {\n int leftSubtreeSize = getTreeSize(currentNode.left);\n int tstSize = leftSubtreeSize + currentNode.size;\n\n if (index < leftSubtreeSize) {\n currentNode = currentNode.left;\n } else if (index >= tstSize) {\n currentNode = currentNode.right;\n index = index - tstSize;\n } else {\n index = index - leftSubtreeSize;\n\n if (currentNode.value != null) {\n if (index == 0) {\n key = prefix.append(currentNode.character).toString();\n found = true;\n }\n index--;\n }\n prefix.append(currentNode.character);\n\n if (currentNode.middle != null) {\n currentNode = currentNode.middle;\n }\n }\n }\n return key;\n }\n\n public int rank(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n int rank = 0;\n int digit = 0;\n int size = 0;\n\n Node currentNode = root;\n\n while (currentNode != null) {\n char currentChar = key.charAt(digit);\n\n if (currentChar < currentNode.character) {\n currentNode = currentNode.left;\n } else {\n if (currentChar > currentNode.character) {\n if (currentNode.value != null) {\n size++;\n }\n rank += getTreeSize(currentNode.left) + getTreeSize(currentNode.middle);\n\n currentNode = currentNode.right;\n } else if (digit < key.length() - 1) {\n // Is current key a prefix of the search key?\n if (digit < key.length() - 1 && currentNode.value != null) {\n size++;\n }\n rank += getTreeSize(currentNode.left);\n\n currentNode = currentNode.middle;\n digit++;\n } else {\n rank += getTreeSize(currentNode.left) + size;\n break;\n }\n }\n }\n return rank;\n }\n\n private int getTreeSize(Node node) {\n if (node == null) {\n return 0;\n }\n int size = 0;\n\n Stack stack = new Stack<>();\n stack.push(node);\n\n while (!stack.isEmpty()) {\n Node currentNode = stack.pop();\n\n size += currentNode.size;\n\n if (currentNode.right != null) {\n stack.push(currentNode.right);\n }\n if (currentNode.left != null) {\n stack.push(currentNode.left);\n }\n }\n return size;\n }\n\n public String min() {\n Node minNode = min(root);\n if (minNode == null) {\n return null;\n }\n\n StringBuilder minKey = new StringBuilder();\n minKey.append(minNode.character);\n\n while (minNode.value == null) {\n minNode = minNode.middle;\n\n while (minNode.left != null) {\n minNode = minNode.left;\n }\n minKey.append(minNode.character);\n }\n return minKey.toString();\n }\n\n private Node min(Node node) {\n if (node == null) {\n return null;\n }\n Node currentNode = node;\n\n while (currentNode.left != null) {\n currentNode = currentNode.left;\n }\n return currentNode;\n }\n\n public String max() {\n Node maxNode = max(root);\n if (maxNode == null) {\n return null;\n }\n\n StringBuilder maxKey = new StringBuilder();\n maxKey.append(maxNode.character);\n\n while (maxNode.value == null) {\n maxNode = maxNode.middle;\n\n while (maxNode.right != null) {\n maxNode = maxNode.right;\n }\n maxKey.append(maxNode.character);\n }\n return maxKey.toString();\n }\n\n private Node max(Node node) {\n if (node == null) {\n return null;\n }\n Node currentNode = node;\n\n while (currentNode.right != null) {\n currentNode = currentNode.right;\n }\n return currentNode;\n }\n\n public void deleteMin() {\n if (isEmpty()) {\n return;\n }\n String minKey = min();\n delete(minKey);\n }\n\n // Used only in delete()\n private Node deleteMin(Node node) {\n Node currentNode = node;\n while (currentNode.left != null) {\n currentNode = currentNode.left;\n }\n return currentNode.right;\n }\n\n public void deleteMax() {\n if (isEmpty()) {\n return;\n }\n String maxKey = max();\n delete(maxKey);\n }\n }\n\n public static void main(String[] args) {\n Exercise5 exercise5 = new Exercise5();\n exercise5.trieTests();\n exercise5.tstTests();\n }\n\n private void trieTests() {\n StdOut.println(\"********Trie tests********\");\n TrieIterative trieIterative = new TrieIterative<>();\n\n // Put tests\n trieIterative.put(\"Rene\", 0);\n trieIterative.put(\"Re\", 1);\n trieIterative.put(\"Re\", 10);\n trieIterative.put(\"Algorithms\", 2);\n trieIterative.put(\"Algo\", 3);\n trieIterative.put(\"Algor\", 4);\n trieIterative.put(\"Tree\", 5);\n trieIterative.put(\"Trie\", 6);\n trieIterative.put(\"TST\", 7);\n trieIterative.put(\"Trie123\", 8);\n trieIterative.put(\"Z-Function\", 9);\n\n // Get tests\n StdOut.println(\"Get Re: \" + trieIterative.get(\"Re\"));\n StdOut.println(\"Expected: 10\");\n StdOut.println(\"Get Algorithms: \" + trieIterative.get(\"Algorithms\"));\n StdOut.println(\"Expected: 2\");\n StdOut.println(\"Get Trie123: \" + trieIterative.get(\"Trie123\"));\n StdOut.println(\"Expected: 8\");\n StdOut.println(\"Get Algori: \" + trieIterative.get(\"Algori\"));\n StdOut.println(\"Expected: null\");\n StdOut.println(\"Get Zooom: \" + trieIterative.get(\"Zooom\"));\n StdOut.println(\"Expected: null\");\n\n // Keys with prefix tests\n StdOut.println(\"\\nKeys with prefix Alg\");\n StringJoiner keysWithPrefix1 = new StringJoiner(\" \");\n\n for (String key : trieIterative.keysWithPrefix(\"Alg\")) {\n keysWithPrefix1.add(key);\n }\n StdOut.println(keysWithPrefix1.toString());\n StdOut.println(\"Expected: Algo Algor Algorithms\");\n\n StdOut.println(\"\\nKeys with prefix T\");\n StringJoiner keysWithPrefix2 = new StringJoiner(\" \");\n\n for (String key : trieIterative.keysWithPrefix(\"T\")) {\n keysWithPrefix2.add(key);\n }\n StdOut.println(keysWithPrefix2.toString());\n StdOut.println(\"Expected: TST Tree Trie Trie123\");\n\n StdOut.println(\"\\nKeys with prefix R\");\n StringJoiner keysWithPrefix3 = new StringJoiner(\" \");\n\n for (String key : trieIterative.keysWithPrefix(\"R\")) {\n keysWithPrefix3.add(key);\n }\n StdOut.println(keysWithPrefix3.toString());\n StdOut.println(\"Expected: Re Rene\");\n\n StdOut.println(\"\\nKeys with prefix ZZZ\");\n StringJoiner keysWithPrefix4 = new StringJoiner(\" \");\n\n for (String key : trieIterative.keysWithPrefix(\"ZZZ\")) {\n keysWithPrefix4.add(key);\n }\n StdOut.println(keysWithPrefix4.toString());\n StdOut.println(\"Expected: \");\n\n // Keys that match tests\n StdOut.println(\"\\nKeys that match Alg..\");\n StringJoiner keysThatMatch1 = new StringJoiner(\"Alg..\");\n\n for (String key : trieIterative.keysThatMatch(\"Alg..\")) {\n keysThatMatch1.add(key);\n }\n StdOut.println(keysThatMatch1.toString());\n StdOut.println(\"Expected: Algor\");\n\n StdOut.println(\"\\nKeys that match Re\");\n StringJoiner keysThatMatch2 = new StringJoiner(\" \");\n\n for (String key : trieIterative.keysThatMatch(\"Re\")) {\n keysThatMatch2.add(key);\n }\n StdOut.println(keysThatMatch2.toString());\n StdOut.println(\"Expected: Re\");\n\n StdOut.println(\"\\nKeys that match Tr.e\");\n StringJoiner keysThatMatch3 = new StringJoiner(\" \");\n\n for (String key : trieIterative.keysThatMatch(\"Tr.e\")) {\n keysThatMatch3.add(key);\n }\n StdOut.println(keysThatMatch3.toString());\n StdOut.println(\"Expected: Tree Trie\");\n\n // Longest-prefix-of tests\n StdOut.println(\"\\nLongest prefix of Re: \" + trieIterative.longestPrefixOf(\"Re\"));\n StdOut.println(\"Expected: Re\");\n\n StdOut.println(\"Longest prefix of Algori: \" + trieIterative.longestPrefixOf(\"Algori\"));\n StdOut.println(\"Expected: Algor\");\n\n StdOut.println(\"Longest prefix of Trie12345: \" + trieIterative.longestPrefixOf(\"Trie12345\"));\n StdOut.println(\"Expected: Trie123\");\n\n StdOut.println(\"Longest prefix of Zooom: \" + trieIterative.longestPrefixOf(\"Zooom\"));\n StdOut.println(\"Expected: \");\n\n // Min tests\n StdOut.println(\"\\nMin key: \" + trieIterative.min());\n StdOut.println(\"Expected: Algo\");\n\n // Max tests\n StdOut.println(\"\\nMax key: \" + trieIterative.max());\n StdOut.println(\"Expected: Z-Function\");\n\n // Delete min and delete max tests\n trieIterative.put(\"ABCKey\", 11);\n trieIterative.put(\"ZKey\", 12);\n\n StdOut.println(\"\\nKeys after ABCKey and ZKey insert: \");\n for (String key : trieIterative.keys()) {\n StdOut.println(key);\n }\n\n trieIterative.deleteMin();\n\n StdOut.println(\"\\nKeys after deleteMin: \");\n for (String key : trieIterative.keys()) {\n StdOut.println(key);\n }\n StdOut.println(\"Expected: ABCKey deleted\");\n\n trieIterative.deleteMax();\n\n StdOut.println(\"\\nKeys after deleteMax: \");\n for (String key : trieIterative.keys()) {\n StdOut.println(key);\n }\n StdOut.println(\"Expected: ZKey deleted\");\n\n // Floor tests\n StdOut.println(\"\\nFloor of Re: \" + trieIterative.floor(\"Re\"));\n StdOut.println(\"Expected: Re\");\n StdOut.println(\"Floor of Algori: \" + trieIterative.floor(\"Algori\"));\n StdOut.println(\"Expected: Algor\");\n StdOut.println(\"Floor of Ball: \" + trieIterative.floor(\"Ball\"));\n StdOut.println(\"Expected: Algorithms\");\n StdOut.println(\"Floor of Tarjan: \" + trieIterative.floor(\"Tarjan\"));\n StdOut.println(\"Expected: TST\");\n StdOut.println(\"Floor of AA: \" + trieIterative.floor(\"AA\"));\n StdOut.println(\"Expected: null\");\n StdOut.println(\"Floor of Zoom: \" + trieIterative.floor(\"Zoom\"));\n StdOut.println(\"Expected: Z-Function\");\n StdOut.println(\"Floor of TAB: \" + trieIterative.floor(\"TAB\"));\n StdOut.println(\"Expected: Rene\");\n\n // Ceiling tests\n StdOut.println(\"\\nCeiling of Re: \" + trieIterative.ceiling(\"Re\"));\n StdOut.println(\"Expected: Re\");\n StdOut.println(\"Ceiling of Algori: \" + trieIterative.ceiling(\"Algori\"));\n StdOut.println(\"Expected: Algorithms\");\n StdOut.println(\"Ceiling of Ball: \" + trieIterative.ceiling(\"Ball\"));\n StdOut.println(\"Expected: Re\");\n StdOut.println(\"Ceiling of Tarjan: \" + trieIterative.ceiling(\"Tarjan\"));\n StdOut.println(\"Expected: Tree\");\n StdOut.println(\"Ceiling of AA: \" + trieIterative.ceiling(\"AA\"));\n StdOut.println(\"Expected: Algo\");\n StdOut.println(\"Ceiling of Zoom: \" + trieIterative.ceiling(\"Zoom\"));\n StdOut.println(\"Expected: null\");\n StdOut.println(\"Ceiling of Tro: \" + trieIterative.ceiling(\"Tro\"));\n StdOut.println(\"Expected: Z-Function\");\n StdOut.println(\"Ceiling of Ruby: \" + trieIterative.ceiling(\"Ruby\"));\n StdOut.println(\"Expected: TST\");\n\n // Select tests\n StdOut.println(\"\\nSelect 0: \" + trieIterative.select(0));\n StdOut.println(\"Expected: Algo\");\n StdOut.println(\"Select 3: \" + trieIterative.select(3));\n StdOut.println(\"Expected: Re\");\n StdOut.println(\"Select 2: \" + trieIterative.select(2));\n StdOut.println(\"Expected: Algorithms\");\n StdOut.println(\"Select 5: \" + trieIterative.select(5));\n StdOut.println(\"Expected: TST\");\n StdOut.println(\"Select 8: \" + trieIterative.select(8));\n StdOut.println(\"Expected: Trie123\");\n StdOut.println(\"Select 9: \" + trieIterative.select(9));\n StdOut.println(\"Expected: Z-Function\");\n\n // Rank tests\n StdOut.println(\"\\nRank of R: \" + trieIterative.rank(\"R\"));\n StdOut.println(\"Expected: 3\");\n StdOut.println(\"Rank of Re: \" + trieIterative.rank(\"Re\"));\n StdOut.println(\"Expected: 3\");\n StdOut.println(\"Rank of A: \" + trieIterative.rank(\"A\"));\n StdOut.println(\"Expected: 0\");\n StdOut.println(\"Rank of Algo: \" + trieIterative.rank(\"Algo\"));\n StdOut.println(\"Expected: 0\");\n StdOut.println(\"Rank of Algori: \" + trieIterative.rank(\"Algori\"));\n StdOut.println(\"Expected: 2\");\n StdOut.println(\"Rank of Algorithms: \" + trieIterative.rank(\"Algorithms\"));\n StdOut.println(\"Expected: 2\");\n StdOut.println(\"Rank of Tarjan: \" + trieIterative.rank(\"Tarjan\"));\n StdOut.println(\"Expected: 6\");\n StdOut.println(\"Rank of Trie123: \" + trieIterative.rank(\"Trie123\"));\n StdOut.println(\"Expected: 8\");\n StdOut.println(\"Rank of Zzoom: \" + trieIterative.rank(\"Zzoom\"));\n StdOut.println(\"Expected: 10\");\n\n // Delete tests\n trieIterative.delete(\"Z-Function\");\n StdOut.println(\"\\nKeys() after deleting Z-Function key\");\n for (String key : trieIterative.keys()) {\n StdOut.println(key);\n }\n\n trieIterative.delete(\"Re\");\n StdOut.println(\"\\nKeys() after deleting Re key\");\n for (String key : trieIterative.keys()) {\n StdOut.println(key);\n }\n\n trieIterative.delete(\"Rene\");\n StdOut.println(\"\\nKeys() after deleting Rene key\");\n for (String key : trieIterative.keys()) {\n StdOut.println(key);\n }\n }\n\n private void tstTests() {\n StdOut.println(\"\\n********Ternary Search Trie tests********\");\n TernarySearchTrieIterative ternarySearchTrieIterative = new TernarySearchTrieIterative<>();\n\n // Put tests\n ternarySearchTrieIterative.put(\"Rene\", 0);\n ternarySearchTrieIterative.put(\"Re\", 1);\n ternarySearchTrieIterative.put(\"Re\", 10);\n ternarySearchTrieIterative.put(\"Algorithms\", 2);\n ternarySearchTrieIterative.put(\"Algo\", 3);\n ternarySearchTrieIterative.put(\"Algor\", 4);\n ternarySearchTrieIterative.put(\"Tree\", 5);\n ternarySearchTrieIterative.put(\"Trie\", 6);\n ternarySearchTrieIterative.put(\"TST\", 7);\n ternarySearchTrieIterative.put(\"Trie123\", 8);\n ternarySearchTrieIterative.put(\"Z-Function\", 9);\n\n // Get tests\n StdOut.println(\"Get Re: \" + ternarySearchTrieIterative.get(\"Re\"));\n StdOut.println(\"Expected: 10\");\n StdOut.println(\"Get Algorithms: \" + ternarySearchTrieIterative.get(\"Algorithms\"));\n StdOut.println(\"Expected: 2\");\n StdOut.println(\"Get Trie123: \" + ternarySearchTrieIterative.get(\"Trie123\"));\n StdOut.println(\"Expected: 8\");\n StdOut.println(\"Get Algori: \" + ternarySearchTrieIterative.get(\"Algori\"));\n StdOut.println(\"Expected: null\");\n StdOut.println(\"Get Zooom: \" + ternarySearchTrieIterative.get(\"Zooom\"));\n StdOut.println(\"Expected: null\");\n\n // Keys with prefix tests\n StdOut.println(\"\\nKeys with prefix Alg\");\n StringJoiner keysWithPrefix1 = new StringJoiner(\" \");\n\n for (String key : ternarySearchTrieIterative.keysWithPrefix(\"Alg\")) {\n keysWithPrefix1.add(key);\n }\n StdOut.println(keysWithPrefix1.toString());\n StdOut.println(\"Expected: Algo Algor Algorithms\");\n\n StdOut.println(\"\\nKeys with prefix T\");\n StringJoiner keysWithPrefix2 = new StringJoiner(\" \");\n\n for (String key : ternarySearchTrieIterative.keysWithPrefix(\"T\")) {\n keysWithPrefix2.add(key);\n }\n StdOut.println(keysWithPrefix2.toString());\n StdOut.println(\"Expected: TST Tree Trie Trie123\");\n\n StdOut.println(\"\\nKeys with prefix R\");\n StringJoiner keysWithPrefix3 = new StringJoiner(\" \");\n\n for (String key : ternarySearchTrieIterative.keysWithPrefix(\"R\")) {\n keysWithPrefix3.add(key);\n }\n StdOut.println(keysWithPrefix3.toString());\n StdOut.println(\"Expected: Re Rene\");\n\n StdOut.println(\"\\nKeys with prefix ZZZ\");\n StringJoiner keysWithPrefix4 = new StringJoiner(\" \");\n\n for (String key : ternarySearchTrieIterative.keysWithPrefix(\"ZZZ\")) {\n keysWithPrefix4.add(key);\n }\n StdOut.println(keysWithPrefix4.toString());\n StdOut.println(\"Expected: \");\n\n // Keys that match tests\n StdOut.println(\"\\nKeys that match Alg..\");\n StringJoiner keysThatMatch1 = new StringJoiner(\"Alg..\");\n\n for (String key : ternarySearchTrieIterative.keysThatMatch(\"Alg..\")) {\n keysThatMatch1.add(key);\n }\n StdOut.println(keysThatMatch1.toString());\n StdOut.println(\"Expected: Algor\");\n\n StdOut.println(\"\\nKeys that match Re\");\n StringJoiner keysThatMatch2 = new StringJoiner(\" \");\n\n for (String key : ternarySearchTrieIterative.keysThatMatch(\"Re\")) {\n keysThatMatch2.add(key);\n }\n StdOut.println(keysThatMatch2.toString());\n StdOut.println(\"Expected: Re\");\n\n StdOut.println(\"\\nKeys that match Tr.e\");\n StringJoiner keysThatMatch3 = new StringJoiner(\" \");\n\n for (String key : ternarySearchTrieIterative.keysThatMatch(\"Tr.e\")) {\n keysThatMatch3.add(key);\n }\n StdOut.println(keysThatMatch3.toString());\n StdOut.println(\"Expected: Tree Trie\");\n\n // Longest-prefix-of tests\n StdOut.println(\"\\nLongest prefix of Re: \" + ternarySearchTrieIterative.longestPrefixOf(\"Re\"));\n StdOut.println(\"Expected: Re\");\n\n StdOut.println(\"Longest prefix of Algori: \" + ternarySearchTrieIterative.longestPrefixOf(\"Algori\"));\n StdOut.println(\"Expected: Algor\");\n\n StdOut.println(\"Longest prefix of Trie12345: \" + ternarySearchTrieIterative.longestPrefixOf(\"Trie12345\"));\n StdOut.println(\"Expected: Trie123\");\n\n StdOut.println(\"Longest prefix of Zooom: \" + ternarySearchTrieIterative.longestPrefixOf(\"Zooom\"));\n StdOut.println(\"Expected: \");\n\n // Min tests\n StdOut.println(\"\\nMin key: \" + ternarySearchTrieIterative.min());\n StdOut.println(\"Expected: Algo\");\n\n // Max tests\n StdOut.println(\"\\nMax key: \" + ternarySearchTrieIterative.max());\n StdOut.println(\"Expected: Z-Function\");\n\n // Delete min and delete max tests\n ternarySearchTrieIterative.put(\"ABCKey\", 11);\n ternarySearchTrieIterative.put(\"ZKey\", 12);\n\n StdOut.println(\"\\nKeys after ABCKey and ZKey insert: \");\n for (String key : ternarySearchTrieIterative.keys()) {\n StdOut.println(key);\n }\n\n ternarySearchTrieIterative.deleteMin();\n StdOut.println(\"\\nKeys after deleteMin: \");\n for (String key : ternarySearchTrieIterative.keys()) {\n StdOut.println(key);\n }\n StdOut.println(\"Expected: ABCKey deleted\");\n\n ternarySearchTrieIterative.deleteMax();\n StdOut.println(\"\\nKeys after deleteMax: \");\n for (String key : ternarySearchTrieIterative.keys()) {\n StdOut.println(key);\n }\n StdOut.println(\"Expected: ZKey deleted\");\n\n // Floor tests\n StdOut.println(\"\\nFloor of Re: \" + ternarySearchTrieIterative.floor(\"Re\"));\n StdOut.println(\"Expected: Re\");\n StdOut.println(\"Floor of Algori: \" + ternarySearchTrieIterative.floor(\"Algori\"));\n StdOut.println(\"Expected: Algor\");\n StdOut.println(\"Floor of Ball: \" + ternarySearchTrieIterative.floor(\"Ball\"));\n StdOut.println(\"Expected: Algorithms\");\n StdOut.println(\"Floor of Tarjan: \" + ternarySearchTrieIterative.floor(\"Tarjan\"));\n StdOut.println(\"Expected: TST\");\n StdOut.println(\"Floor of AA: \" + ternarySearchTrieIterative.floor(\"AA\"));\n StdOut.println(\"Expected: null\");\n StdOut.println(\"Floor of Zoom: \" + ternarySearchTrieIterative.floor(\"Zoom\"));\n StdOut.println(\"Expected: Z-Function\");\n StdOut.println(\"Floor of TAB: \" + ternarySearchTrieIterative.floor(\"TAB\"));\n StdOut.println(\"Expected: Rene\");\n\n // Ceiling tests\n StdOut.println(\"\\nCeiling of Re: \" + ternarySearchTrieIterative.ceiling(\"Re\"));\n StdOut.println(\"Expected: Re\");\n StdOut.println(\"Ceiling of Algori: \" + ternarySearchTrieIterative.ceiling(\"Algori\"));\n StdOut.println(\"Expected: Algorithms\");\n StdOut.println(\"Ceiling of Ball: \" + ternarySearchTrieIterative.ceiling(\"Ball\"));\n StdOut.println(\"Expected: Re\");\n StdOut.println(\"Ceiling of Tarjan: \" + ternarySearchTrieIterative.ceiling(\"Tarjan\"));\n StdOut.println(\"Expected: Tree\");\n StdOut.println(\"Ceiling of AA: \" + ternarySearchTrieIterative.ceiling(\"AA\"));\n StdOut.println(\"Expected: Algo\");\n StdOut.println(\"Ceiling of Zoom: \" + ternarySearchTrieIterative.ceiling(\"Zoom\"));\n StdOut.println(\"Expected: null\");\n StdOut.println(\"Ceiling of Tro: \" + ternarySearchTrieIterative.ceiling(\"Tro\"));\n StdOut.println(\"Expected: Z-Function\");\n StdOut.println(\"Ceiling of Ruby: \" + ternarySearchTrieIterative.ceiling(\"Ruby\"));\n StdOut.println(\"Expected: TST\");\n\n // Select tests\n StdOut.println(\"\\nSelect 0: \" + ternarySearchTrieIterative.select(0));\n StdOut.println(\"Expected: Algo\");\n StdOut.println(\"Select 3: \" + ternarySearchTrieIterative.select(3));\n StdOut.println(\"Expected: Re\");\n StdOut.println(\"Select 2: \" + ternarySearchTrieIterative.select(2));\n StdOut.println(\"Expected: Algorithms\");\n StdOut.println(\"Select 5: \" + ternarySearchTrieIterative.select(5));\n StdOut.println(\"Expected: TST\");\n StdOut.println(\"Select 8: \" + ternarySearchTrieIterative.select(8));\n StdOut.println(\"Expected: Trie123\");\n StdOut.println(\"Select 9: \" + ternarySearchTrieIterative.select(9));\n StdOut.println(\"Expected: Z-Function\");\n\n // Rank tests\n StdOut.println(\"\\nRank of R: \" + ternarySearchTrieIterative.rank(\"R\"));\n StdOut.println(\"Expected: 3\");\n StdOut.println(\"Rank of Re: \" + ternarySearchTrieIterative.rank(\"Re\"));\n StdOut.println(\"Expected: 3\");\n StdOut.println(\"Rank of A: \" + ternarySearchTrieIterative.rank(\"A\"));\n StdOut.println(\"Expected: 0\");\n StdOut.println(\"Rank of Algo: \" + ternarySearchTrieIterative.rank(\"Algo\"));\n StdOut.println(\"Expected: 0\");\n StdOut.println(\"Rank of Algori: \" + ternarySearchTrieIterative.rank(\"Algori\"));\n StdOut.println(\"Expected: 2\");\n StdOut.println(\"Rank of Algorithms: \" + ternarySearchTrieIterative.rank(\"Algorithms\"));\n StdOut.println(\"Expected: 2\");\n StdOut.println(\"Rank of Tarjan: \" + ternarySearchTrieIterative.rank(\"Tarjan\"));\n StdOut.println(\"Expected: 6\");\n StdOut.println(\"Rank of Trie123: \" + ternarySearchTrieIterative.rank(\"Trie123\"));\n StdOut.println(\"Expected: 8\");\n StdOut.println(\"Rank of Zzoom: \" + ternarySearchTrieIterative.rank(\"Zzoom\"));\n StdOut.println(\"Expected: 10\");\n\n // Delete tests\n ternarySearchTrieIterative.delete(\"Z-Function\");\n StdOut.println(\"\\nKeys() after deleting Z-Function key\");\n for (String key : ternarySearchTrieIterative.keys()) {\n StdOut.println(key);\n }\n\n ternarySearchTrieIterative.delete(\"Re\");\n StdOut.println(\"\\nKeys() after deleting Re key\");\n for (String key : ternarySearchTrieIterative.keys()) {\n StdOut.println(key);\n }\n\n ternarySearchTrieIterative.delete(\"Rene\");\n StdOut.println(\"\\nKeys() after deleting Rene key\");\n for (String key : ternarySearchTrieIterative.keys()) {\n StdOut.println(key);\n }\n }\n}\n", "support_files": [], "metadata": {"number": "5.2.5", "chapter": 5, "chapter_title": "Strings", "section": 5.2, "section_title": "Tries", "type": "Exercise", "code_execution": false}} {"question": "Implement the following API, for a StringSET data type:\npublic class StringSET\nStringSET() create a string set\nvoid add(String key) put key into the set\nvoid delete(String key) remove key from the set\nboolean contains(String key) is key in the set?\nboolean isEmpty() is the set empty?\nint size() number of keys in the set\nint toString() string representation of the set", "answer": "package chapter5.section2;\n\nimport chapter3.section4.SeparateChainingHashTable;\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.*;\n\n/**\n * Created by Rene Argento on 31/01/18.\n */\npublic class Exercise6 {\n\n public interface StringSETAPI {\n void add(String key);\n void delete(String key);\n boolean contains(String key);\n boolean isEmpty();\n int size();\n String toString();\n }\n\n public class StringSET implements StringSETAPI {\n\n private class Node {\n private SeparateChainingHashTable next = new SeparateChainingHashTable<>();\n boolean isKey;\n }\n\n private Node root = new Node();\n private int size;\n\n @Override\n public int size() {\n return size;\n }\n\n @Override\n public boolean isEmpty() {\n return size() == 0;\n }\n\n @Override\n public boolean contains(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n return contains(root, key, 0);\n }\n\n private boolean contains(Node node, String key, int digit) {\n if (node == null) {\n return false;\n }\n\n if (digit == key.length()) {\n return node.isKey;\n }\n\n char nextChar = key.charAt(digit);\n\n if (node.next.contains(nextChar)) {\n return contains(node.next.get(nextChar), key, digit + 1);\n } else {\n return false;\n }\n }\n\n @Override\n public void add(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n if (contains(key)) {\n return;\n }\n\n root = add(root, key, 0);\n size++;\n }\n\n private Node add(Node node, String key, int digit) {\n if (node == null) {\n node = new Node();\n }\n\n if (digit == key.length()) {\n node.isKey = true;\n return node;\n }\n\n char nextChar = key.charAt(digit);\n\n Node nextNode = add(node.next.get(nextChar), key, digit + 1);\n node.next.put(nextChar, nextNode);\n return node;\n }\n\n @Override\n public void delete(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n if (!contains(key)) {\n return;\n }\n\n root = delete(root, key, 0);\n size--;\n }\n\n private Node delete(Node node, String key, int digit) {\n\n if (digit == key.length()) {\n node.isKey = false;\n } else {\n char nextChar = key.charAt(digit);\n Node childNode = delete(node.next.get(nextChar), key, digit + 1);\n node.next.put(nextChar, childNode);\n }\n\n if (node.isKey || node.next.size() > 0) {\n return node;\n }\n\n return null;\n }\n\n // O(n lg n) due to sort - the hash map in the nodes saves memory, but does not necessarily store subsets in order.\n // So a sort is required to return the keys in order.\n public Iterable keys() {\n List keys = new ArrayList<>();\n keys(root, new StringBuilder(), keys);\n\n Collections.sort(keys);\n\n return keys;\n }\n\n private void keys(Node node, StringBuilder prefix, List keys) {\n if (node == null) {\n return;\n }\n\n if (node.isKey) {\n keys.add(prefix.toString());\n }\n\n for (Character character : node.next.keys()) {\n keys(node.next.get(character), new StringBuilder(prefix).append(character), keys);\n }\n }\n\n @Override\n public String toString() {\n StringJoiner keys = new StringJoiner(\", \");\n\n for (String key : keys()) {\n keys.add(key);\n }\n\n return \"{ \" + keys.toString() + \" }\";\n }\n\n }\n\n public static void main(String[] args) {\n StringSET stringSET = new Exercise6().new StringSET();\n\n StdOut.println(\"Is string set empty: \" + stringSET.isEmpty());\n StdOut.println(\"Expected: true\");\n\n StdOut.println(\"\\nSize: \" + stringSET.size());\n StdOut.println(\"Expected: 0\");\n\n StdOut.println(\"\\nToString:\\n\" + stringSET);\n\n stringSET.add(\"Rene\");\n stringSET.add(\"Re\");\n stringSET.add(\"Algorithms\");\n stringSET.add(\"Algo\");\n stringSET.add(\"Algor\");\n stringSET.add(\"Tree\");\n stringSET.add(\"Trie\");\n stringSET.add(\"TST\");\n stringSET.add(\"Trie123\");\n\n StdOut.println(\"\\nIs string set empty: \" + stringSET.isEmpty());\n StdOut.println(\"Expected: false\");\n\n StdOut.println(\"\\nSize: \" + stringSET.size());\n StdOut.println(\"Expected: 9\");\n\n StdOut.println(\"\\nToString:\\n\" + stringSET);\n\n // Adding a key that already exists\n stringSET.add(\"Algorithms\");\n\n StdOut.println(\"\\nSize after adding key that already exists: \" + stringSET.size());\n StdOut.println(\"Expected: 9\");\n\n StdOut.println(\"\\nContains key Sedgewick: \" + stringSET.contains(\"Sedgewick\"));\n StdOut.println(\"Expected: false\");\n\n StdOut.println(\"\\nContains key Rene: \" + stringSET.contains(\"Rene\"));\n StdOut.println(\"Expected: true\");\n\n StdOut.println(\"\\nContains key Z-Function: \" + stringSET.contains(\"Z-Function\"));\n StdOut.println(\"Expected: false\");\n\n StdOut.println(\"\\nContains key Algorithms: \" + stringSET.contains(\"Algorithms\"));\n StdOut.println(\"Expected: true\");\n\n stringSET.delete(\"Algorithms\");\n\n StdOut.println(\"\\nContains key Algorithms (after delete): \" + stringSET.contains(\"Algorithms\"));\n StdOut.println(\"Expected: false\");\n\n stringSET.delete(\"Re\");\n StdOut.println(\"\\nSize after deletes: \" + stringSET.size());\n StdOut.println(\"Expected: 7\");\n\n StdOut.println(\"\\nToString:\\n\" + stringSET);\n }\n}\n", "support_files": [], "metadata": {"number": "5.2.6", "chapter": 5, "chapter_title": "Strings", "section": 5.2, "section_title": "Tries", "type": "Exercise", "code_execution": false}} {"question": "Ordered operations for tries. Implement the floor(), ceil(), rank(), and select() (from our standard ordered ST API from Chapter 3) for TrieST.", "answer": "package chapter5.section2;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 23/01/18.\n */\npublic class Exercise8_OrderedOperationsForTries {\n\n public class TrieOrdered extends Trie {\n\n // Returns the highest key in the symbol table smaller than or equal to key.\n public String floor(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n return floor(root, key, 0, new StringBuilder(), null, true);\n }\n\n private String floor(Node node, String key, int digit, StringBuilder prefix, String lastKeyFound,\n boolean mustBeEqualDigit) {\n if (node == null) {\n return null;\n }\n\n if (prefix.toString().compareTo(key) > 0) {\n return lastKeyFound;\n }\n\n if (node.value != null) {\n lastKeyFound = prefix.toString();\n }\n\n char currentChar;\n\n if (mustBeEqualDigit && digit < key.length()) {\n currentChar = key.charAt(digit);\n } else {\n currentChar = R - 1;\n }\n\n for (char nextChar = currentChar; true; nextChar--) {\n if (node.next[nextChar] != null) {\n if (nextChar < currentChar) {\n mustBeEqualDigit = false;\n }\n\n lastKeyFound = floor(node.next[nextChar], key, digit + 1, prefix.append(nextChar), lastKeyFound, mustBeEqualDigit);\n\n if (lastKeyFound != null) {\n return lastKeyFound;\n }\n prefix.deleteCharAt(prefix.length() - 1);\n }\n\n // nextChar value never becomes less than zero in the for loop, so we need this extra validation\n if (nextChar == 0) {\n break;\n }\n }\n\n return lastKeyFound;\n }\n\n // Returns the smallest key in the symbol table greater than or equal to key.\n public String ceiling(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n return ceiling(root, key, 0, new StringBuilder(), true);\n }\n\n private String ceiling(Node node, String key, int digit, StringBuilder prefix, boolean mustBeEqualDigit) {\n if (node == null) {\n return null;\n }\n\n if (node.value != null && prefix.toString().compareTo(key) >= 0) {\n return prefix.toString();\n }\n\n char currentChar;\n\n if (mustBeEqualDigit && digit < key.length()) {\n currentChar = key.charAt(digit);\n } else {\n currentChar = 0;\n }\n\n for (char nextChar = currentChar; nextChar < R; nextChar++) {\n if (node.next[nextChar] != null) {\n if (nextChar > currentChar) {\n mustBeEqualDigit = false;\n }\n\n String keyFound = ceiling(node.next[nextChar], key, digit + 1, prefix.append(nextChar),\n mustBeEqualDigit);\n\n if (keyFound != null) {\n return keyFound;\n }\n prefix.deleteCharAt(prefix.length() - 1);\n }\n }\n\n return null;\n }\n\n public String select(int index) {\n if (index < 0 || index >= size()) {\n throw new IllegalArgumentException(\"Index cannot be negative and must be lower than trie size\");\n }\n\n return select(root, index, new StringBuilder());\n }\n\n private String select(Node node, int index, StringBuilder prefix) {\n if (node == null) {\n return null;\n }\n\n if (node.value != null) {\n index--;\n\n // Found the key with the target index\n if (index == -1) {\n return prefix.toString();\n }\n }\n\n for (char nextChar = 0; nextChar < R; nextChar++) {\n if (node.next[nextChar] != null) {\n if (index - size(node.next[nextChar]) < 0) {\n return select(node.next[nextChar], index, prefix.append(nextChar));\n } else {\n index = index - size(node.next[nextChar]);\n }\n }\n }\n\n return null;\n }\n\n public int rank(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n return rank(root, key, 0, 0);\n }\n\n private int rank(Node node, String key, int digit, int size) {\n if (node == null || digit == key.length()) {\n return size;\n }\n\n if (node.value != null) {\n if (digit < key.length()) {\n size++;\n } else {\n return size;\n }\n }\n\n char currentChar = key.charAt(digit);\n\n for (char nextChar = 0; nextChar < currentChar; nextChar++) {\n size += size(node.next[nextChar]);\n }\n\n return rank(node.next[currentChar], key, digit + 1, size);\n }\n\n public String min() {\n if (isEmpty()) {\n return null;\n }\n\n return min(root, new StringBuilder());\n }\n\n private String min(Node node, StringBuilder prefix) {\n\n if (node.value != null) {\n return prefix.toString();\n }\n\n for (char nextChar = 0; nextChar < R; nextChar++) {\n if (node.next[nextChar] != null) {\n return min(node.next[nextChar], prefix.append(nextChar));\n }\n }\n\n return prefix.toString();\n }\n\n public String max() {\n if (isEmpty()) {\n return null;\n }\n\n return max(root, new StringBuilder());\n }\n\n private String max(Node node, StringBuilder prefix) {\n\n for (char nextChar = R - 1; true; nextChar--) {\n if (node.next[nextChar] != null) {\n return max(node.next[nextChar], prefix.append(nextChar));\n }\n\n // nextChar value never becomes less than zero in the for loop, so we need this extra validation\n if (nextChar == 0) {\n break;\n }\n }\n\n return prefix.toString();\n }\n\n public void deleteMin() {\n if (isEmpty()) {\n return;\n }\n\n String minKey = min();\n delete(minKey);\n }\n\n public void deleteMax() {\n if (isEmpty()) {\n return;\n }\n\n String maxKey = max();\n delete(maxKey);\n }\n\n }\n\n public class TernarySearchTrieOrdered extends TernarySearchTrie {\n\n // Returns the highest key in the symbol table smaller than or equal to key.\n public String floor(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n return floor(root, key, 0, new StringBuilder(), null, true);\n }\n\n private String floor(Node node, String key, int digit, StringBuilder prefix, String lastKeyFound,\n boolean mustBeEqualDigit) {\n if (node == null) {\n return lastKeyFound;\n }\n\n StringBuilder prefixWithCharacter = new StringBuilder(prefix).append(node.character);\n\n char currentChar;\n if (digit < key.length() && mustBeEqualDigit) {\n currentChar = key.charAt(digit);\n } else {\n currentChar = Character.MAX_VALUE;\n mustBeEqualDigit = false;\n }\n\n if (currentChar < node.character && mustBeEqualDigit) {\n return floor(node.left, key, digit, prefix, lastKeyFound, true);\n } else if (!mustBeEqualDigit || currentChar >= node.character) {\n // Optimization: if current prefix is higher than the search key, left is the only way to go\n if (prefixWithCharacter.toString().compareTo(key) > 0) {\n\n if (node.left != null) {\n return floor(node.left, key, digit, prefix, lastKeyFound, mustBeEqualDigit);\n }\n return lastKeyFound;\n }\n\n if (mustBeEqualDigit && currentChar > node.character) {\n mustBeEqualDigit = false;\n }\n\n // Check child nodes in the order: right, middle, current, left\n String rightKey = floor(node.right, key, digit, prefix, lastKeyFound, mustBeEqualDigit);\n if (rightKey != null) {\n return rightKey;\n }\n\n String middleKey = floor(node.middle, key, digit + 1, prefixWithCharacter, null, mustBeEqualDigit);\n if (middleKey != null) {\n return middleKey;\n }\n\n if (node.value != null && prefixWithCharacter.toString().compareTo(key) <= 0) {\n return prefixWithCharacter.toString();\n }\n\n String leftKey = floor(node.left, key, digit, prefix, lastKeyFound, mustBeEqualDigit);\n if (leftKey != null) {\n return leftKey;\n }\n }\n\n return null;\n }\n\n // Returns the smallest key in the symbol table greater than or equal to key.\n public String ceiling(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n if (contains(key)) {\n return key;\n }\n\n return ceiling(root, key, 0, new StringBuilder(), null, true);\n }\n\n private String ceiling(Node node, String key, int digit, StringBuilder prefix, String lastKeyFound,\n boolean mustBeEqualDigit) {\n if (node == null) {\n return lastKeyFound;\n }\n\n StringBuilder prefixWithCharacter = new StringBuilder(prefix).append(node.character);\n\n char currentChar;\n if (digit < key.length() && mustBeEqualDigit) {\n currentChar = key.charAt(digit);\n } else {\n currentChar = 0;\n mustBeEqualDigit = false;\n }\n\n if (currentChar > node.character && mustBeEqualDigit) {\n return ceiling(node.right, key, digit, prefix, lastKeyFound, true);\n } else if (!mustBeEqualDigit || currentChar <= node.character) {\n if (mustBeEqualDigit && currentChar < node.character) {\n mustBeEqualDigit = false;\n }\n\n // Check child nodes in the order: left, current, middle, right\n if (!mustBeEqualDigit) {\n lastKeyFound = ceiling(node.left, key, digit, prefix, null, false);\n if (lastKeyFound != null) {\n return lastKeyFound;\n }\n }\n\n if (node.value != null && prefixWithCharacter.toString().compareTo(key) >= 0) {\n return prefixWithCharacter.toString();\n }\n\n String middleKey = ceiling(node.middle, key, digit + 1, prefixWithCharacter, null, mustBeEqualDigit);\n if (middleKey != null) {\n return middleKey;\n }\n\n String rightKey = ceiling(node.right, key, digit, prefix, null, mustBeEqualDigit);\n if (rightKey != null) {\n return rightKey;\n }\n }\n\n return null;\n }\n\n public String select(int index) {\n if (index < 0 || index >= size()) {\n throw new IllegalArgumentException(\"Index cannot be negative and must be lower than TST size\");\n }\n\n return select(root, index, new StringBuilder());\n }\n\n private String select(Node node, int index, StringBuilder prefix) {\n if (node == null) {\n return null;\n }\n\n int leftSubtreeSize = getTreeSize(node.left);\n int tstSize = leftSubtreeSize + node.size;\n\n if (index < leftSubtreeSize) {\n return select(node.left, index, prefix);\n } else if (index >= tstSize) {\n return select(node.right, index - tstSize, prefix);\n } else {\n index = index - leftSubtreeSize;\n\n if (node.value != null) {\n if (index == 0) {\n return prefix.append(node.character).toString();\n }\n index--;\n }\n\n prefix.append(node.character);\n return select(node.middle, index, prefix);\n }\n }\n\n public int rank(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n return rank(root, key, 0, 0);\n }\n\n private int rank(Node node, String key, int digit, int size) {\n if (node == null) {\n return size;\n }\n\n char currentChar = key.charAt(digit);\n\n if (currentChar < node.character) {\n return rank(node.left, key, digit, size);\n } else {\n if (currentChar > node.character) {\n if (node.value != null) {\n size++;\n }\n\n return getTreeSize(node.left) + getTreeSize(node.middle) + rank(node.right, key, digit, size);\n } else if (digit < key.length() - 1) {\n // Is current key a prefix of the search key?\n if (digit < key.length() - 1 && node.value != null) {\n size++;\n }\n\n return getTreeSize(node.left) + rank(node.middle, key, digit + 1, size);\n } else {\n return getTreeSize(node.left) + size;\n }\n }\n }\n\n private int getTreeSize(Node node) {\n if (node == null) {\n return 0;\n }\n\n int size = node.size;\n size += getTreeSize(node.left);\n size += getTreeSize(node.right);\n\n return size;\n }\n\n public String min() {\n if (isEmpty()) {\n return null;\n }\n\n Node minNode = min(root);\n\n StringBuilder minKey = new StringBuilder();\n minKey.append(minNode.character);\n\n while (minNode.value == null) {\n minNode = minNode.middle;\n\n while (minNode.left != null) {\n minNode = minNode.left;\n }\n minKey.append(minNode.character);\n }\n\n return minKey.toString();\n }\n\n private Node min(Node node) {\n if (node.left == null) {\n return node;\n }\n\n return min(node.left);\n }\n\n public String max() {\n if (isEmpty()) {\n return null;\n }\n\n Node maxNode = max(root);\n\n StringBuilder maxKey = new StringBuilder();\n maxKey.append(maxNode.character);\n\n // Verify if size is different than 1 to avoid getting max key prefixes instead of the max key\n while (maxNode.size != 1 || maxNode.value == null) {\n maxNode = maxNode.middle;\n\n while (maxNode.right != null) {\n maxNode = maxNode.right;\n }\n maxKey.append(maxNode.character);\n }\n\n return maxKey.toString();\n }\n\n private Node max(Node node) {\n if (node.right == null) {\n return node;\n }\n\n return max(node.right);\n }\n\n public void deleteMin() {\n if (isEmpty()) {\n return;\n }\n\n String minKey = min();\n delete(minKey);\n }\n\n public void deleteMax() {\n if (isEmpty()) {\n return;\n }\n\n String maxKey = max();\n delete(maxKey);\n }\n\n }\n\n public static void main(String[] args) {\n Exercise8_OrderedOperationsForTries orderedOperationsForTries = new Exercise8_OrderedOperationsForTries();\n orderedOperationsForTries.trieTests();\n orderedOperationsForTries.tstTests();\n }\n\n private void trieTests() {\n StdOut.println(\"********Trie tests********\");\n TrieOrdered trieOrdered = new TrieOrdered<>();\n\n trieOrdered.put(\"Rene\", 0);\n trieOrdered.put(\"Re\", 1);\n trieOrdered.put(\"Algorithms\", 2);\n trieOrdered.put(\"Algo\", 3);\n trieOrdered.put(\"Algor\", 4);\n trieOrdered.put(\"Tree\", 5);\n trieOrdered.put(\"Trie\", 6);\n trieOrdered.put(\"TST\", 7);\n trieOrdered.put(\"Trie123\", 8);\n\n StdOut.println(\"Floor of Re: \" + trieOrdered.floor(\"Re\"));\n StdOut.println(\"Expected: Re\");\n StdOut.println(\"Floor of Algori: \" + trieOrdered.floor(\"Algori\"));\n StdOut.println(\"Expected: Algor\");\n StdOut.println(\"Floor of Ball: \" + trieOrdered.floor(\"Ball\"));\n StdOut.println(\"Expected: Algorithms\");\n StdOut.println(\"Floor of Tarjan: \" + trieOrdered.floor(\"Tarjan\"));\n StdOut.println(\"Expected: TST\");\n StdOut.println(\"Floor of AA: \" + trieOrdered.floor(\"AA\"));\n StdOut.println(\"Expected: null\");\n StdOut.println(\"Floor of Zoom: \" + trieOrdered.floor(\"Zoom\"));\n StdOut.println(\"Expected: Trie123\");\n StdOut.println(\"Floor of TAB: \" + trieOrdered.floor(\"TAB\"));\n StdOut.println(\"Expected: Rene\");\n\n StdOut.println(\"\\nCeiling of Re: \" + trieOrdered.ceiling(\"Re\"));\n StdOut.println(\"Expected: Re\");\n StdOut.println(\"Ceiling of Algori: \" + trieOrdered.ceiling(\"Algori\"));\n StdOut.println(\"Expected: Algorithms\");\n StdOut.println(\"Ceiling of Ball: \" + trieOrdered.ceiling(\"Ball\"));\n StdOut.println(\"Expected: Re\");\n StdOut.println(\"Ceiling of Tarjan: \" + trieOrdered.ceiling(\"Tarjan\"));\n StdOut.println(\"Expected: Tree\");\n StdOut.println(\"Ceiling of AA: \" + trieOrdered.ceiling(\"AA\"));\n StdOut.println(\"Expected: Algo\");\n StdOut.println(\"Ceiling of Zoom: \" + trieOrdered.ceiling(\"Zoom\"));\n StdOut.println(\"Expected: null\");\n StdOut.println(\"Ceiling of Ruby: \" + trieOrdered.ceiling(\"Ruby\"));\n StdOut.println(\"Expected: TST\");\n\n StdOut.println(\"\\nSelect 0: \" + trieOrdered.select(0));\n StdOut.println(\"Expected: Algo\");\n StdOut.println(\"Select 3: \" + trieOrdered.select(3));\n StdOut.println(\"Expected: Re\");\n StdOut.println(\"Select 2: \" + trieOrdered.select(2));\n StdOut.println(\"Expected: Algorithms\");\n StdOut.println(\"Select 5: \" + trieOrdered.select(5));\n StdOut.println(\"Expected: TST\");\n StdOut.println(\"Select 8: \" + trieOrdered.select(8));\n StdOut.println(\"Expected: Trie123\");\n\n StdOut.println(\"\\nRank of R: \" + trieOrdered.rank(\"R\"));\n StdOut.println(\"Expected: 3\");\n StdOut.println(\"Rank of Re: \" + trieOrdered.rank(\"Re\"));\n StdOut.println(\"Expected: 3\");\n StdOut.println(\"Rank of A: \" + trieOrdered.rank(\"A\"));\n StdOut.println(\"Expected: 0\");\n StdOut.println(\"Rank of Algo: \" + trieOrdered.rank(\"Algo\"));\n StdOut.println(\"Expected: 0\");\n StdOut.println(\"Rank of Algori: \" + trieOrdered.rank(\"Algori\"));\n StdOut.println(\"Expected: 2\");\n StdOut.println(\"Rank of Algorithms: \" + trieOrdered.rank(\"Algorithms\"));\n StdOut.println(\"Expected: 2\");\n StdOut.println(\"Rank of Tarjan: \" + trieOrdered.rank(\"Tarjan\"));\n StdOut.println(\"Expected: 6\");\n StdOut.println(\"Rank of Trie123: \" + trieOrdered.rank(\"Trie123\"));\n StdOut.println(\"Expected: 8\");\n StdOut.println(\"Rank of Zoom: \" + trieOrdered.rank(\"Zoom\"));\n StdOut.println(\"Expected: 9\");\n\n StdOut.println(\"\\nMin key: \" + trieOrdered.min());\n StdOut.println(\"Expected: Algo\");\n\n StdOut.println(\"\\nMax key: \" + trieOrdered.max());\n StdOut.println(\"Expected: Trie123\");\n\n StdOut.println(\"\\nKeys after deleteMin():\");\n trieOrdered.deleteMin();\n\n for (String key : trieOrdered.keys()) {\n StdOut.println(key);\n }\n\n StdOut.println(\"\\nExpected:\\n\" +\n \"Algor\\n\" +\n \"Algorithms\\n\" +\n \"Re\\n\" +\n \"Rene\\n\" +\n \"TST\\n\" +\n \"Tree\\n\" +\n \"Trie\\n\" +\n \"Trie123\");\n\n StdOut.println(\"\\nKeys after deleteMax():\");\n trieOrdered.deleteMax();\n\n for (String key : trieOrdered.keys()) {\n StdOut.println(key);\n }\n\n StdOut.println(\"\\nExpected:\\n\" +\n \"Algor\\n\" +\n \"Algorithms\\n\" +\n \"Re\\n\" +\n \"Rene\\n\" +\n \"TST\\n\" +\n \"Tree\\n\" +\n \"Trie\");\n }\n\n private void tstTests() {\n StdOut.println(\"\\n********Ternary Search Trie tests********\");\n TernarySearchTrieOrdered ternarySearchTrieOrdered = new TernarySearchTrieOrdered<>();\n\n ternarySearchTrieOrdered.put(\"Rene\", 0);\n ternarySearchTrieOrdered.put(\"Re\", 1);\n ternarySearchTrieOrdered.put(\"Algorithms\", 2);\n ternarySearchTrieOrdered.put(\"Algo\", 3);\n ternarySearchTrieOrdered.put(\"Algor\", 4);\n ternarySearchTrieOrdered.put(\"Tree\", 5);\n ternarySearchTrieOrdered.put(\"Trie\", 6);\n ternarySearchTrieOrdered.put(\"TST\", 7);\n ternarySearchTrieOrdered.put(\"Trie123\", 8);\n\n StdOut.println(\"Floor of Re: \" + ternarySearchTrieOrdered.floor(\"Re\"));\n StdOut.println(\"Expected: Re\");\n StdOut.println(\"Floor of Algori: \" + ternarySearchTrieOrdered.floor(\"Algori\"));\n StdOut.println(\"Expected: Algor\");\n StdOut.println(\"Floor of Ball: \" + ternarySearchTrieOrdered.floor(\"Ball\"));\n StdOut.println(\"Expected: Algorithms\");\n StdOut.println(\"Floor of Tarjan: \" + ternarySearchTrieOrdered.floor(\"Tarjan\"));\n StdOut.println(\"Expected: TST\");\n StdOut.println(\"Floor of AA: \" + ternarySearchTrieOrdered.floor(\"AA\"));\n StdOut.println(\"Expected: null\");\n StdOut.println(\"Floor of Zoom: \" + ternarySearchTrieOrdered.floor(\"Zoom\"));\n StdOut.println(\"Expected: Trie123\");\n StdOut.println(\"Floor of TAB: \" + ternarySearchTrieOrdered.floor(\"TAB\"));\n StdOut.println(\"Expected: Rene\");\n\n StdOut.println(\"\\nCeiling of Re: \" + ternarySearchTrieOrdered.ceiling(\"Re\"));\n StdOut.println(\"Expected: Re\");\n StdOut.println(\"Ceiling of Algori: \" + ternarySearchTrieOrdered.ceiling(\"Algori\"));\n StdOut.println(\"Expected: Algorithms\");\n StdOut.println(\"Ceiling of Ball: \" + ternarySearchTrieOrdered.ceiling(\"Ball\"));\n StdOut.println(\"Expected: Re\");\n StdOut.println(\"Ceiling of Tarjan: \" + ternarySearchTrieOrdered.ceiling(\"Tarjan\"));\n StdOut.println(\"Expected: Tree\");\n StdOut.println(\"Ceiling of AA: \" + ternarySearchTrieOrdered.ceiling(\"AA\"));\n StdOut.println(\"Expected: Algo\");\n StdOut.println(\"Ceiling of Zoom: \" + ternarySearchTrieOrdered.ceiling(\"Zoom\"));\n StdOut.println(\"Expected: null\");\n StdOut.println(\"Ceiling of Ruby: \" + ternarySearchTrieOrdered.ceiling(\"Ruby\"));\n StdOut.println(\"Expected: TST\");\n\n StdOut.println(\"\\nSelect 0: \" + ternarySearchTrieOrdered.select(0));\n StdOut.println(\"Expected: Algo\");\n StdOut.println(\"Select 3: \" + ternarySearchTrieOrdered.select(3));\n StdOut.println(\"Expected: Re\");\n StdOut.println(\"Select 2: \" + ternarySearchTrieOrdered.select(2));\n StdOut.println(\"Expected: Algorithms\");\n StdOut.println(\"Select 5: \" + ternarySearchTrieOrdered.select(5));\n StdOut.println(\"Expected: TST\");\n StdOut.println(\"Select 8: \" + ternarySearchTrieOrdered.select(8));\n StdOut.println(\"Expected: Trie123\");\n\n StdOut.println(\"\\nRank of R: \" + ternarySearchTrieOrdered.rank(\"R\"));\n StdOut.println(\"Expected: 3\");\n StdOut.println(\"Rank of Re: \" + ternarySearchTrieOrdered.rank(\"Re\"));\n StdOut.println(\"Expected: 3\");\n StdOut.println(\"Rank of A: \" + ternarySearchTrieOrdered.rank(\"A\"));\n StdOut.println(\"Expected: 0\");\n StdOut.println(\"Rank of Algo: \" + ternarySearchTrieOrdered.rank(\"Algo\"));\n StdOut.println(\"Expected: 0\");\n StdOut.println(\"Rank of Algori: \" + ternarySearchTrieOrdered.rank(\"Algori\"));\n StdOut.println(\"Expected: 2\");\n StdOut.println(\"Rank of Algorithms: \" + ternarySearchTrieOrdered.rank(\"Algorithms\"));\n StdOut.println(\"Expected: 2\");\n StdOut.println(\"Rank of Tarjan: \" + ternarySearchTrieOrdered.rank(\"Tarjan\"));\n StdOut.println(\"Expected: 6\");\n StdOut.println(\"Rank of Trie123: \" + ternarySearchTrieOrdered.rank(\"Trie123\"));\n StdOut.println(\"Expected: 8\");\n StdOut.println(\"Rank of Zoom: \" + ternarySearchTrieOrdered.rank(\"Zoom\"));\n StdOut.println(\"Expected: 9\");\n\n StdOut.println(\"\\nMin key: \" + ternarySearchTrieOrdered.min());\n StdOut.println(\"Expected: Algo\");\n\n StdOut.println(\"\\nMax key: \" + ternarySearchTrieOrdered.max());\n StdOut.println(\"Expected: Trie123\");\n\n StdOut.println(\"\\nKeys after deleteMin():\");\n ternarySearchTrieOrdered.deleteMin();\n\n for (String key : ternarySearchTrieOrdered.keys()) {\n StdOut.println(key);\n }\n\n StdOut.println(\"\\nExpected:\\n\" +\n \"Algor\\n\" +\n \"Algorithms\\n\" +\n \"Re\\n\" +\n \"Rene\\n\" +\n \"TST\\n\" +\n \"Tree\\n\" +\n \"Trie\\n\" +\n \"Trie123\");\n\n StdOut.println(\"\\nKeys after deleteMax():\");\n ternarySearchTrieOrdered.deleteMax();\n\n for (String key : ternarySearchTrieOrdered.keys()) {\n StdOut.println(key);\n }\n\n StdOut.println(\"\\nExpected:\\n\" +\n \"Algor\\n\" +\n \"Algorithms\\n\" +\n \"Re\\n\" +\n \"Rene\\n\" +\n \"TST\\n\" +\n \"Tree\\n\" +\n \"Trie\");\n }\n}\n", "support_files": [], "metadata": {"number": "5.2.8", "chapter": 5, "chapter_title": "Strings", "section": 5.2, "section_title": "Tries", "type": "Creative Problem", "code_execution": false}} {"question": "Size. Implement very eager size() (that keeps in each node the number of keys in its subtree) for TrieST and TST.", "answer": "package chapter5.section2;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 22/01/18.\n */\npublic class Exercise10_Size {\n\n @SuppressWarnings(\"unchecked\")\n public static class TrieWithSize extends Trie {\n\n private NodeWithSize root = new NodeWithSize();\n\n private static class NodeWithSize extends Node {\n private int size;\n private NodeWithSize[] next = new NodeWithSize[R];\n }\n\n public int size() {\n return size(root);\n }\n\n private int size(NodeWithSize nodeWithSize) {\n if (nodeWithSize == null) {\n return 0;\n }\n\n return nodeWithSize.size;\n }\n\n public boolean contains(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n return get(key) != null;\n }\n\n @Override\n public Value get(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n if (key.length() == 0) {\n throw new IllegalArgumentException(\"Key must have a positive length\");\n }\n\n Node node = get(root, key, 0);\n\n if (node == null) {\n return null;\n }\n return (Value) node.value;\n }\n\n private Node get(NodeWithSize node, String key, int digit) {\n if (node == null) {\n return null;\n }\n\n if (digit == key.length()) {\n return node;\n }\n\n char nextChar = key.charAt(digit); // Use digitTh key char to identify subtrie.\n return get(node.next[nextChar], key, digit + 1);\n }\n\n @Override\n public void put(String key, Value value) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n boolean isNewKey = false;\n\n if (!contains(key)) {\n isNewKey = true;\n }\n\n if (value == null) {\n delete(key);\n } else {\n root = put(root, key, value, 0, isNewKey);\n }\n }\n\n private NodeWithSize put(NodeWithSize node, String key, Value value, int digit, boolean isNewKey) {\n if (node == null) {\n node = new NodeWithSize();\n }\n\n if (isNewKey) {\n node.size = node.size + 1;\n }\n\n if (digit == key.length()) {\n node.value = value;\n return node;\n }\n\n char nextChar = key.charAt(digit); // Use digitTh key char to identify subtrie.\n node.next[nextChar] = put(node.next[nextChar], key, value, digit + 1, isNewKey);\n\n return node;\n }\n\n @Override\n public void delete(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n if (!contains(key)) {\n return;\n }\n\n root = delete(root, key, 0);\n }\n\n private NodeWithSize delete(NodeWithSize node, String key, int digit) {\n if (node == null) {\n return null;\n }\n\n node.size = node.size - 1;\n\n if (digit == key.length()) {\n node.value = null;\n } else {\n char nextChar = key.charAt(digit);\n node.next[nextChar] = delete(node.next[nextChar], key, digit + 1);\n }\n\n if (node.value != null) {\n return node;\n }\n\n for (char nextChar = 0; nextChar < R; nextChar++) {\n if (node.next[nextChar] != null) {\n return node;\n }\n }\n\n return null;\n }\n }\n\n public static class TernarySearchTrieWithSize extends TernarySearchTrie {\n\n private int size;\n private NodeWithSize root;\n\n public class NodeWithSize extends Node {\n private int size;\n\n private NodeWithSize left;\n private NodeWithSize middle;\n private NodeWithSize right;\n }\n\n public int size() {\n return size;\n }\n\n public boolean contains(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n return get(key) != null;\n }\n\n @Override\n public Value get(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n if (key.length() == 0) {\n throw new IllegalArgumentException(\"Key must have a positive length\");\n }\n\n NodeWithSize node = get(root, key, 0);\n\n if (node == null) {\n return null;\n }\n return node.value;\n }\n\n private NodeWithSize get(NodeWithSize node, String key, int digit) {\n if (node == null) {\n return null;\n }\n\n char currentChar = key.charAt(digit);\n\n if (currentChar < node.character) {\n return get(node.left, key, digit);\n } else if (currentChar > node.character) {\n return get(node.right, key, digit);\n } else if (digit < key.length() - 1) {\n return get(node.middle, key, digit + 1);\n } else {\n return node;\n }\n }\n\n @Override\n public void put(String key, Value value) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n if (value == null) {\n delete(key);\n return;\n }\n\n boolean isNewKey = false;\n\n if (!contains(key)) {\n isNewKey = true;\n size++;\n }\n\n root = put(root, key, value, 0, isNewKey);\n }\n\n private NodeWithSize put(NodeWithSize node, String key, Value value, int digit, boolean isNewKey) {\n char currentChar = key.charAt(digit);\n\n if (node == null) {\n node = new NodeWithSize();\n node.character = currentChar;\n }\n\n if (currentChar < node.character) {\n node.left = put(node.left, key, value, digit, isNewKey);\n } else if (currentChar > node.character) {\n node.right = put(node.right, key, value, digit, isNewKey);\n } else if (digit < key.length() - 1) {\n node.middle = put(node.middle, key, value, digit + 1, isNewKey);\n\n if (isNewKey) {\n node.size = node.size + 1;\n }\n } else {\n node.value = value;\n\n if (isNewKey) {\n node.size = node.size + 1;\n }\n }\n\n return node;\n }\n\n public void delete(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n if (!contains(key)) {\n return;\n }\n\n root = delete(root, key, 0);\n size--;\n }\n\n private NodeWithSize delete(NodeWithSize node, String key, int digit) {\n if (node == null) {\n return null;\n }\n\n if (digit == key.length() - 1) {\n node.size = node.size - 1;\n node.value = null;\n } else {\n char nextChar = key.charAt(digit);\n\n if (nextChar < node.character) {\n node.left = delete(node.left, key, digit);\n } else if (nextChar > node.character) {\n node.right = delete(node.right, key, digit);\n } else {\n node.size = node.size - 1;\n node.middle = delete(node.middle, key, digit + 1);\n }\n }\n\n if (node.size == 0) {\n if (node.left == null && node.right == null) {\n return null;\n } else if (node.left == null) {\n return node.right;\n } else if (node.right == null) {\n return node.left;\n } else {\n NodeWithSize aux = node;\n node = min(aux.right);\n node.right = deleteMin(aux.right);\n node.left = aux.left;\n }\n }\n\n return node;\n }\n\n private NodeWithSize min(NodeWithSize node) {\n if (node.left == null) {\n return node;\n }\n\n return min(node.left);\n }\n\n private NodeWithSize deleteMin(NodeWithSize node) {\n if (node.left == null) {\n return node.right;\n }\n\n node.left = deleteMin(node.left);\n return node;\n }\n }\n\n // Considering ' ' as root node when printing\n private void printNodeSizes(TrieWithSize.NodeWithSize currentNode, char currentChar) {\n if (currentNode == null) {\n return;\n }\n\n StdOut.println(\"Node character: \" + currentChar + \" Size: \" + currentNode.size);\n\n for (char nextChar = 0; nextChar < TrieWithSize.R; nextChar++) {\n if (currentNode.next[nextChar] != null) {\n printNodeSizes(currentNode.next[nextChar], nextChar);\n }\n }\n }\n\n private void printNodeSizes(TernarySearchTrieWithSize.NodeWithSize currentNode) {\n if (currentNode == null) {\n return;\n }\n\n printNodeSizes(currentNode.left);\n\n StdOut.println(\"Node character: \" + currentNode.character + \" Size: \" + currentNode.size);\n printNodeSizes(currentNode.middle);\n printNodeSizes(currentNode.right);\n }\n\n public static void main(String[] args) {\n Exercise10_Size exercise10_size = new Exercise10_Size();\n\n StdOut.println(\"********Trie tests********\");\n TrieWithSize trieWithSize = new TrieWithSize<>();\n\n trieWithSize.put(\"Rene\", 0);\n trieWithSize.put(\"Re\", 1);\n trieWithSize.put(\"Algorithms\", 2);\n trieWithSize.put(\"Algo\", 3);\n trieWithSize.put(\"Algor\", 4);\n trieWithSize.put(\"Tree\", 5);\n trieWithSize.put(\"Trie\", 6);\n trieWithSize.put(\"TST\", 7);\n\n StdOut.println(\"Size of Trie: \" + trieWithSize.size());\n StdOut.println(\"Expected: 8\");\n\n StdOut.println();\n exercise10_size.printNodeSizes(trieWithSize.root, ' ');\n\n StdOut.println(\"\\nExpected:\\n\" +\n \"Node character: Size: 8\\n\" +\n \"Node character: A Size: 3\\n\" +\n \"Node character: l Size: 3\\n\" +\n \"Node character: g Size: 3\\n\" +\n \"Node character: o Size: 3\\n\" +\n \"Node character: r Size: 2\\n\" +\n \"Node character: i Size: 1\\n\" +\n \"Node character: t Size: 1\\n\" +\n \"Node character: h Size: 1\\n\" +\n \"Node character: m Size: 1\\n\" +\n \"Node character: s Size: 1\\n\" +\n \"Node character: R Size: 2\\n\" +\n \"Node character: e Size: 2\\n\" +\n \"Node character: n Size: 1\\n\" +\n \"Node character: e Size: 1\\n\" +\n \"Node character: T Size: 3\\n\" +\n \"Node character: S Size: 1\\n\" +\n \"Node character: T Size: 1\\n\" +\n \"Node character: r Size: 2\\n\" +\n \"Node character: e Size: 1\\n\" +\n \"Node character: e Size: 1\\n\" +\n \"Node character: i Size: 1\\n\" +\n \"Node character: e Size: 1\");\n\n StdOut.println(\"\\nDeleted Trie key\");\n trieWithSize.delete(\"Trie\");\n\n exercise10_size.printNodeSizes(trieWithSize.root, ' ');\n StdOut.println(\"Expected: no 'i' and 'e' nodes after 'Tr'\");\n\n StdOut.println(\"\\nSize of Trie: \" + trieWithSize.size());\n StdOut.println(\"Expected: 7\");\n\n StdOut.println(\"\\nDeleted Re key\");\n trieWithSize.delete(\"Re\");\n\n exercise10_size.printNodeSizes(trieWithSize.root, ' ');\n StdOut.println(\"Expected: 'R' and 'e' with size 1\");\n\n StdOut.println(\"\\nSize of Trie: \" + trieWithSize.size());\n StdOut.println(\"Expected: 6\");\n\n StdOut.println(\"\\nDeleted Algo key\");\n trieWithSize.delete(\"Algo\");\n\n exercise10_size.printNodeSizes(trieWithSize.root, ' ');\n StdOut.println(\"Expected: 'A', 'l', 'g', 'o' and 'r' nodes with size 2\");\n\n StdOut.println(\"\\nSize of Trie: \" + trieWithSize.size());\n StdOut.println(\"Expected: 5\");\n\n StdOut.println(\"\\n********Ternary Search Trie tests********\");\n TernarySearchTrieWithSize tstWithSize = new TernarySearchTrieWithSize<>();\n\n tstWithSize.put(\"Rene\", 0);\n tstWithSize.put(\"Re\", 1);\n tstWithSize.put(\"Algorithms\", 2);\n tstWithSize.put(\"Algo\", 3);\n tstWithSize.put(\"Algor\", 4);\n tstWithSize.put(\"Tree\", 5);\n tstWithSize.put(\"Trie\", 6);\n tstWithSize.put(\"TST\", 7);\n\n StdOut.println(\"Size of TST: \" + tstWithSize.size());\n StdOut.println(\"Expected: 8\");\n\n StdOut.println();\n exercise10_size.printNodeSizes(tstWithSize.root);\n\n StdOut.println(\"\\nExpected:\\n\" +\n \"Node character: A Size: 3\\n\" +\n \"Node character: l Size: 3\\n\" +\n \"Node character: g Size: 3\\n\" +\n \"Node character: o Size: 3\\n\" +\n \"Node character: r Size: 2\\n\" +\n \"Node character: i Size: 1\\n\" +\n \"Node character: t Size: 1\\n\" +\n \"Node character: h Size: 1\\n\" +\n \"Node character: m Size: 1\\n\" +\n \"Node character: s Size: 1\\n\" +\n \"Node character: R Size: 2\\n\" +\n \"Node character: e Size: 2\\n\" +\n \"Node character: n Size: 1\\n\" +\n \"Node character: e Size: 1\\n\" +\n \"Node character: T Size: 3\\n\" +\n \"Node character: S Size: 1\\n\" +\n \"Node character: T Size: 1\\n\" +\n \"Node character: r Size: 2\\n\" +\n \"Node character: e Size: 1\\n\" +\n \"Node character: e Size: 1\\n\" +\n \"Node character: i Size: 1\\n\" +\n \"Node character: e Size: 1\");\n\n StdOut.println(\"\\nDeleted Trie key\");\n tstWithSize.delete(\"Trie\");\n\n exercise10_size.printNodeSizes(tstWithSize.root);\n StdOut.println(\"Expected: no 'i' and 'e' nodes after 'Tr'\");\n\n StdOut.println(\"\\nSize of TST: \" + tstWithSize.size());\n StdOut.println(\"Expected: 7\");\n\n StdOut.println(\"\\nDeleted Re key\");\n tstWithSize.delete(\"Re\");\n\n exercise10_size.printNodeSizes(tstWithSize.root);\n StdOut.println(\"Expected: 'R' and 'e' with size 1\");\n\n StdOut.println(\"\\nSize of TST: \" + tstWithSize.size());\n StdOut.println(\"Expected: 6\");\n\n StdOut.println(\"\\nDeleted Algo key\");\n tstWithSize.delete(\"Algo\");\n\n exercise10_size.printNodeSizes(tstWithSize.root);\n StdOut.println(\"Expected: 'A', 'l', 'g', 'o' and 'r' nodes with size 2\");\n\n StdOut.println(\"\\nSize of TST: \" + tstWithSize.size());\n StdOut.println(\"Expected: 5\");\n }\n}\n", "support_files": [], "metadata": {"number": "5.2.10", "chapter": 5, "chapter_title": "Strings", "section": 5.2, "section_title": "Tries", "type": "Creative Problem", "code_execution": false}} {"question": "Hybrid TST with R2-way branching at the root. Add code to TST to do multiway branching at the first two levels, as described in the text.", "answer": "package chapter5.section2;\n\nimport chapter1.section3.Queue;\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.StringJoiner;\n\n/**\n * Created by Rene Argento on 05/02/18.\n */\npublic class Exercise13_HybridTSTWithR2BranchingAtTheRoot {\n\n @SuppressWarnings(\"unchecked\")\n public class HybridTernarySearchTrie {\n\n private static final int R = 256;\n private int size;\n private TernarySearchTrie[][] ternarySearchTries;\n private static final int NULL_CHAR_INDEX = R;\n\n public HybridTernarySearchTrie() {\n // Columns have size R + 1 because there may be keys of length 1, which are equivalent to\n // row = character1, column = R\n ternarySearchTries = new TernarySearchTrie[R][R + 1];\n\n for (int tst1 = 0; tst1 < R; tst1++) {\n for (int tst2 = 0; tst2 <= R; tst2++) {\n ternarySearchTries[tst1][tst2] = new TernarySearchTrie<>();\n }\n }\n }\n\n private TernarySearchTrie getTernarySearchTrie(String key) {\n TernarySearchTrie ternarySearchTrie;\n\n char character1 = key.charAt(0);\n\n if (key.length() == 1) {\n ternarySearchTrie = ternarySearchTries[character1][NULL_CHAR_INDEX];\n } else {\n char character2 = key.charAt(1);\n ternarySearchTrie = ternarySearchTries[character1][character2];\n }\n\n return ternarySearchTrie;\n }\n\n public int size() {\n return size;\n }\n\n public boolean isEmpty() {\n return size() == 0;\n }\n\n public boolean contains(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n return get(key) != null;\n }\n\n public Value get(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n if (key.length() == 0) {\n throw new IllegalArgumentException(\"Key must have a positive length\");\n }\n\n TernarySearchTrie ternarySearchTrie = getTernarySearchTrie(key);\n return ternarySearchTrie.get(key);\n }\n\n public void put(String key, Value value) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n if (value == null) {\n delete(key);\n return;\n }\n\n if (!contains(key)) {\n size++;\n }\n\n TernarySearchTrie ternarySearchTrie = getTernarySearchTrie(key);\n ternarySearchTrie.put(key, value);\n }\n\n public void delete(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n if (!contains(key)) {\n return;\n }\n\n TernarySearchTrie ternarySearchTrie = getTernarySearchTrie(key);\n ternarySearchTrie.delete(key);\n size--;\n }\n\n public Iterable keys() {\n Queue keys = new Queue<>();\n\n for (char tst1 = 0; tst1 < R; tst1++) {\n\n // First add key of size 1\n getAllKeysInTST(tst1, NULL_CHAR_INDEX, keys);\n\n for (char tst2 = 0; tst2 < R; tst2++) {\n getAllKeysInTST(tst1, tst2, keys);\n }\n }\n\n return keys;\n }\n\n private void getAllKeysInTST(int index1, int index2, Queue keys) {\n\n if (ternarySearchTries[index1][index2].size() > 0) {\n for (String key : ternarySearchTries[index1][index2].keys()) {\n keys.enqueue(key);\n }\n }\n }\n\n public Iterable keysWithPrefix(String prefix) {\n if (prefix == null) {\n throw new IllegalArgumentException(\"Prefix cannot be null\");\n }\n\n Queue keysWithPrefix = new Queue<>();\n\n if (prefix.length() == 1) {\n char character1 = prefix.charAt(0);\n\n // Check if key of size 1 is in the hybrid ternary search trie\n getAllKeysInTST(character1, NULL_CHAR_INDEX, keysWithPrefix);\n\n // Also check for keys of size 2 or higher\n for (char tst = 0; tst < R; tst++) {\n getAllKeysInTST(character1, tst, keysWithPrefix);\n }\n } else if (prefix.length() > 1) {\n char character1 = prefix.charAt(0);\n char character2 = prefix.charAt(1);\n\n getAllKeysInTST(character1, character2, keysWithPrefix);\n }\n\n return keysWithPrefix;\n }\n\n public Iterable keysThatMatch(String pattern) {\n if (pattern == null) {\n throw new IllegalArgumentException(\"Pattern cannot be null\");\n }\n\n Queue keysThatMatch = new Queue<>();\n\n if (pattern.length() == 1) {\n char character = pattern.charAt(0);\n\n if (character != '.') {\n getAllKeysInTST(character, NULL_CHAR_INDEX, keysThatMatch);\n } else {\n for (char tst = 0; tst < R; tst++) {\n getAllKeysInTST(tst, NULL_CHAR_INDEX, keysThatMatch);\n }\n }\n } else if (pattern.length() > 1) {\n char character1 = pattern.charAt(0);\n char character2 = pattern.charAt(1);\n\n if (character1 != '.' && character2 != '.') {\n TernarySearchTrie ternarySearchTrie = getTernarySearchTrie(pattern);\n\n for (String key : ternarySearchTrie.keysThatMatch(pattern)) {\n keysThatMatch.enqueue(key);\n }\n } else if (character1 == '.' && character2 != '.') {\n\n for (char tst = 0; tst < R; tst++) {\n TernarySearchTrie ternarySearchTrie = ternarySearchTries[tst][character2];\n\n for (String key : ternarySearchTrie.keysThatMatch(pattern)) {\n keysThatMatch.enqueue(key);\n }\n }\n } else if (character1 != '.' && character2 == '.') {\n\n for (char tst = 0; tst < R; tst++) {\n TernarySearchTrie ternarySearchTrie = ternarySearchTries[character1][tst];\n\n for (String key : ternarySearchTrie.keysThatMatch(pattern)) {\n keysThatMatch.enqueue(key);\n }\n }\n } else {\n\n for (char tst1 = 0; tst1 < R; tst1++) {\n for (int tst2 = 0; tst2 < R; tst2++) {\n TernarySearchTrie ternarySearchTrie = ternarySearchTries[tst1][tst2];\n\n for (String key : ternarySearchTrie.keysThatMatch(pattern)) {\n keysThatMatch.enqueue(key);\n }\n }\n }\n }\n }\n\n return keysThatMatch;\n }\n\n public String longestPrefixOf(String query) {\n if (query == null) {\n throw new IllegalArgumentException(\"Query cannot be null\");\n }\n\n TernarySearchTrie ternarySearchTrie = getTernarySearchTrie(query);\n return ternarySearchTrie.longestPrefixOf(query);\n }\n\n public String floor(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n if (key.length() == 0) {\n return key;\n }\n\n String floorKey;\n\n char character1 = key.charAt(0);\n char character2;\n\n if (key.length() == 1) {\n character2 = NULL_CHAR_INDEX;\n } else {\n character2 = key.charAt(1);\n }\n\n boolean mustBeEqualDigit = true;\n\n for (char tst1 = character1; true; tst1--) {\n\n if (!mustBeEqualDigit) {\n character2 = R - 1;\n }\n\n for (char tst2 = character2; true; tst2--) {\n TernarySearchTrie ternarySearchTrie = ternarySearchTries[tst1][tst2];\n floorKey = ternarySearchTrie.floor(key);\n\n if (floorKey != null) {\n break;\n }\n\n // Before decrementing character1 value check for key of size 1\n if (tst2 == 0) {\n TernarySearchTrie ternarySearchTrieKeySize1 = ternarySearchTries[tst1][NULL_CHAR_INDEX];\n floorKey = ternarySearchTrieKeySize1.floor(key);\n\n mustBeEqualDigit = false;\n break;\n }\n }\n\n // tst1 value never becomes less than zero in the for loop, so we need this extra validation\n if (tst1 == 0) {\n break;\n }\n\n if (floorKey != null) {\n break;\n }\n }\n\n return floorKey;\n }\n\n public String ceiling(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n if (key.length() == 0) {\n return key;\n }\n\n String ceilingKey = null;\n\n char character1 = key.charAt(0);\n char character2;\n\n if (key.length() == 1) {\n character2 = NULL_CHAR_INDEX;\n } else {\n character2 = key.charAt(1);\n }\n\n boolean mustBeEqualDigit = true;\n\n for (char tst1 = character1; tst1 < R; tst1++) {\n\n if (!mustBeEqualDigit) {\n character2 = 0;\n }\n\n for (char tst2 = character2; tst2 < R; tst2++) {\n\n // Before beginning to check character2 value, check for key of size 1\n if (tst2 == 0) {\n TernarySearchTrie ternarySearchTrieKeySize1 = ternarySearchTries[tst1][NULL_CHAR_INDEX];\n ceilingKey = ternarySearchTrieKeySize1.ceiling(key);\n\n if (ceilingKey != null) {\n break;\n }\n }\n\n TernarySearchTrie ternarySearchTrie = ternarySearchTries[tst1][tst2];\n ceilingKey = ternarySearchTrie.ceiling(key);\n\n if (ceilingKey != null) {\n break;\n }\n\n if (tst2 == R - 1) {\n mustBeEqualDigit = false;\n }\n }\n\n if (ceilingKey != null) {\n break;\n }\n }\n\n return ceilingKey;\n }\n\n public String select(int index) {\n if (index < 0 || index >= size()) {\n throw new IllegalArgumentException(\"Index cannot be negative and must be lower than TST size\");\n }\n\n String targetKey = null;\n int currentIndex = 0;\n\n for (char tst1 = 0; tst1 < R; tst1++) {\n for (char tst2 = 0; tst2 < R; tst2++) {\n\n // Before beginning to check character2 value, check for key of size 1\n if (tst2 == 0) {\n TernarySearchTrie ternarySearchTrieKeySize1 = ternarySearchTries[tst1][NULL_CHAR_INDEX];\n\n int size = ternarySearchTrieKeySize1.size();\n\n if (currentIndex + size > index) {\n int targetIndex = index - currentIndex;\n targetKey = ternarySearchTrieKeySize1.select(targetIndex);\n break;\n }\n\n currentIndex += size;\n }\n\n TernarySearchTrie ternarySearchTrie = ternarySearchTries[tst1][tst2];\n\n int size = ternarySearchTrie.size();\n\n if (currentIndex + size > index) {\n int targetIndex = index - currentIndex;\n targetKey = ternarySearchTrie.select(targetIndex);\n break;\n }\n\n currentIndex += size;\n }\n\n if (targetKey != null) {\n break;\n }\n }\n\n return targetKey;\n }\n\n public int rank(String key) {\n if (key == null) {\n throw new IllegalArgumentException(\"Key cannot be null\");\n }\n\n if (key.length() == 0) {\n return 0;\n }\n\n char character1 = key.charAt(0);\n char character2;\n\n TernarySearchTrie keyTernarySearchTrie;\n boolean canDecreaseCharacterValue = true;\n\n if (key.length() == 1) {\n character2 = NULL_CHAR_INDEX;\n\n keyTernarySearchTrie = ternarySearchTries[character1][character2];\n\n if (character1 > 0) {\n character1--;\n } else {\n canDecreaseCharacterValue = false;\n }\n } else {\n character2 = key.charAt(1);\n\n keyTernarySearchTrie = ternarySearchTries[character1][character2];\n\n if (character2 > 0) {\n character2--;\n } else if (character1 > 0) {\n character1--;\n character2 = R - 1;\n } else {\n canDecreaseCharacterValue = false;\n }\n }\n\n // If there are no keys with a prefix lower than the current key we just have to check its TST\n if (!canDecreaseCharacterValue) {\n return keyTernarySearchTrie.rank(key);\n }\n\n int totalSize = 0;\n boolean mustBeEqualDigit = true;\n\n for (char tst1 = character1; true; tst1--) {\n\n if (!mustBeEqualDigit) {\n character2 = R - 1;\n }\n\n for (char tst2 = character2; true; tst2--) {\n TernarySearchTrie ternarySearchTrie = ternarySearchTries[tst1][tst2];\n totalSize += ternarySearchTrie.size();\n\n // Before decrementing character1 value check for key of size 1\n if (tst2 == 0) {\n TernarySearchTrie ternarySearchTrieKeySize1 = ternarySearchTries[tst1][NULL_CHAR_INDEX];\n totalSize += ternarySearchTrieKeySize1.size();\n\n mustBeEqualDigit = false;\n break;\n }\n }\n\n // tst1 value never becomes less than zero in the for loop, so we need this extra validation\n if (tst1 == 0) {\n break;\n }\n }\n\n return totalSize + keyTernarySearchTrie.rank(key);\n }\n\n public String min() {\n if (isEmpty()) {\n return null;\n }\n\n for (char tst1 = 0; tst1 < R; tst1++) {\n for (char tst2 = 0; tst2 < R; tst2++) {\n\n // Before beginning to check character2 value, check for key of size 1\n if (tst2 == 0) {\n TernarySearchTrie ternarySearchTrieKeySize1 = ternarySearchTries[tst1][NULL_CHAR_INDEX];\n if (!ternarySearchTrieKeySize1.isEmpty()) {\n return ternarySearchTrieKeySize1.min();\n }\n }\n\n TernarySearchTrie ternarySearchTrie = ternarySearchTries[tst1][tst2];\n if (!ternarySearchTrie.isEmpty()) {\n return ternarySearchTrie.min();\n }\n }\n }\n\n return null;\n }\n\n public String max() {\n if (isEmpty()) {\n return null;\n }\n\n for (char tst1 = R - 1; true; tst1--) {\n for (char tst2 = R - 1; true; tst2--) {\n\n TernarySearchTrie ternarySearchTrie = ternarySearchTries[tst1][tst2];\n if (!ternarySearchTrie.isEmpty()) {\n return ternarySearchTrie.max();\n }\n\n // Before decrementing character1 value check for key of size 1\n if (tst2 == 0) {\n TernarySearchTrie ternarySearchTrieKeySize1 = ternarySearchTries[tst1][NULL_CHAR_INDEX];\n if (!ternarySearchTrieKeySize1.isEmpty()) {\n return ternarySearchTrieKeySize1.max();\n }\n\n break;\n }\n }\n\n // tst1 value never becomes less than zero in the for loop, so we need this extra validation\n if (tst1 == 0) {\n break;\n }\n }\n\n return null;\n }\n\n public void deleteMin() {\n if (isEmpty()) {\n return;\n }\n\n String minKey = min();\n delete(minKey);\n }\n\n public void deleteMax() {\n if (isEmpty()) {\n return;\n }\n\n String maxKey = max();\n delete(maxKey);\n }\n }\n\n public static void main(String[] args) {\n HybridTernarySearchTrie hybridTernarySearchTrie =\n new Exercise13_HybridTSTWithR2BranchingAtTheRoot().new HybridTernarySearchTrie<>();\n\n StdOut.println(\"Size: \" + hybridTernarySearchTrie.size());\n StdOut.println(\"Expected: 0\");\n\n // Put tests\n hybridTernarySearchTrie.put(\"Rene\", 0);\n hybridTernarySearchTrie.put(\"Re\", 1);\n hybridTernarySearchTrie.put(\"Re\", 10);\n hybridTernarySearchTrie.put(\"Algorithms\", 2);\n hybridTernarySearchTrie.put(\"Algo\", 3);\n hybridTernarySearchTrie.put(\"Algor\", 4);\n hybridTernarySearchTrie.put(\"Tree\", 5);\n hybridTernarySearchTrie.put(\"Trie\", 6);\n hybridTernarySearchTrie.put(\"TST\", 7);\n hybridTernarySearchTrie.put(\"Trie123\", 8);\n hybridTernarySearchTrie.put(\"Z-Function\", 9);\n hybridTernarySearchTrie.put(\"B\", 11);\n hybridTernarySearchTrie.put(\"Binary\", 12);\n\n StdOut.println(\"\\nSize: \" + hybridTernarySearchTrie.size());\n StdOut.println(\"Expected: 12\");\n\n // Get tests\n StdOut.println(\"\\nGet Re: \" + hybridTernarySearchTrie.get(\"Re\"));\n StdOut.println(\"Expected: 10\");\n StdOut.println(\"Get Algorithms: \" + hybridTernarySearchTrie.get(\"Algorithms\"));\n StdOut.println(\"Expected: 2\");\n StdOut.println(\"Get Trie123: \" + hybridTernarySearchTrie.get(\"Trie123\"));\n StdOut.println(\"Expected: 8\");\n StdOut.println(\"Get Algori: \" + hybridTernarySearchTrie.get(\"Algori\"));\n StdOut.println(\"Expected: null\");\n StdOut.println(\"Get Zooom: \" + hybridTernarySearchTrie.get(\"Zooom\"));\n StdOut.println(\"Expected: null\");\n\n // Keys() test\n StdOut.println(\"\\nAll keys\");\n for (String key : hybridTernarySearchTrie.keys()) {\n StdOut.println(key);\n }\n\n // Keys with prefix tests\n StdOut.println(\"\\nKeys with prefix Alg\");\n StringJoiner keysWithPrefix1 = new StringJoiner(\" \");\n\n for (String key : hybridTernarySearchTrie.keysWithPrefix(\"Alg\")) {\n keysWithPrefix1.add(key);\n }\n StdOut.println(keysWithPrefix1.toString());\n StdOut.println(\"Expected: Algo Algor Algorithms\");\n\n StdOut.println(\"\\nKeys with prefix T\");\n StringJoiner keysWithPrefix2 = new StringJoiner(\" \");\n\n for (String key : hybridTernarySearchTrie.keysWithPrefix(\"T\")) {\n keysWithPrefix2.add(key);\n }\n StdOut.println(keysWithPrefix2.toString());\n StdOut.println(\"Expected: TST Tree Trie Trie123\");\n\n StdOut.println(\"\\nKeys with prefix R\");\n StringJoiner keysWithPrefix3 = new StringJoiner(\" \");\n\n for (String key : hybridTernarySearchTrie.keysWithPrefix(\"R\")) {\n keysWithPrefix3.add(key);\n }\n StdOut.println(keysWithPrefix3.toString());\n StdOut.println(\"Expected: Re Rene\");\n\n StdOut.println(\"\\nKeys with prefix ZZZ\");\n StringJoiner keysWithPrefix4 = new StringJoiner(\" \");\n\n for (String key : hybridTernarySearchTrie.keysWithPrefix(\"ZZZ\")) {\n keysWithPrefix4.add(key);\n }\n StdOut.println(keysWithPrefix4.toString());\n StdOut.println(\"Expected: \");\n\n StdOut.println(\"\\nKeys with prefix B\");\n StringJoiner keysWithPrefix5 = new StringJoiner(\" \");\n\n for (String key : hybridTernarySearchTrie.keysWithPrefix(\"B\")) {\n keysWithPrefix5.add(key);\n }\n StdOut.println(keysWithPrefix5.toString());\n StdOut.println(\"Expected: B Binary\");\n\n // Keys that match tests\n StdOut.println(\"\\nKeys that match Alg..\");\n StringJoiner keysThatMatch1 = new StringJoiner(\"Alg..\");\n\n for (String key : hybridTernarySearchTrie.keysThatMatch(\"Alg..\")) {\n keysThatMatch1.add(key);\n }\n StdOut.println(keysThatMatch1.toString());\n StdOut.println(\"Expected: Algor\");\n\n StdOut.println(\"\\nKeys that match Re\");\n StringJoiner keysThatMatch2 = new StringJoiner(\" \");\n\n for (String key : hybridTernarySearchTrie.keysThatMatch(\"Re\")) {\n keysThatMatch2.add(key);\n }\n StdOut.println(keysThatMatch2.toString());\n StdOut.println(\"Expected: Re\");\n\n StdOut.println(\"\\nKeys that match Tr.e\");\n StringJoiner keysThatMatch3 = new StringJoiner(\" \");\n\n for (String key : hybridTernarySearchTrie.keysThatMatch(\"Tr.e\")) {\n keysThatMatch3.add(key);\n }\n StdOut.println(keysThatMatch3.toString());\n StdOut.println(\"Expected: Tree Trie\");\n\n StdOut.println(\"\\nKeys that match .\");\n StringJoiner keysThatMatch4 = new StringJoiner(\" \");\n\n for (String key : hybridTernarySearchTrie.keysThatMatch(\".\")) {\n keysThatMatch4.add(key);\n }\n StdOut.println(keysThatMatch4.toString());\n StdOut.println(\"Expected: B\");\n\n // Longest-prefix-of tests\n StdOut.println(\"\\nLongest prefix of Re: \" + hybridTernarySearchTrie.longestPrefixOf(\"Re\"));\n StdOut.println(\"Expected: Re\");\n\n StdOut.println(\"Longest prefix of Alg: \" + hybridTernarySearchTrie.longestPrefixOf(\"Alg\"));\n StdOut.println(\"Expected: \");\n\n StdOut.println(\"Longest prefix of Algori: \" + hybridTernarySearchTrie.longestPrefixOf(\"Algori\"));\n StdOut.println(\"Expected: Algor\");\n\n StdOut.println(\"Longest prefix of Trie12345: \" + hybridTernarySearchTrie.longestPrefixOf(\"Trie12345\"));\n StdOut.println(\"Expected: Trie123\");\n\n StdOut.println(\"Longest prefix of Zooom: \" + hybridTernarySearchTrie.longestPrefixOf(\"Zooom\"));\n StdOut.println(\"Expected: \");\n\n // Min tests\n StdOut.println(\"\\nMin key: \" + hybridTernarySearchTrie.min());\n StdOut.println(\"Expected: Algo\");\n\n // Max tests\n StdOut.println(\"\\nMax key: \" + hybridTernarySearchTrie.max());\n StdOut.println(\"Expected: Z-Function\");\n\n // Delete min and delete max tests\n hybridTernarySearchTrie.put(\"ABCKey\", 11);\n hybridTernarySearchTrie.put(\"ZKey\", 12);\n\n StdOut.println(\"\\nKeys after ABCKey and ZKey insert: \");\n for (String key : hybridTernarySearchTrie.keys()) {\n StdOut.println(key);\n }\n\n hybridTernarySearchTrie.deleteMin();\n\n StdOut.println(\"\\nKeys after deleteMin: \");\n for (String key : hybridTernarySearchTrie.keys()) {\n StdOut.println(key);\n }\n\n StdOut.println(\"Expected: ABCKey deleted\");\n\n hybridTernarySearchTrie.deleteMax();\n\n StdOut.println(\"\\nKeys after deleteMax: \");\n for (String key : hybridTernarySearchTrie.keys()) {\n StdOut.println(key);\n }\n\n StdOut.println(\"Expected: ZKey deleted\");\n\n // Floor tests\n StdOut.println(\"\\nFloor of Re: \" + hybridTernarySearchTrie.floor(\"Re\"));\n StdOut.println(\"Expected: Re\");\n StdOut.println(\"Floor of Algori: \" + hybridTernarySearchTrie.floor(\"Algori\"));\n StdOut.println(\"Expected: Algor\");\n StdOut.println(\"Floor of Azure: \" + hybridTernarySearchTrie.floor(\"Azure\"));\n StdOut.println(\"Expected: Algorithms\");\n StdOut.println(\"Floor of Tarjan: \" + hybridTernarySearchTrie.floor(\"Tarjan\"));\n StdOut.println(\"Expected: TST\");\n StdOut.println(\"Floor of AA: \" + hybridTernarySearchTrie.floor(\"AA\"));\n StdOut.println(\"Expected: null\");\n StdOut.println(\"Floor of Zoom: \" + hybridTernarySearchTrie.floor(\"Zoom\"));\n StdOut.println(\"Expected: Z-Function\");\n StdOut.println(\"Floor of TAB: \" + hybridTernarySearchTrie.floor(\"TAB\"));\n StdOut.println(\"Expected: Rene\");\n StdOut.println(\"Floor of Cat: \" + hybridTernarySearchTrie.floor(\"Cat\"));\n StdOut.println(\"Expected: Binary\");\n StdOut.println(\"Floor of Ball: \" + hybridTernarySearchTrie.floor(\"Ball\"));\n StdOut.println(\"Expected: B\");\n\n // Ceiling tests\n StdOut.println(\"\\nCeiling of Re: \" + hybridTernarySearchTrie.ceiling(\"Re\"));\n StdOut.println(\"Expected: Re\");\n StdOut.println(\"Ceiling of Algori: \" + hybridTernarySearchTrie.ceiling(\"Algori\"));\n StdOut.println(\"Expected: Algorithms\");\n StdOut.println(\"Ceiling of Bull: \" + hybridTernarySearchTrie.ceiling(\"Bull\"));\n StdOut.println(\"Expected: Re\");\n StdOut.println(\"Ceiling of Tarjan: \" + hybridTernarySearchTrie.ceiling(\"Tarjan\"));\n StdOut.println(\"Expected: Tree\");\n StdOut.println(\"Ceiling of AA: \" + hybridTernarySearchTrie.ceiling(\"AA\"));\n StdOut.println(\"Expected: Algo\");\n StdOut.println(\"Ceiling of Zoom: \" + hybridTernarySearchTrie.ceiling(\"Zoom\"));\n StdOut.println(\"Expected: null\");\n StdOut.println(\"Ceiling of Tro: \" + hybridTernarySearchTrie.ceiling(\"Tro\"));\n StdOut.println(\"Expected: Z-Function\");\n StdOut.println(\"Ceiling of Ruby: \" + hybridTernarySearchTrie.ceiling(\"Ruby\"));\n StdOut.println(\"Expected: TST\");\n StdOut.println(\"Ceiling of Azure: \" + hybridTernarySearchTrie.ceiling(\"Azure\"));\n StdOut.println(\"Expected: B\");\n StdOut.println(\"Ceiling of Ball: \" + hybridTernarySearchTrie.ceiling(\"Ball\"));\n StdOut.println(\"Expected: Binary\");\n\n // Select tests\n StdOut.println(\"\\nSelect 0: \" + hybridTernarySearchTrie.select(0));\n StdOut.println(\"Expected: Algo\");\n StdOut.println(\"Select 3: \" + hybridTernarySearchTrie.select(3));\n StdOut.println(\"Expected: B\");\n StdOut.println(\"Select 5: \" + hybridTernarySearchTrie.select(5));\n StdOut.println(\"Expected: Re\");\n StdOut.println(\"Select 2: \" + hybridTernarySearchTrie.select(2));\n StdOut.println(\"Expected: Algorithms\");\n StdOut.println(\"Select 7: \" + hybridTernarySearchTrie.select(7));\n StdOut.println(\"Expected: TST\");\n StdOut.println(\"Select 10: \" + hybridTernarySearchTrie.select(10));\n StdOut.println(\"Expected: Trie123\");\n StdOut.println(\"Select 11: \" + hybridTernarySearchTrie.select(11));\n StdOut.println(\"Expected: Z-Function\");\n\n // Rank tests\n StdOut.println(\"\\nRank of R: \" + hybridTernarySearchTrie.rank(\"R\"));\n StdOut.println(\"Expected: 5\");\n StdOut.println(\"Rank of Re: \" + hybridTernarySearchTrie.rank(\"Re\"));\n StdOut.println(\"Expected: 5\");\n StdOut.println(\"Rank of A: \" + hybridTernarySearchTrie.rank(\"A\"));\n StdOut.println(\"Expected: 0\");\n StdOut.println(\"Rank of Algo: \" + hybridTernarySearchTrie.rank(\"Algo\"));\n StdOut.println(\"Expected: 0\");\n StdOut.println(\"Rank of Algori: \" + hybridTernarySearchTrie.rank(\"Algori\"));\n StdOut.println(\"Expected: 2\");\n StdOut.println(\"Rank of Algorithms: \" + hybridTernarySearchTrie.rank(\"Algorithms\"));\n StdOut.println(\"Expected: 2\");\n StdOut.println(\"Rank of B: \" + hybridTernarySearchTrie.rank(\"B\"));\n StdOut.println(\"Expected: 3\");\n StdOut.println(\"Rank of Ball: \" + hybridTernarySearchTrie.rank(\"Ball\"));\n StdOut.println(\"Expected: 4\");\n StdOut.println(\"Rank of Tarjan: \" + hybridTernarySearchTrie.rank(\"Tarjan\"));\n StdOut.println(\"Expected: 8\");\n StdOut.println(\"Rank of Trie123: \" + hybridTernarySearchTrie.rank(\"Trie123\"));\n StdOut.println(\"Expected: 10\");\n StdOut.println(\"Rank of Zzoom: \" + hybridTernarySearchTrie.rank(\"Zzoom\"));\n StdOut.println(\"Expected: 12\");\n\n // Delete tests\n hybridTernarySearchTrie.delete(\"Z-Function\");\n\n StdOut.println(\"\\nKeys() after deleting Z-Function key\");\n for (String key : hybridTernarySearchTrie.keys()) {\n StdOut.println(key);\n }\n\n hybridTernarySearchTrie.delete(\"Rene\");\n\n StdOut.println(\"\\nKeys() after deleting Rene key\");\n for (String key : hybridTernarySearchTrie.keys()) {\n StdOut.println(key);\n }\n\n hybridTernarySearchTrie.delete(\"Re\");\n\n StdOut.println(\"\\nKeys() after deleting Re key\");\n for (String key : hybridTernarySearchTrie.keys()) {\n StdOut.println(key);\n }\n }\n}\n", "support_files": [], "metadata": {"number": "5.2.13", "chapter": 5, "chapter_title": "Strings", "section": 5.2, "section_title": "Tries", "type": "Creative Problem", "code_execution": false}} {"question": "Spell checking. Write a TST client SpellChecker that takes as command-line argument the name of a file containing a dictionary of words in the English language, and then reads a string from standard input and prints out any word that is not in the dictionary. Use a string set.", "answer": "package chapter5.section2;\n\nimport edu.princeton.cs.algs4.StdIn;\nimport edu.princeton.cs.algs4.StdOut;\nimport util.Constants;\nimport util.FileUtil;\n\n/**\n * Created by Rene Argento on 08/02/18.\n */\npublic class Exercise17_SpellChecking {\n\n private void spellChecker(String dictionaryFileName) {\n String filePath = Constants.FILES_PATH + dictionaryFileName;\n String[] wordsInDictionary = FileUtil.getAllStringsFromFile(filePath);\n\n String[] text = StdIn.readAllStrings();\n\n StdOut.println(\"Words not in the dictionary:\");\n\n if (wordsInDictionary == null) {\n for (String word : text) {\n StdOut.println(word);\n }\n\n return;\n }\n\n StringSet stringSet = new StringSet();\n\n for (String word : wordsInDictionary) {\n stringSet.add(word);\n }\n\n for (String word : text) {\n if (!stringSet.contains(word)) {\n StdOut.println(word);\n }\n }\n }\n\n // Parameters example: 3.1.26_Dictionary.txt\n // This is the same dictionary file used in exercise 3.1.26\n // Standard input text: Djikstra sorting method Test good Algorithms\n\n // Expected output:\n // sorting\n // method\n // good\n\n // Dictionary file contents\n\n // Algorithms\n // ABC\n // Djikstra\n // Test\n // Rene\n // Binary\n // Sort\n public static void main(String[] args) {\n String fileName = args[0];\n new Exercise17_SpellChecking().spellChecker(fileName);\n }\n\n}\n", "support_files": [], "metadata": {"number": "5.2.17", "chapter": 5, "chapter_title": "Strings", "section": 5.2, "section_title": "Tries", "type": "Creative Problem", "code_execution": false}} {"question": "Typing monkeys. Suppose that a typing monkey creates random words by appending each of 26 possible letter with probability p to the current word and finishes the word with probability 1 - 26p. Write a program to estimate the frequency distribution of the lengths of words produced. If \"abc\" is produced more than once, count it only once.", "answer": "package chapter5.section2;\n\nimport chapter3.section4.SeparateChainingHashTable;\nimport edu.princeton.cs.algs4.StdOut;\nimport edu.princeton.cs.algs4.StdRandom;\nimport util.Constants;\n\n/**\n * Created by Rene Argento on 17/02/18.\n */\npublic class Exercise22_TypingMonkeys {\n\n public double[] getFrequencyDistribution(int numberOfWordsToGenerate, double probability) {\n int wordsGenerated = 0;\n\n SeparateChainingHashTable frequencyMap = new SeparateChainingHashTable<>();\n int maxWordLength = 0;\n\n StringSet wordsGeneratedStringSet = new StringSet();\n\n while (wordsGenerated < numberOfWordsToGenerate) {\n StringBuilder currentWord = new StringBuilder();\n\n while (true) {\n double currentProbability = StdRandom.uniform();\n\n int characterIndexToAppend = (int) (currentProbability / probability);\n\n // Valid characters are in the range [0, 25]\n boolean shouldFinishWord = characterIndexToAppend >= 26;\n\n if (shouldFinishWord) {\n\n String word = currentWord.toString();\n if (wordsGeneratedStringSet.contains(word)) {\n // Word was already generated, so we do not count it\n break;\n } else {\n wordsGeneratedStringSet.add(word);\n }\n\n wordsGenerated++;\n\n int currentWordLength = currentWord.length();\n\n if (currentWordLength > maxWordLength) {\n maxWordLength = currentWordLength;\n }\n\n int frequencyCount = 0;\n\n if (frequencyMap.contains(currentWordLength)) {\n frequencyCount = frequencyMap.get(currentWordLength);\n }\n\n frequencyCount++;\n\n frequencyMap.put(currentWordLength, frequencyCount);\n break;\n }\n\n int nextCharacterIndex = Constants.ASC_II_UPPERCASE_LETTERS_INITIAL_INDEX + characterIndexToAppend;\n currentWord.append((char) nextCharacterIndex);\n }\n }\n\n double[] frequencies = new double[maxWordLength + 1];\n\n for (int wordLength : frequencyMap.keys()) {\n double wordLengthFrequency = frequencyMap.get(wordLength) / (double) numberOfWordsToGenerate;\n frequencies[wordLength] = wordLengthFrequency;\n }\n\n return frequencies;\n }\n\n // Parameters example: 0.025 1000\n public static void main(String[] args) {\n double probability = Double.parseDouble(args[0]);\n int numberOfWordsToGenerate = Integer.parseInt(args[1]);\n\n if (probability >= 0.03846) {\n throw new IllegalArgumentException(\"Probability must be less than 0.03846 (which is 1 / 26)\");\n }\n\n // Release the monkey\n double[] frequencies = new Exercise22_TypingMonkeys().getFrequencyDistribution(numberOfWordsToGenerate, probability);\n\n StdOut.println(\"Frequency distribution estimate\\n\");\n for (int i = 0; i < frequencies.length; i++) {\n StdOut.printf(\"%12s %.3f\\n\", \"Length \" + i + \": \", frequencies[i]);\n }\n }\n}\n", "support_files": [], "metadata": {"number": "5.2.22", "chapter": 5, "chapter_title": "Strings", "section": 5.2, "section_title": "Tries", "type": "Creative Problem", "code_execution": false}} {"question": "Duplicates (revisited again). Redo Exercise 3.5.30 using StringSET (see Exercise 5.2.6) instead of HashSET. Compare the running times of the two approaches. Then use Dedup to run the experiments for N = 10^7, 10^8, and10^9, repeat the experiments for random long values and discuss the results.", "answer": "5.2.23 - Duplicates (revisited again)\n\nResults:\n\n Method | Data structure | Values type | Values Generated | Max Value | Time spent\n Array index count Array Integer 1000 500 0.01\n Array index count Array Integer 1000 1000 0.00\n Array index count Array Integer 1000 2000 0.00\n Array index count Array Integer 10000 5000 0.00\n Array index count Array Integer 10000 10000 0.00\n Array index count Array Integer 10000 20000 0.00\n Array index count Array Integer 100000 50000 0.02\n Array index count Array Integer 100000 100000 0.02\n Array index count Array Integer 100000 200000 0.03\n Array index count Array Integer 1000000 500000 0.28\n Array index count Array Integer 1000000 1000000 0.35\n Array index count Array Integer 1000000 2000000 0.37\n DeDup HashSet Integer 1000 500 0.00\n DeDup HashSet Integer 1000 1000 0.00\n DeDup HashSet Integer 1000 2000 0.00\n DeDup HashSet Integer 10000 5000 0.01\n DeDup HashSet Integer 10000 10000 0.01\n DeDup HashSet Integer 10000 20000 0.01\n DeDup HashSet Integer 100000 50000 0.05\n DeDup HashSet Integer 100000 100000 0.06\n DeDup HashSet Integer 100000 200000 0.06\n DeDup HashSet Integer 1000000 500000 1.30\n DeDup HashSet Integer 1000000 1000000 1.34\n DeDup HashSet Integer 1000000 2000000 2.18\n DeDup StringSet Integer 1000 500 0.01\n DeDup StringSet Integer 1000 1000 0.00\n DeDup StringSet Integer 1000 2000 0.00\n DeDup StringSet Integer 10000 5000 0.02\n DeDup StringSet Integer 10000 10000 0.02\n DeDup StringSet Integer 10000 20000 0.03\n DeDup StringSet Integer 100000 50000 0.29\n DeDup StringSet Integer 100000 100000 0.35\n DeDup StringSet Integer 100000 200000 0.46\n DeDup StringSet Integer 1000000 500000 6.23\n DeDup StringSet Integer 1000000 1000000 7.20\n DeDup StringSet Integer 1000000 2000000 8.13\n Array index count Array Long 1000 500 0.00\n Array index count Array Long 1000 1000 0.00\n Array index count Array Long 1000 2000 0.00\n Array index count Array Long 10000 5000 0.00\n Array index count Array Long 10000 10000 0.00\n Array index count Array Long 10000 20000 0.00\n Array index count Array Long 100000 50000 0.02\n Array index count Array Long 100000 100000 0.02\n Array index count Array Long 100000 200000 0.02\n Array index count Array Long 1000000 500000 0.24\n Array index count Array Long 1000000 1000000 0.38\n Array index count Array Long 1000000 2000000 0.39\n DeDup HashSet Long 1000 500 0.00\n DeDup HashSet Long 1000 1000 0.00\n DeDup HashSet Long 1000 2000 0.00\n DeDup HashSet Long 10000 5000 0.01\n DeDup HashSet Long 10000 10000 0.01\n DeDup HashSet Long 10000 20000 0.01\n DeDup HashSet Long 100000 50000 0.06\n DeDup HashSet Long 100000 100000 0.08\n DeDup HashSet Long 100000 200000 0.09\n DeDup HashSet Long 1000000 500000 1.51\n DeDup HashSet Long 1000000 1000000 1.57\n DeDup HashSet Long 1000000 2000000 2.20\n DeDup StringSet Long 1000 500 0.02\n DeDup StringSet Long 1000 1000 0.01\n DeDup StringSet Long 1000 2000 0.00\n DeDup StringSet Long 10000 5000 0.03\n DeDup StringSet Long 10000 10000 0.03\n DeDup StringSet Long 10000 20000 0.03\n DeDup StringSet Long 100000 50000 0.30\n DeDup StringSet Long 100000 100000 0.40\n DeDup StringSet Long 100000 200000 0.43\n DeDup StringSet Long 1000000 500000 6.40\n DeDup StringSet Long 1000000 1000000 7.29\n DeDup StringSet Long 1000000 2000000 8.19\n\nResults for DeDup with 10^7 and 10^8 values generated (10^9 configuration was not used due to operational system limitations)\n\n Method | Data structure | Values type | Values Generated | Max Value | Time spent\n DeDup HashSet Integer 10000000 5000000 19.15\n DeDup HashSet Integer 10000000 10000000 24.70\n DeDup HashSet Integer 10000000 20000000 30.05\n DeDup HashSet Integer 100000000 50000000 513.71\n DeDup HashSet Integer 100000000 100000000 823.40\n DeDup HashSet Integer 100000000 200000000 2362.58\n DeDup StringSet Integer 10000000 5000000 106.45\n DeDup StringSet Integer 10000000 10000000 115.64\n DeDup StringSet Integer 10000000 20000000 128.20\n DeDup StringSet Integer 100000000 50000000 2131.47\n DeDup StringSet Integer 100000000 100000000 5311.38\n DeDup StringSet Integer 100000000 200000000 11004.70\n DeDup HashSet Long 10000000 5000000 126.06\n DeDup HashSet Long 10000000 10000000 39.92\n DeDup HashSet Long 10000000 20000000 29.64\n DeDup HashSet Long 100000000 50000000 530.19\n DeDup HashSet Long 100000000 100000000 890.28\n DeDup HashSet Long 100000000 200000000 1556.39\n DeDup StringSet Long 10000000 5000000 151.01\n DeDup StringSet Long 10000000 10000000 122.93\n DeDup StringSet Long 10000000 20000000 141.92\n DeDup StringSet Long 100000000 50000000 2610.32\n DeDup StringSet Long 100000000 100000000 3423.40\n DeDup StringSet Long 100000000 200000000 9592.43\n\nDedup using a string set takes longer (more than 4 times more) to compute the distinct values than dedup using a hash set. The main reason for this seems to be because string sets only allow strings to be stored and every int and long key must be cast to a String before being inserted into the data structure. Casting is a costly operation, especially when it is done thousands or millions of times.\nAs seen on exercise 3.5.30, dedup using a hash set takes longer to compute the distinct values than the method counting frequencies in the array for both random integer and random long values. This is expected because even though hash sets and arrays have constant search time, the hash set requires autoboxing and unboxing for the int and long keys, which adds time in the operations.\nAlso, dedup does up to two operations per value generated: one to check if the set contains the value and (if it does not contain the value) another operation to insert it in the set whereas the array simply increases the value's index count. The dedup implementation in the book could be improved since the extra check to see if the set contains the value is not necessary. Sets do not allow duplicates, so it would internally ignore any attempts to insert a duplicate value.\nAs expected, the experiments with dedup for N = 10^7 and 10^8 using a string set are also slower to compute the distinct values than with dedup using a hash set.\n\n\nCorrection: the experiment table above is incomplete for the prompt as written because it reports `Dedup` only through `N = 10^8`; the requested `N = 10^9` case is not present. A complete dataset answer should either add the `10^9` timing for both random `int` and random `long` values or explicitly state that the run was skipped because of time/memory limits. The qualitative comparison remains that trie-based `StringSET` dedup is slower than hash-based `HashSET` for this workload, while direct array counting is fastest when the key universe is small enough to index directly.\n", "support_files": [], "metadata": {"number": "5.2.23", "chapter": 5, "chapter_title": "Strings", "section": 5.2, "section_title": "Tries", "type": "Experiment", "code_execution": false}} {"question": "Spell checker. Redo Exercise 3.5.31, which uses the file dictionary.txt from the booksite and the BlackFilter client on page 491 to print all misspelled words in a text file. Compare the performance of TrieST and TST for the file war.txt with this client and discuss the results.", "answer": "// Exercise24_SpellChecker.java\npackage chapter5.section2;\n\nimport chapter3.section5.HashSet;\nimport edu.princeton.cs.algs4.In;\nimport edu.princeton.cs.algs4.StdOut;\nimport edu.princeton.cs.algs4.Stopwatch;\nimport util.Constants;\nimport util.FileUtil;\n\n/**\n * Created by Rene Argento on 18/02/18.\n */\npublic class Exercise24_SpellChecker {\n\n private class BlackFilter {\n\n public HashSet filterUsingTrie(String dictionaryFilePath, String warAndPeaceFilePath) {\n HashSet filteredWords = new HashSet<>();\n\n // The value field is not used, but it is required by the trie\n Trie trie = new Trie<>();\n\n In in = new In(dictionaryFilePath);\n while (!in.isEmpty()) {\n trie.put(in.readString(), true);\n }\n\n String[] allWords = FileUtil.getAllStringsFromFile(warAndPeaceFilePath);\n\n if (allWords == null) {\n return filteredWords;\n }\n\n for (String word : allWords) {\n if (!trie.contains(word)) {\n filteredWords.add(word);\n }\n }\n\n return filteredWords;\n }\n\n public HashSet filterUsingTST(String dictionaryFilePath, String warAndPeaceFilePath) {\n HashSet filteredWords = new HashSet<>();\n\n // The value field is not used, but it is required by the ternary search trie\n TernarySearchTrie ternarySearchTrie = new TernarySearchTrie<>();\n\n In in = new In(dictionaryFilePath);\n while (!in.isEmpty()) {\n ternarySearchTrie.put(in.readString(), true);\n }\n\n String[] allWords = FileUtil.getAllStringsFromFile(warAndPeaceFilePath);\n\n if (allWords == null) {\n return filteredWords;\n }\n\n for (String word : allWords) {\n if (!ternarySearchTrie.contains(word)) {\n filteredWords.add(word);\n }\n }\n\n return filteredWords;\n }\n }\n\n // There was no dictionary.txt file on the booksite, so I suspect it has been renamed to commonwords.txt\n // Parameter example: common_words.txt\n\n private void doExperiment(String[] args) {\n String dictionaryFileName = args[0];\n String dictionaryFilePath = Constants.FILES_PATH + dictionaryFileName;\n\n String warAndPeaceFilePath = Constants.FILES_PATH + Constants.WAR_AND_PEACE_FILE;\n\n BlackFilter blackFilter = new BlackFilter();\n\n Stopwatch stopwatch = new Stopwatch();\n blackFilter.filterUsingTrie(dictionaryFilePath, warAndPeaceFilePath);\n double timeSpentWithTrie = stopwatch.elapsedTime();\n\n stopwatch = new Stopwatch();\n blackFilter.filterUsingTST(dictionaryFilePath, warAndPeaceFilePath);\n double timeSpentWithTST = stopwatch.elapsedTime();\n\n StdOut.printf(\"%19s %14s\\n\", \"Time spent trie | \", \"Time spent TST\");\n printResults(timeSpentWithTrie, timeSpentWithTST);\n }\n\n private void printResults(double trieTime, double ternarySearchTrieTime) {\n StdOut.printf(\"%16.2f %17.2f\\n\", trieTime, ternarySearchTrieTime);\n }\n\n public static void main(String[] args) {\n new Exercise24_SpellChecker().doExperiment(args);\n }\n}\n\nAdditional notes/results:\n5.2.24 - Spell checker\n\nResults:\n\n Time spent trie | Time spent TST\n 0.71 0.44\n\nThe ternary search trie had the best result, computing misspelled words in almost half the time required by the trie (the TST took 0.44 seconds against the 0.71 seconds taken by the trie).\nThis is an unexpected result because tries make a constant number of character compares during the search for words, while ternary search tries make a logarithmic number of character compares during these same searches.\nOne possible explanation for this result is that whenever a new node is created in the trie, an array of size 256 is also created. The cumulative time needed for the creation of these arrays may take a performance hit when dealing with many operations.", "support_files": [], "metadata": {"number": "5.2.24", "chapter": 5, "chapter_title": "Strings", "section": 5.2, "section_title": "Tries", "type": "Experiment", "code_execution": false}} {"question": "Give the dfa[][] array for the Knuth-Morris-Pratt algorithm for the pattern A A A A A A A A A, and draw the DFA, in the style of the figures in the text.", "answer": "5.3.2\n\npattern: A A A A A A A A A\n\n j 0\npat.charAt(j) A\n A 1\n dfa[][j] B 0\n C 0\n … 0\n\n j A\n 0 —> 1\n / ^\n / \\\n -B,C,…-\n\n X\n j 0 1\npat.charAt(j) A A\n A 1 2\n dfa[][j] B 0 0\n C 0 0\n … 0 0\n\n A j A\n 0 —> 1 —> 2\n / ^ <- \\\n / \\ \\ \\\n -B,C,…- --B,C,…-\n\n X\n j 0 1 2\npat.charAt(j) A A A\n A 1 2 3\n dfa[][j] B 0 0 0\n C 0 0 0\n … 0 0 0\n\n A A j A\n 0 —> 1 —> 2 —> 3\n / ^ <—- \\ \\\n / \\ \\ \\ \\\n -B,C,…- -B,C,…- <-—B,C,…-\n\n X\n j 0 1 2 3\npat.charAt(j) A A A A\n A 1 2 3 4\n dfa[][j] B 0 0 0 0\n C 0 0 0 0\n … 0 0 0 0\n\n A A A j A\n 0 —> 1 —> 2 —> 3 —> 4\n / ^ <—- \\ \\ \\\n / \\ \\ \\ \\ \\\n -B,C,…- -B,C,…- <-—B,C,…- <-—B,C,…-\n\n X\n j 0 1 2 3 4\npat.charAt(j) A A A A A\n A 1 2 3 4 5\n dfa[][j] B 0 0 0 0 0\n C 0 0 0 0 0\n … 0 0 0 0 0\n\n A A A A j A\n 0 —> 1 —> 2 —> 3 —> 4 —> 5\n / ^ <—- \\ \\ \\ \\\n / \\ \\ \\ \\ \\ \\\n -B,C,…- -B,C,…- <-—B,C,…- <-—B,C,…- <-—B,C,…-\n\n X\n j 0 1 2 3 4 5\npat.charAt(j) A A A A A A\n A 1 2 3 4 5 6\n dfa[][j] B 0 0 0 0 0 0\n C 0 0 0 0 0 0\n … 0 0 0 0 0 0\n\n A A A A A j A\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6\n / ^ <—- \\ \\ \\ \\ \\\n / \\ \\ \\ \\ \\ \\ \\\n -B,C,…- -B,C,…- <-—B,C,…- <-—B,C,…- <-—B,C,…- <-—B,C,…-\n\n\n X\n j 0 1 2 3 4 5 6\npat.charAt(j) A A A A A A A\n A 1 2 3 4 5 6 7\n dfa[][j] B 0 0 0 0 0 0 0\n C 0 0 0 0 0 0 0\n … 0 0 0 0 0 0 0\n\n A A A A A A j A\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7\n / ^ <—- \\ \\ \\ \\ \\ \\\n / \\ \\ \\ \\ \\ \\ \\ \\\n -B,C,…- -B,C,…- <-—B,C,…- <-—B,C,…- <-—B,C,…- <-—B,C,…- <-—B,C,…-\n\n X\n j 0 1 2 3 4 5 6 7\npat.charAt(j) A A A A A A A A\n A 1 2 3 4 5 6 7 8\n dfa[][j] B 0 0 0 0 0 0 0 0\n C 0 0 0 0 0 0 0 0\n … 0 0 0 0 0 0 0 0\n\n A A A A A A A j A\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8\n / ^ <—- \\ \\ \\ \\ \\ \\ \\\n / \\ \\ \\ \\ \\ \\ \\ \\ \\\n -B,C,…- -B,C,…- <-—B,C,…- <-—B,C,…- <-—B,C,…- <-—B,C,…- <-—B,C,…- <-—B,C,…-\n\n X\n j 0 1 2 3 4 5 6 7 8\npat.charAt(j) A A A A A A A A A\n A 1 2 3 4 5 6 7 8 9\n dfa[][j] B 0 0 0 0 0 0 0 0 0\n C 0 0 0 0 0 0 0 0 0\n … 0 0 0 0 0 0 0 0 0\n\n A A A A A A A A j A\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9\n / ^ <—- \\ \\ \\ \\ \\ \\ \\ \\\n / \\ \\ \\ \\ \\ \\ \\ \\ \\ \\\n -B,C,…- -B,C,…- <-—B,C,…- <-—B,C,…- <-—B,C,…- <-—B,C,…- <-—B,C,…- <-—B,C,…- <-—B,C,…-\n", "support_files": [], "metadata": {"number": "5.3.2", "chapter": 5, "chapter_title": "Strings", "section": 5.3, "section_title": "Substring Search", "type": "Exercise", "code_execution": false}} {"question": "Give the dfa[][] array for the Knuth-Morris-Pratt algorithm for the pattern A B R A C A D A B R A, and draw the DFA, in the style of the figures in the text.", "answer": "5.3.3\n\npattern: A B R A C A D A B R A\n\n j 0\npat.charAt(j) A\n A 1\n dfa[][j] B 0\n C 0\n D 0\n … 0\n R 0\n … 0\n\n j A\n 0 —> 1\n / ^\n / \\\n -B,C,D,…,R,…-\n\n X\n j 0 1\npat.charAt(j) A B\n A 1 1\n dfa[][j] B 0 2\n C 0 0\n D 0 0\n … 0 0\n R 0 0\n … 0 0\n\n A j B\n 0 —> 1 —> 2\n / ^ ^ \\\n / \\ / \\\n -B,C,D,…,R,…- - A -\n \\ \\\n -C,D,…,R,…-\n\n X\n j 0 1 2\npat.charAt(j) A B R\n A 1 1 1\n dfa[][j] B 0 2 0\n C 0 0 0\n D 0 0 0\n … 0 0 0\n R 0 0 3\n … 0 0 0\n\n A B j R\n 0 —> 1 —> 2 —> 3\n / ^ ^ \\ |\n / \\ / \\ |\n -B,C,D,…,R,…- - A - <————-—-A-—-—-\n \\ \\ |\n —C,D,…,R,…- <—B,C,D,…,Q,S,…—\n\n X\n j 0 1 2 3\npat.charAt(j) A B R A\n A 1 1 1 4\n dfa[][j] B 0 2 0 0\n C 0 0 0 0\n D 0 0 0 0\n … 0 0 0 0\n R 0 0 3 0\n … 0 0 0 0\n\n A B R j A\n 0 —> 1 —> 2 —> 3 —> 4\n / ^ ^ \\ | |\n / \\ / \\ | |\n -B,C,D,…,R,…- - A - <————-—-A-—-——- |\n \\ \\ | |\n --C,D,…,R,…- <—B,C,D,…,Q,S,…— <—B,C,D,…,R,…—\n\n X\n j 0 1 2 3 4\npat.charAt(j) A B R A C\n A 1 1 1 4 1\n dfa[][j] B 0 2 0 0 2\n C 0 0 0 0 5\n D 0 0 0 0 0\n … 0 0 0 0 0\n R 0 0 3 0 0\n … 0 0 0 0 0\n\n ————————-——-B————————-——--—\n A B V R A j| C\n 0 —> 1 —> 2 —> 3 —> 4 —> 5\n / ^ ^ \\ | | |\n / \\ / \\ | | |\n -B,C,D,…,R,…- - A - <————-—-A-—-——- <—————-————--|-————A-——-\n \\ \\ | | |\n --C,D,…,R,…- <—B,C,D,…,Q,S,…— <—B,C,D,…,R,…— <-D,…,R,…—\n\n X\n j 0 1 2 3 4 5\npat.charAt(j) A B R A C A\n A 1 1 1 4 1 6\n dfa[][j] B 0 2 0 0 2 0\n C 0 0 0 0 5 0\n D 0 0 0 0 0 0\n … 0 0 0 0 0 0\n R 0 0 3 0 0 0\n … 0 0 0 0 0 0\n\n ————————-——-B————————-——-—\n A B V R A | C j A\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6\n / ^ ^ \\ | | | |\n / \\ / \\ | | | |\n -B,C,D,…,R,…- - A - <————-—-A-————- <-—————-—————|-————A-——- |\n \\ \\ | | | |\n --C,D,…,R,…- <—B,C,D,…,Q,S,…— <—B,C,D,…,R,…— <-D,…,R,…— <—B,C,D,…,R,…-\n\n X\n j 0 1 2 3 4 5 6\npat.charAt(j) A B R A C A D\n A 1 1 1 4 1 6 1\n dfa[][j] B 0 2 0 0 2 0 2\n C 0 0 0 0 5 0 0\n D 0 0 0 0 0 0 7\n … 0 0 0 0 0 0 0\n R 0 0 3 0 0 0 0\n … 0 0 0 0 0 0 0\n\n ————————-——-B————————-——— <————————-——--B————————-—————\n A B V R A | C A j| D\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7\n / ^ ^ \\ | | | | |\n / \\ / \\ | | | | |\n -B,C,D,…,R,…- - A - <————-—-A-————- <-—————-—————-|-————A-——- <—————-——————|-————A-——-—-\n \\ \\ | | | | |\n --C,D,…,R,…- <—B,C,D,…,Q,S,…— <—B,C,D,…,R,…— <-D,…,R,…— <—B,C,D,…,R,…- <—C,E,…,R,…-\n\n X\n j 0 1 2 3 4 5 6 7\npat.charAt(j) A B R A C A D A\n A 1 1 1 4 1 6 1 8\n dfa[][j] B 0 2 0 0 2 0 2 0\n C 0 0 0 0 5 0 0 0\n D 0 0 0 0 0 0 7 0\n … 0 0 0 0 0 0 0 0\n R 0 0 3 0 0 0 0 0\n … 0 0 0 0 0 0 0 0\n\n ————————-——-B————————-——-—— <————————-——-B————————-————\n A B V R A | C A | D j A\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8\n / ^ ^ \\ | | | | | |\n / \\ / \\ | | | | | |\n -B,C,D,…,R,…- - A - <————-—-A-————- <—————-—————-|-————A-———- <—————-—————-|-————A-——-—- |\n \\ \\ | | | | | |\n --C,D,…,R,…- <—B,C,D,…,Q,S,…— <—B,C,D,…,R,…— <-D,…,R,…— <—B,C,D,…,R,…- <—C,E,…,R,…- <—B,C,D,…,R,…—\n\n X\n j 0 1 2 3 4 5 6 7 8\npat.charAt(j) A B R A C A D A B\n A 1 1 1 4 1 6 1 8 1\n dfa[][j] B 0 2 0 0 2 0 2 0 9\n C 0 0 0 0 5 0 0 0 0\n D 0 0 0 0 0 0 7 0 0\n … 0 0 0 0 0 0 0 0 0\n R 0 0 3 0 0 0 0 0 0\n … 0 0 0 0 0 0 0 0 0\n\n ————————-——-B————————-——-- <————————-——-B————————-—————\n A B V R A | C A | D A j B\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9\n / ^ ^ \\ | | | | | | |\n / \\ / \\ | | | | | | |\n -B,C,D,…,R,…- - A - <————-—-A-————- <—————-————--|-————A-——- <—————-——————|-————A-————— <——————-—————-|-—-————A-——-\n \\ \\ | | | | | | |\n --C,D,…,R,…- <—B,C,D,…,Q,S,…— <—B,C,D,…,R,…— <-D,…,R,…— <—B,C,D,…,R,…- <—C,E,…,R,…- <—B,C,D,…,R,…— <—C,D,…,R,…—\n\n X\n j 0 1 2 3 4 5 6 7 8 9\npat.charAt(j) A B R A C A D A B R\n A 1 1 1 4 1 6 1 8 1 1\n dfa[][j] B 0 2 0 0 2 0 2 0 9 0\n C 0 0 0 0 5 0 0 0 0 0\n D 0 0 0 0 0 0 7 0 0 0\n … 0 0 0 0 0 0 0 0 0 0\n R 0 0 3 0 0 0 0 0 0 10\n … 0 0 0 0 0 0 0 0 0 0\n\n ————————-——-B————————-———— <————————-——-B————————-—————\n A B V R A | C A | D A B j R\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10\n / ^ ^ \\ | | | | | | | |\n / \\ / \\ | | | | | | | |\n -B,C,D,…,R,…- - A - <————-—-A-————- <—————-——————|-————A-——- <—————-————-—|-————A-——-—— <--—————-————-|-—-————A-——- <—-————A-————---\n \\ \\ | | | | | | | |\n --C,D,…,R,…- <—B,C,D,…,Q,S,…— <—B,C,D,…,R,…— <-D,…,R,…— <—B,C,D,…,R,…- <—C,E,…,R,…- <—B,C,D,…,R,…— <—C,D,…,R,…— <—B,C,D,…,Q,S,…—\n\n X\n j 0 1 2 3 4 5 6 7 8 9 10\npat.charAt(j) A B R A C A D A B R A\n A 1 1 1 4 1 6 1 8 1 1 11\n dfa[][j] B 0 2 0 0 2 0 2 0 9 0 0\n C 0 0 0 0 5 0 0 0 0 0 0\n D 0 0 0 0 0 0 7 0 0 0 0\n … 0 0 0 0 0 0 0 0 0 0 0\n R 0 0 3 0 0 0 0 0 0 10 0\n … 0 0 0 0 0 0 0 0 0 0 0\n\n ————————-——-B————————-———— <————————-——-B————————-—————\n A B V R A | C A | D A B R j A\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> 11\n / ^ ^ \\ | | | | | | | | |\n / \\ / \\ | | | | | | | | |\n -B,C,D,…,R,…- - A - <————-—-A-————- <—————-——————|-————A-——- <—————-————-—|-————A-——-—— <--—————-————-|-—-————A-——- <—-————A-————--- |\n \\ \\ | | | | | | | | |\n --C,D,…,R,…- <—B,C,D,…,Q,S,…— <—B,C,D,…,R,…— <-D,…,R,…— <—B,C,D,…,R,…- <—C,E,…,R,…- <—B,C,D,…,R,…— <—C,D,…,R,…— <—B,C,D,…,Q,S,…— <—B,C,D,…,R,…—\n", "support_files": [], "metadata": {"number": "5.3.3", "chapter": 5, "chapter_title": "Strings", "section": 5.3, "section_title": "Substring Search", "type": "Exercise", "code_execution": false}} {"question": "Write an efficient method that takes a string txt and an integer M as arguments and returns the position of the first occurrence of M consecutive blanks in the string, txt.length if there is no such occurrence. Estimate the number of character compares used by your method, on typical text and in the worst case.", "answer": "package chapter5.section3;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 24/02/18.\n */\n// Thanks to AdamShamaa (https://github.com/AdamShamaa) for suggesting an optimization to this exercise.\n// https://github.com/reneargento/algorithms-sedgewick-wayne/issues/174\n\n// Number of character compares:\n // Typical case: N / 2\n // Worst case: N\npublic class Exercise4 {\n\n public int findBlankCharacters(String text, int mSpaces) {\n int textLength = text.length();\n int consecutiveBlanks;\n int i;\n\n for (i = 0, consecutiveBlanks = 0; i < textLength && consecutiveBlanks < mSpaces; i++) {\n if (text.charAt(i) == ' ') {\n consecutiveBlanks++;\n } else {\n consecutiveBlanks = 0;\n }\n }\n\n if (consecutiveBlanks == mSpaces) {\n return i - mSpaces;\t //found\n } else {\n return textLength; //not found\n }\n }\n\n public static void main(String[] args) {\n Exercise4 exercise4 = new Exercise4();\n\n String text = \" abacada abr braca brabrabracad\";\n\n int index1 = exercise4.findBlankCharacters(text, 1);\n StdOut.println(\"Index 1: \" + index1 + \" Expected: 0\");\n\n int index2 = exercise4.findBlankCharacters(text, 2);\n StdOut.println(\"Index 2: \" + index2 + \" Expected: 8\");\n\n int index3 = exercise4.findBlankCharacters(text, 3);\n StdOut.println(\"Index 3: \" + index3 + \" Expected: 13\");\n\n int index4 = exercise4.findBlankCharacters(text, 4);\n StdOut.println(\"Index 4: \" + index4 + \" Expected: 35\");\n }\n\n}\n", "support_files": [], "metadata": {"number": "5.3.4", "chapter": 5, "chapter_title": "Strings", "section": 5.3, "section_title": "Substring Search", "type": "Exercise", "code_execution": false}} {"question": "Develop a brute-force substring search implementation BruteForceRL that processes the pattern from right to left (a simplified version of ALGORITHM 5.7).", "answer": "package chapter5.section3;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 25/02/18.\n */\npublic class Exercise15 {\n\n public class BruteForceRL {\n\n private String pattern;\n private int patternLength;\n\n BruteForceRL(String pattern) {\n this.pattern = pattern;\n patternLength = pattern.length();\n }\n\n public int search(String text) {\n\n int textLength = text.length();\n\n for (int textIndex = 0; textIndex <= textLength - patternLength; textIndex++) {\n\n int patternIndex;\n for (patternIndex = patternLength - 1; patternIndex >= 0; patternIndex--) {\n if (text.charAt(textIndex + patternIndex) != pattern.charAt(patternIndex)) {\n break;\n }\n }\n\n if (patternIndex == -1) {\n return textIndex; // found\n }\n }\n\n return textLength; // not found\n }\n\n }\n\n public static void main(String[] args) {\n Exercise15 exercise15 = new Exercise15();\n\n String text = \"abacadabrabracabracadabrabrabracad\";\n\n String pattern1 = \"abracadabra\";\n BruteForceRL bruteForceRL1 = exercise15.new BruteForceRL(pattern1);\n int index1 = bruteForceRL1.search(text);\n StdOut.println(\"Index 1: \" + index1 + \" Expected: 14\");\n\n String pattern2 = \"rab\";\n BruteForceRL bruteForceRL2 = exercise15.new BruteForceRL(pattern2);\n int index2 = bruteForceRL2.search(text);\n StdOut.println(\"Index 2: \" + index2 + \" Expected: 8\");\n\n String pattern3 = \"bcara\";\n BruteForceRL bruteForceRL3 = exercise15.new BruteForceRL(pattern3);\n int index3 = bruteForceRL3.search(text);\n StdOut.println(\"Index 3: \" + index3 + \" Expected: 34\");\n\n String pattern4 = \"rabrabracad\";\n BruteForceRL bruteForceRL4 = exercise15.new BruteForceRL(pattern4);\n int index4 = bruteForceRL4.search(text);\n StdOut.println(\"Index 4: \" + index4 + \" Expected: 23\");\n\n String pattern5 = \"abacad\";\n BruteForceRL bruteForceRL5 = exercise15.new BruteForceRL(pattern5);\n int index5 = bruteForceRL5.search(text);\n StdOut.println(\"Index 5: \" + index5 + \" Expected: 0\");\n }\n\n}\n", "support_files": [], "metadata": {"number": "5.3.5", "chapter": 5, "chapter_title": "Strings", "section": 5.3, "section_title": "Substring Search", "type": "Exercise", "code_execution": false}} {"question": "Give the right[] array computed by the constructor in ALGORITHM 5.7 for the pattern A B R A C A D A B R A.", "answer": "5.3.6\n\npattern: A B R A C A D A B R A\n\n A B R A C A D A B R A\nc 0 1 2 3 4 5 6 7 8 9 10 right[c]\nA 0 0 0 3 3 5 5 7 7 7 10 10\nB -1 1 1 1 1 1 1 1 8 8 8 8\nC -1 -1 -1 -1 4 4 4 4 4 4 4 4\nD -1 -1 -1 -1 -1 -1 6 6 6 6 6 6\n… -1\nR -1 -1 2 2 2 2 2 2 2 9 9 9\n… -1\n", "support_files": [], "metadata": {"number": "5.3.6", "chapter": 5, "chapter_title": "Strings", "section": 5.3, "section_title": "Substring Search", "type": "Exercise", "code_execution": false}} {"question": "Add to KMP a count() method to count occurrences and a searchAll() method to print all occurrences.", "answer": "package chapter5.section3;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 25/02/18.\n */\npublic class Exercise8 {\n\n public class KnuthMorrisPrattSearchAll extends KnuthMorrisPratt {\n\n KnuthMorrisPrattSearchAll(String pattern) {\n super(pattern);\n }\n\n // Count the occurrences of pattern in the text\n public int count(String text) {\n int count = 0;\n\n int occurrenceIndex = searchFromIndex(text, 0);\n\n while (occurrenceIndex != text.length()) {\n count++;\n occurrenceIndex = searchFromIndex(text, occurrenceIndex + 1);\n }\n\n return count;\n }\n\n // Prints all the occurrences of pattern in the text\n public void searchAll(String text) {\n int occurrenceIndex = searchFromIndex(text, 0);\n\n if (occurrenceIndex == text.length()) {\n StdOut.println(\"No occurrences\");\n return;\n }\n\n while (occurrenceIndex != text.length()) {\n StdOut.println(\"Pattern found at index \" + occurrenceIndex);\n occurrenceIndex = searchFromIndex(text, occurrenceIndex + 1);\n }\n }\n\n // Searches for the pattern in the text starting at specified index\n protected int searchFromIndex(String text, int textStartIndex) {\n int textIndex;\n int patternIndex;\n int textLength = text.length();\n int patternLength = pattern.length();\n\n for (textIndex = textStartIndex, patternIndex = 0; textIndex < textLength && patternIndex < patternLength;\n textIndex++) {\n patternIndex = dfa[text.charAt(textIndex)][patternIndex];\n }\n if (patternIndex == patternLength) {\n return textIndex - patternLength; // found\n } else {\n return textLength; // not found\n }\n }\n }\n\n public static void main(String[] args) {\n Exercise8 exercise8 = new Exercise8();\n\n String text = \"abcdrenetestreneabdreneabcdd\";\n\n String pattern1 = \"rene\";\n KnuthMorrisPrattSearchAll knuthMorrisPrattSearchAll1 = exercise8.new KnuthMorrisPrattSearchAll(pattern1);\n int count1 = knuthMorrisPrattSearchAll1.count(text);\n StdOut.println(\"Count 1: \" + count1 + \" Expected: 3\");\n\n StdOut.println(\"Occurrences\");\n knuthMorrisPrattSearchAll1.searchAll(text);\n StdOut.println(\"Expected: 4, 12, 19\\n\");\n\n String pattern2 = \"abcd\";\n KnuthMorrisPrattSearchAll knuthMorrisPrattSearchAll2 = exercise8.new KnuthMorrisPrattSearchAll(pattern2);\n int count2 = knuthMorrisPrattSearchAll2.count(text);\n StdOut.println(\"Count 2: \" + count2 + \" Expected: 2\");\n\n StdOut.println(\"Occurrences\");\n knuthMorrisPrattSearchAll2.searchAll(text);\n StdOut.println(\"Expected: 0, 23\\n\");\n\n String pattern3 = \"d\";\n KnuthMorrisPrattSearchAll knuthMorrisPrattSearchAll3 = exercise8.new KnuthMorrisPrattSearchAll(pattern3);\n int count3 = knuthMorrisPrattSearchAll3.count(text);\n StdOut.println(\"Count 3: \" + count3 + \" Expected: 4\");\n\n StdOut.println(\"Occurrences\");\n knuthMorrisPrattSearchAll3.searchAll(text);\n StdOut.println(\"Expected: 3, 18, 26, 27\\n\");\n\n String pattern4 = \"zzz\";\n KnuthMorrisPrattSearchAll knuthMorrisPrattSearchAll4 = exercise8.new KnuthMorrisPrattSearchAll(pattern4);\n int count4 = knuthMorrisPrattSearchAll4.count(text);\n StdOut.println(\"Count 4: \" + count4 + \" Expected: 0\");\n\n StdOut.println(\"Occurrences\");\n knuthMorrisPrattSearchAll4.searchAll(text);\n StdOut.println(\"Expected: No occurrences\");\n }\n\n}\n", "support_files": [], "metadata": {"number": "5.3.8", "chapter": 5, "chapter_title": "Strings", "section": 5.3, "section_title": "Substring Search", "type": "Exercise", "code_execution": false}} {"question": "Add to RabinKarp a count() method to count occurrences and a searchAll() method to print all occurrences.", "answer": "package chapter5.section3;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 25/02/18.\n */\npublic class Exercise10 {\n\n public class RabinKarpSearchAll extends RabinKarp {\n\n RabinKarpSearchAll(String pattern, boolean isMonteCarloVersion) {\n super(pattern, isMonteCarloVersion);\n }\n\n // Count the occurrences of pattern in the text\n public int count(String text) {\n int count = 0;\n\n int occurrenceIndex = searchFromIndex(text, 0);\n\n while (occurrenceIndex != text.length()) {\n count++;\n\n if (occurrenceIndex + 1 >= text.length()) {\n break;\n }\n\n occurrenceIndex = searchFromIndex(text, occurrenceIndex + 1);\n }\n\n return count;\n }\n\n // Prints all the occurrences of pattern in the text\n public void searchAll(String text) {\n int occurrenceIndex = searchFromIndex(text, 0);\n\n if (occurrenceIndex == text.length()) {\n StdOut.println(\"No occurrences\");\n return;\n }\n\n while (occurrenceIndex != text.length()) {\n StdOut.println(\"Pattern found at index \" + occurrenceIndex);\n\n if (occurrenceIndex + 1 >= text.length()) {\n break;\n }\n\n occurrenceIndex = searchFromIndex(text, occurrenceIndex + 1);\n }\n }\n\n // Searches for the pattern in the text starting at specified index\n protected int searchFromIndex(String text, int textStartIndex) {\n String eligibleText = text.substring(textStartIndex);\n\n int textLength = eligibleText.length();\n\n if (textLength < patternLength) {\n return textStartIndex + textLength; // no match\n }\n\n long textHash = hash(eligibleText);\n\n if (patternHash == textHash && check(eligibleText, 0)) {\n return textStartIndex; // match\n }\n\n for (int textIndex = patternLength; textIndex < textLength; textIndex++) {\n // Remove leading character, add trailing character, check for match\n textHash = (textHash + largePrimeNumber - rm * eligibleText.charAt(textIndex - patternLength) % largePrimeNumber)\n % largePrimeNumber;\n textHash = (textHash * alphabetSize + eligibleText.charAt(textIndex)) % largePrimeNumber;\n\n int offset = textIndex - patternLength + 1;\n\n if (patternHash == textHash && check(eligibleText, offset)) {\n return textStartIndex + offset; // match\n }\n }\n\n return textStartIndex + textLength; // no match\n }\n\n }\n\n public static void main(String[] args) {\n Exercise10 exercise10 = new Exercise10();\n\n String text = \"abcdrenetestreneabdreneabcdd\";\n\n String pattern1 = \"rene\";\n RabinKarpSearchAll rabinKarpSearchAll1 = exercise10.new RabinKarpSearchAll(pattern1, true);\n int count1 = rabinKarpSearchAll1.count(text);\n StdOut.println(\"Count 1: \" + count1 + \" Expected: 3\");\n\n StdOut.println(\"Occurrences\");\n rabinKarpSearchAll1.searchAll(text);\n StdOut.println(\"Expected: 4, 12, 19\\n\");\n\n String pattern2 = \"abcd\";\n RabinKarpSearchAll rabinKarpSearchAll2 = exercise10.new RabinKarpSearchAll(pattern2, true);\n int count2 = rabinKarpSearchAll2.count(text);\n StdOut.println(\"Count 2: \" + count2 + \" Expected: 2\");\n\n StdOut.println(\"Occurrences\");\n rabinKarpSearchAll2.searchAll(text);\n StdOut.println(\"Expected: 0, 23\\n\");\n\n String pattern3 = \"d\";\n RabinKarpSearchAll rabinKarpSearchAll3 = exercise10.new RabinKarpSearchAll(pattern3, true);\n int count3 = rabinKarpSearchAll3.count(text);\n StdOut.println(\"Count 3: \" + count3 + \" Expected: 4\");\n\n StdOut.println(\"Occurrences\");\n rabinKarpSearchAll3.searchAll(text);\n StdOut.println(\"Expected: 3, 18, 26, 27\\n\");\n\n String pattern4 = \"zzz\";\n RabinKarpSearchAll rabinKarpSearchAll4 = exercise10.new RabinKarpSearchAll(pattern4, true);\n int count4 = rabinKarpSearchAll4.count(text);\n StdOut.println(\"Count 4: \" + count4 + \" Expected: 0\");\n\n StdOut.println(\"Occurrences\");\n rabinKarpSearchAll4.searchAll(text);\n StdOut.println(\"Expected: No occurrences\");\n }\n\n}\n", "support_files": [], "metadata": {"number": "5.3.10", "chapter": 5, "chapter_title": "Strings", "section": 5.3, "section_title": "Substring Search", "type": "Exercise", "code_execution": false}} {"question": "In the Boyer-Moore implementation in ALGORITHM 5.7, show that you can set right[c] to the penultimate occurrence of c when c is the last character in the pattern.", "answer": "5.3.13\n\nConsider that we are currently checking the text character in index i (as the leftmost position of the pattern), the pattern character in index j and that a mismatch occurs in the text character at index mi.\nAlso, consider that the last character in the pattern is c, the index of its last occurrence in the pattern is pMax and its penultimate occurrence is (pMax - x), where x is a number between 1 and pMax. Since c is the last character in the pattern pMax = patternLength - 1.\n\nWhen the character mismatch happens, the pattern has to be shifted to the right.\nIf right[c] were equal to pMax then the pattern would be shifted to the right 1 position because pMax will always be higher than j (a mismatch for character c would never occur in the last index of the pattern (pMax), because character c is in that position) and the rule to shift the pattern is: shift positions = max(1, j - pMax).\n\nHowever, if we had a mismatch in the text character c this means two things:\n1- In the inner loop of the algorithm the first character compare is always with the last character in the pattern (c). So there was a comparison of pattern character c with a text character that was a match. The mismatch must have happened in the range [0 … patternLength - 2] of the pattern.\n2- Since pMax is equal to patternLength - 1, we know that pMax > j. As mentioned above, this would imply shifting the pattern right 1 position. However, the penultimate occurrence of c is in index (pMax - x). If (pMax - x) >= j, the pattern would still be shifted only 1 position. But if (pMax - x) < j, we can shift the pattern to align mi with the penultimate occurrence of c in the pattern (by incrementing i by j - (pMax - x)). Anything less would align that text character with a pattern character it could not match (such as one to the right of c’s penultimate occurrence).\n\nTherefore, right[c] can be set to the penultimate occurrence of c when c is the last character in the pattern.\n", "support_files": [], "metadata": {"number": "5.3.13", "chapter": 5, "chapter_title": "Strings", "section": 5.3, "section_title": "Substring Search", "type": "Exercise", "code_execution": false}} {"question": "Draw the KMP DFA for the following pattern strings.\na. AAAAAAB\nb. AACAAAB\nc. ABABABAB\nd. ABAABAAABAAAB\ne. ABAABCABAABCB", "answer": "5.3.17\n\na. AAAAAAB\n\n j 0\npat.charAt(j) A\n A 1\n dfa[][j] B 0\n … 0\n\n j A\n 0 —> 1\n / ^\n / \\\n -B,…-\n\n X\n j 0 1\npat.charAt(j) A A\n A 1 2\n dfa[][j] B 0 0\n … 0 0\n\n A j A\n 0 —> 1 —> 2\n / ^ <- |\n / \\ | |\n -B,…- -B,…-\n\n X\n j 0 1 2\npat.charAt(j) A A A\n A 1 2 3\n dfa[][j] B 0 0 0\n … 0 0 0\n\n A A j A\n 0 —> 1 —> 2 —> 3\n / ^ <- | |\n / \\ | | |\n -B,…- -B,…- <--B,…-\n\n X\n j 0 1 2 3\npat.charAt(j) A A A A\n A 1 2 3 4\n dfa[][j] B 0 0 0 0\n … 0 0 0 0\n\n A A A j A\n 0 —> 1 —> 2 —> 3 —> 4\n / ^ <- | | |\n / \\ | | | |\n -B,…- -B,…- <--B,…- <--B,…-\n\n X\n j 0 1 2 3 4\npat.charAt(j) A A A A A\n A 1 2 3 4 5\n dfa[][j] B 0 0 0 0 0\n … 0 0 0 0 0\n\n A A A A j A\n 0 —> 1 —> 2 —> 3 —> 4 —> 5\n / ^ <- | | | |\n / \\ | | | | |\n -B,…- -B,…- <--B,…- <--B,…- <--B,…-\n\n X\n j 0 1 2 3 4 5\npat.charAt(j) A A A A A A\n A 1 2 3 4 5 6\n dfa[][j] B 0 0 0 0 0 0\n … 0 0 0 0 0 0\n\n A A A A A j A\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6\n / ^ <- | | | | |\n / \\ | | | | | |\n -B,…- -B,…- <--B,…- <--B,…- <--B,…- <--B,…-\n\n X\n j 0 1 2 3 4 5 6\npat.charAt(j) A A A A A A B\n A 1 2 3 4 5 6 6\n dfa[][j] B 0 0 0 0 0 0 7\n … 0 0 0 0 0 0 0\n\n A A A A A A j B\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7\n / ^ <- | | | | | |^\n / \\ | | | | | | / \\\\\n -B,…- -B,…- <--B,…- <--B,…- <--B,…- <--B,…- <-C,…- -A\n\nb. AACAAAB\n\n j 0\npat.charAt(j) A\n A 1\n dfa[][j] B 0\n C 0\n … 0\n\n j A\n 0 —> 1\n / ^\n / \\\n -B,C,…-\n\n X\n j 0 1\npat.charAt(j) A A\n A 1 2\n dfa[][j] B 0 0\n C 0 0\n … 0 0\n\n A j A\n 0 —> 1 —> 2\n / ^ <- \\\n / \\ \\ \\\n -B,C,…- --B,C,…-\n\n X\n j 0 1 2\npat.charAt(j) A A C\n A 1 2 2\n dfa[][j] B 0 0 0\n C 0 0 3\n … 0 0 0\n\n A A j C\n 0 —> 1 —> 2 —> 3\n / ^ <—- \\ |^\n / \\ \\ \\ / \\\\\n -B,C,…- -B,C,…- <-—B,D,…- -A\n\n X\n j 0 1 2 3\npat.charAt(j) A A C A\n A 1 2 2 4\n dfa[][j] B 0 0 0 0\n C 0 0 3 0\n … 0 0 0 0\n\n A A C j A\n 0 —> 1 —> 2 —> 3 —> 4\n / ^ <—- \\ |^ |\n / \\ \\ \\ / \\\\ |\n -B,C,…- -B,C,…- <-—B,D,…- -A |\n ^ |\n \\ |\n ————————————————————————-—B,C,…-\n\n X\n j 0 1 2 3 4\npat.charAt(j) A A C A A\n A 1 2 2 4 5\n dfa[][j] B 0 0 0 0 0\n C 0 0 3 0 0\n … 0 0 0 0 0\n\n A A C A j A\n 0 —> 1 —> 2 —> 3 —> 4 —> 5\n / ^ <—- \\ |^ | |\n / \\ \\ \\ / \\\\ | |\n -B,C,…- -B,C,…- <-—B,D,…- -A | |\n ^ | |\n \\ | |\n ————————————————————————-—B,C,…- <-—B,C,…-\n\n X\n j 0 1 2 3 4 5\npat.charAt(j) A A C A A A\n A 1 2 2 4 5 6\n dfa[][j] B 0 0 0 0 0 0\n C 0 0 3 0 0 3\n … 0 0 0 0 0 0\n\n ——————————C——————————\n A A C V A A j| A\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6\n / ^ <—- \\ |^ | | |\n / \\ \\ \\ / \\\\ | | |\n -B,C,…- -B,C,…- <-—B,D,…- -A | | |\n ^ | | |\n \\ | | |\n ————————————————————————-—B,C,…- <-—B,C,…- <-—B,D,…-\n\n X\n j 0 1 2 3 4 5 6\npat.charAt(j) A A C A A A B\n A 1 2 2 4 5 6 2\n dfa[][j] B 0 0 0 0 0 0 7\n C 0 0 3 0 0 3 3\n … 0 0 0 0 0 0 0\n\n ————————————————————————————————————A————\n | ——————————C—————————— <———C———|\n A A V C V A A | A j| B\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7\n / ^ <—- \\ |^ | | | |\n / \\ \\ \\ / \\\\ | | | |\n -B,C,…- -B,C,…- <-—B,D,…- -A | | | |\n ^ | | | |\n \\ | | | |\n ————————————————————————-—B,C,…- <-—B,C,…- <-—B,D,…- <--—-D,…-\n\nc. ABABABAB\n\n j 0\npat.charAt(j) A\n A 1\n dfa[][j] B 0\n … 0\n\n j A\n 0 —> 1\n / ^\n / \\\n -B,…-\n\n X\n j 0 1\npat.charAt(j) A B\n A 1 1\n dfa[][j] B 0 2\n … 0 0\n\n A j B\n 0 —> 1 —> 2\n / ^ <- |^\n / \\ | / \\\\\n -B,…- -C,…- -A\n\n X\n j 0 1 2\npat.charAt(j) A B A\n A 1 1 3\n dfa[][j] B 0 2 0\n … 0 0 0\n\n A B j A\n 0 —> 1 —> 2 —> 3\n / ^ <- |^ |\n / \\ | / \\\\ |\n -B,…- -C,…- -A |\n ^ |\n \\ |\n —————————————B,…-\n\n X\n j 0 1 2 3\npat.charAt(j) A B A B\n A 1 1 3 1\n dfa[][j] B 0 2 0 4\n … 0 0 0 0\n\n ———————————————A———\n | |\n A V B A j| B\n 0 —> 1 —> 2 —> 3 —> 4\n / ^ <- |^ | |\n / \\ | / \\\\ | |\n -B,…- -C,…- -A | |\n ^ | |\n \\ | |\n —————————————B,…- <———C,…-\n\n X\n j 0 1 2 3 4\npat.charAt(j) A B A B A\n A 1 1 3 1 5\n dfa[][j] B 0 2 0 4 0\n … 0 0 0 0 0\n\n ———————————————A———\n | |\n A V B A | B j A\n 0 —> 1 —> 2 —> 3 —> 4 —> 5\n / ^ <- |^ | | |\n / \\ | / \\\\ | | |\n -B,…- -C,…- -A | | |\n ^ | | |\n \\ | | |\n —————————————B,…- <———C,…- <———B,…-\n\n X\n j 0 1 2 3 4 5\npat.charAt(j) A B A B A B\n A 1 1 3 1 5 1\n dfa[][j] B 0 2 0 4 0 6\n … 0 0 0 0 0 0\n\n ———————————————A——— <——————————————A—\n | | |\n A V B A | B A j| B\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6\n / ^ <- |^ | | | |\n / \\ | / \\\\ | | | |\n -B,…- -C,…- -A | | | |\n ^ | | | |\n \\ | | | |\n —————————————B,…- <———C,…- <———B,…- <———C,…-\n\n X\n j 0 1 2 3 4 5 6\npat.charAt(j) A B A B A B A\n A 1 1 3 1 5 1 7\n dfa[][j] B 0 2 0 4 0 6 0\n … 0 0 0 0 0 0 0\n\n ———————————————A——— <——————————————A—\n | | |\n A V B A | B A | B j A\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7\n / ^ <- |^ | | | | |\n / \\ | / \\\\ | | | | |\n -B,…- -C,…- -A | | | | |\n ^ | | | | |\n \\ | | | | |\n —————————————B,…- <———C,…- <———B,…- <———C,…- <———B,…-\n\n X\n j 0 1 2 3 4 5 6 7\npat.charAt(j) A B A B A B A B\n A 1 1 3 1 5 1 7 1\n dfa[][j] B 0 2 0 4 0 6 0 8\n … 0 0 0 0 0 0 0 0\n\n ———————————————A——— <——————————————A— <——————————————A—\n | | | |\n A V B A | B A | B A j| B\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8\n / ^ <- |^ | | | | | |\n / \\ | / \\\\ | | | | | |\n -B,…- -C,…- -A | | | | | |\n ^ | | | | | |\n \\ | | | | | |\n —————————————B,…- <———C,…- <———B,…- <———C,…- <———B,…- <———C,…-\n\nd. ABAABAAABAAAB\n\n j 0\npat.charAt(j) A\n A 1\n dfa[][j] B 0\n … 0\n\n j A\n 0 —> 1\n / ^\n / \\\n -B,…-\n\n X\n j 0 1\npat.charAt(j) A B\n A 1 1\n dfa[][j] B 0 2\n … 0 0\n\n A j B\n 0 —> 1 —> 2\n / ^ <- |^\n / \\ | / \\\\\n -B,…- -C,…- -A\n\n X\n j 0 1 2\npat.charAt(j) A B A\n A 1 1 3\n dfa[][j] B 0 2 0\n … 0 0 0\n\n A B j A\n 0 —> 1 —> 2 —> 3\n / ^ <- |^ |\n / \\ | / \\\\ |\n -B,…- -C,…- -A |\n ^ |\n \\ |\n —————————————B,…-\n\n X\n j 0 1 2 3\npat.charAt(j) A B A A\n A 1 1 3 4\n dfa[][j] B 0 2 0 2\n … 0 0 0 0\n\n ——————B———\n A B V A j| A\n 0 —> 1 —> 2 —> 3 —> 4\n / ^ <- |^ | |\n / \\ | / \\\\ | |\n -B,…- -C,…- -A | |\n ^ | |\n \\ | |\n —————————————B,…- <———C,…-\n\n X\n j 0 1 2 3 4\npat.charAt(j) A B A A B\n A 1 1 3 4 1\n dfa[][j] B 0 2 0 2 5\n … 0 0 0 0 0\n\n ——————————————————————————A—\n | ——————B——— |\n A V B V A | A j| B\n 0 —> 1 —> 2 —> 3 —> 4 —> 5\n / ^ <- |^ | | |\n / \\ | / \\\\ | | |\n -B,…- -C,…- -A | | |\n ^ | | |\n \\ | | |\n —————————————B,…- <———C,…- <———C,…-\n\n X\n j 0 1 2 3 4 5\npat.charAt(j) A B A A B A\n A 1 1 3 4 1 6\n dfa[][j] B 0 2 0 2 5 0\n … 0 0 0 0 0 0\n\n ——————————————————————————A—\n | ——————B——— |\n A V B V A | A | B j A\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6\n / ^ <- |^ | | | |\n / \\ | / \\\\ | | | |\n -B,…- -C,…- -A | | | |\n ^ | | | |\n \\ | | | |\n —————————————B,…- <———C,…- <———C,…- <———B,…-\n\n X\n j 0 1 2 3 4 5 6\npat.charAt(j) A B A A B A A\n A 1 1 3 4 1 6 7\n dfa[][j] B 0 2 0 2 5 0 2\n … 0 0 0 0 0 0 0\n\n ——————————————————————————A—\n | ——————B——— <——————|————————————————B—\n A V B V A | A | B A j| A\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7\n / ^ <- |^ | | | | |\n / \\ | / \\\\ | | | | |\n -B,…- -C,…- -A | | | | |\n ^ | | | | |\n \\ | | | | |\n —————————————B,…- <———C,…- <———C,…- <———B,…- <———C,…-\n\n X\n j 0 1 2 3 4 5 6 7\npat.charAt(j) A B A A B A A A\n A 1 1 3 4 1 6 7 8\n dfa[][j] B 0 2 0 2 5 0 2 5\n … 0 0 0 0 0 0 0 0\n\n ——————————————————————————A— —————————————————B—\n | ——————B——— <——————|————————|———————B— |\n A V B V A | A | B V A | A j| A\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8\n / ^ <- |^ | | | | | |\n / \\ | / \\\\ | | | | | |\n -B,…- -C,…- -A | | | | | |\n ^ | | | | | |\n \\ | | | | | |\n —————————————B,…- <———C,…- <———C,…- <———B,…- <———C,…- <———C,…-\n\n X\n j 0 1 2 3 4 5 6 7 8\npat.charAt(j) A B A A B A A A B\n A 1 1 3 4 1 6 7 8 1\n dfa[][j] B 0 2 0 2 5 0 2 5 9\n … 0 0 0 0 0 0 0 0 0\n\n ——————————————————————————————————————————————————————————————A—\n | |\n |—————————————————————————A— —————————————————B— |\n | ——————B——— <——————|————————|———————B— | |\n A V B V A | A | B V A | A | A j| B\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9\n / ^ <- |^ | | | | | | |\n / \\ | / \\\\ | | | | | | |\n -B,…- -C,…- -A | | | | | | |\n ^ | | | | | | |\n \\ | | | | | | |\n —————————————B,…- <———C,…- <———C,…- <———B,…- <———C,…- <———C,…- <———C,…-\n\n X\n j 0 1 2 3 4 5 6 7 8 9\npat.charAt(j) A B A A B A A A B A\n A 1 1 3 4 1 6 7 8 1 10\n dfa[][j] B 0 2 0 2 5 0 2 5 9 0\n … 0 0 0 0 0 0 0 0 0 0\n\n ——————————————————————————————————————————————————————————————A—\n | |\n |—————————————————————————A— —————————————————B— |\n | ——————B——— <——————|————————|———————B— | |\n A V B V A | A | B V A | A | A | B j A\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10\n / ^ <- |^ | | | | | | | |\n / \\ | / \\\\ | | | | | | | |\n -B,…- -C,…- -A | | | | | | | |\n ^ | | | | | | | |\n \\ | | | | | | | |\n —————————————B,…- <———C,…- <———C,…- <———B,…- <———C,…- <———C,…- <———C,…- <———B,…-\n\n X\n j 0 1 2 3 4 5 6 7 8 9 10\npat.charAt(j) A B A A B A A A B A A\n A 1 1 3 4 1 6 7 8 1 10 11\n dfa[][j] B 0 2 0 2 5 0 2 5 9 0 2\n … 0 0 0 0 0 0 0 0 0 0 0\n\n ———————————————————————————————————————————————————————————————————————B—\n —————————|————————————————————————————————————————————————————A— |\n | | | |\n |————————|————————————————A— —————————————————B— | |\n | |—————B——— <——————|————————|———————B— | | |\n A V B V A | A | B V A | A | A | B A j| A\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> 11\n / ^ <- |^ | | | | | | | | |\n / \\ | / \\\\ | | | | | | | | |\n -B,…- -C,…- -A | | | | | | | | |\n ^ | | | | | | | | |\n \\ | | | | | | | | |\n —————————————B,…- <———C,…- <———C,…- <———B,…- <———C,…- <———C,…- <———C,…- <———B,…- <———C,…-\n\n X\n j 0 1 2 3 4 5 6 7 8 9 10 11\npat.charAt(j) A B A A B A A A B A A A\n A 1 1 3 4 1 6 7 8 1 10 11 12\n dfa[][j] B 0 2 0 2 5 0 2 5 9 0 2 5\n … 0 0 0 0 0 0 0 0 0 0 0 0\n\n —————————————————————————————————————————————————————B—\n ———————————————————————————|———————————————————————————————————————————B— |\n —————————|——————————————————————————|—————————————————————————A— | |\n | | | | | |\n |————————|————————————————A— |————————————————B— | | |\n | |—————B——— <——————|————————|———————B— | | | |\n A V B V A | A | B V A | A | A | B A | A j| A\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> 11 —> 12\n / ^ <- |^ | | | | | | | | | |\n / \\ | / \\\\ | | | | | | | | | |\n -B,…- -C,…- -A | | | | | | | | | |\n ^ | | | | | | | | | |\n \\ | | | | | | | | | |\n —————————————B,…- <———C,…- <———C,…- <———B,…- <———C,…- <———C,…- <———C,…- <———B,…- <———C,…- <———C,…-\n\n X\n j 0 1 2 3 4 5 6 7 8 9 10 11 12\npat.charAt(j) A B A A B A A A B A A A B\n A 1 1 3 4 1 6 7 8 1 10 11 12 1\n dfa[][j] B 0 2 0 2 5 0 2 5 9 0 2 5 13\n … 0 0 0 0 0 0 0 0 0 0 0 0 0\n\n ——————————————————————————————————————————————————————————————————————————————————————————————————A—\n | —————————————————————————————————————————————————————B— |\n | ———————————————————————————|———————————————————————————————————————————B— | |\n |————————|——————————————————————————|—————————————————————————A— | | |\n | | | | | | |\n |————————|————————————————A— |————————————————B— | | | |\n | |—————B——— <——————|————————|———————B— | | | | |\n A V B V A | A | B V A | A | A | B A | A | A j| B\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> 11 —> 12 —> 13\n / ^ <- |^ | | | | | | | | | | |\n / \\ | / \\\\ | | | | | | | | | | |\n -B,…- -C,…- -A | | | | | | | | | | |\n ^ | | | | | | | | | | |\n \\ | | | | | | | | | | |\n —————————————B,…- <———C,…- <———C,…- <———B,…- <———C,…- <———C,…- <———C,…- <———B,…- <———C,…- <———C,…- <———C,…-\n\ne. ABAABCABAABCB\n\n j 0\npat.charAt(j) A\n A 1\n dfa[][j] B 0\n C 0\n … 0\n\n j A\n 0 —> 1\n / ^\n / \\\n -B,C,…-\n\n X\n j 0 1\npat.charAt(j) A B\n A 1 1\n dfa[][j] B 0 2\n C 0 0\n … 0 0\n\n A j B\n 0 —> 1 —> 2\n / ^ <- |^\n / \\ | / \\\\\n -B,C,…- -C,…- -A\n\n X\n j 0 1 2\npat.charAt(j) A B A\n A 1 1 3\n dfa[][j] B 0 2 0\n C 0 0 0\n … 0 0 0\n\n A B j A\n 0 —> 1 —> 2 —> 3\n / ^ <- |^ |\n / \\ | / \\\\ |\n -B,C,…- -C,…- -A |\n ^ |\n \\ |\n ———————————B,C,…-\n\n X\n j 0 1 2 3\npat.charAt(j) A B A A\n A 1 1 3 4\n dfa[][j] B 0 2 0 2\n C 0 0 0 0\n … 0 0 0 0\n\n ——————B———\n A B V A j| A\n 0 —> 1 —> 2 —> 3 —> 4\n / ^ <- |^ | |\n / \\ | / \\\\ | |\n -B,C,…- -C,…- -A | |\n ^ | |\n \\ | |\n ———————————B,C,…- <———C,…-\n\n X\n j 0 1 2 3 4\npat.charAt(j) A B A A B\n A 1 1 3 4 1\n dfa[][j] B 0 2 0 2 5\n C 0 0 0 0 0\n … 0 0 0 0 0\n\n ——————————————————————————A—\n | ——————B——— |\n A V B V A | A j| B\n 0 —> 1 —> 2 —> 3 —> 4 —> 5\n / ^ <- |^ | | |\n / \\ | / \\\\ | | |\n -B,C,…- -C,…- -A | | |\n ^ | | |\n \\ | | |\n ———————————B,C,…- <———C,…- <———C,…-\n\n X\n j 0 1 2 3 4 5\npat.charAt(j) A B A A B C\n A 1 1 3 4 1 3\n dfa[][j] B 0 2 0 2 5 0\n C 0 0 0 0 0 6\n … 0 0 0 0 0 0\n\n ————————————————A—\n ———————————————————|——————A— |\n | ——————B———| | |\n A V B V A |V A | B j| C\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6\n / ^ <- |^ | | | |\n / \\ | / \\\\ | | | |\n -B,C,…- -C,…- -A | | | |\n ^ | | | |\n \\ | | | |\n ———————————B,C,…- <———C,…- <———C,…- <—B,D,…-\n\n X\n j 0 1 2 3 4 5 6\npat.charAt(j) A B A A B C A\n A 1 1 3 4 1 3 7\n dfa[][j] B 0 2 0 2 5 0 0\n C 0 0 0 0 0 6 0\n … 0 0 0 0 0 0 0\n\n ————————————————A—\n ———————————————————|——————A— |\n | ——————B———| | |\n A V B V A |V A | B | C j A\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7\n / ^ <- |^ | | | | |\n / \\ | / \\\\ | | | | |\n -B,C,…- -C,…- -A | | | | |\n ^ | | | | |\n \\ | | | | |\n ———————————B,C,…- <———C,…- <———C,…- <—B,D,…- <—B,C,…-\n\n X\n j 0 1 2 3 4 5 6 7\npat.charAt(j) A B A A B C A B\n A 1 1 3 4 1 3 7 1\n dfa[][j] B 0 2 0 2 5 0 0 8\n C 0 0 0 0 0 6 0 0\n … 0 0 0 0 0 0 0 0\n\n —————————————————————————————————————————————————————A—\n | ————————————————A— |\n |——————————————————|——————A— | |\n | ——————B———| | | |\n A V B V A |V A | B | C A j| B\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8\n / ^ <- |^ | | | | | |\n / \\ | / \\\\ | | | | | |\n -B,C,…- -C,…- -A | | | | | |\n ^ | | | | | |\n \\ | | | | | |\n ———————————B,C,…- <———C,…- <———C,…- <—B,D,…- <—B,C,…- <———C,…-\n\n X\n j 0 1 2 3 4 5 6 7 8\npat.charAt(j) A B A A B C A B A\n A 1 1 3 4 1 3 7 1 9\n dfa[][j] B 0 2 0 2 5 0 0 8 0\n C 0 0 0 0 0 6 0 0 0\n … 0 0 0 0 0 0 0 0 0\n\n —————————————————————————————————————————————————————A—\n | ————————————————A— |\n |——————————————————|——————A— | |\n | ——————B———| | | |\n A V B V A |V A | B | C A | B j A\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9\n / ^ <- |^ | | | | | | |\n / \\ | / \\\\ | | | | | | |\n -B,C,…- -C,…- -A | | | | | | |\n ^ | | | | | | |\n \\ | | | | | | |\n ———————————B,C,…- <———C,…- <———C,…- <—B,D,…- <—B,C,…- <———C,…- <—B,C,…-\n\n X\n j 0 1 2 3 4 5 6 7 8 9\npat.charAt(j) A B A A B C A B A A\n A 1 1 3 4 1 3 7 1 9 10\n dfa[][j] B 0 2 0 2 5 0 0 8 0 2\n C 0 0 0 0 0 6 0 0 0 0\n … 0 0 0 0 0 0 0 0 0 0\n\n ——————————————————————————————————————————————————————————————B—\n —————————|———————————————————————————————————————————A— |\n | | ————————————————A— | |\n |————————|—————————|——————A— | | |\n | |—————B———| | | | |\n A V B V A |V A | B | C A | B A j| A\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10\n / ^ <- |^ | | | | | | | |\n / \\ | / \\\\ | | | | | | | |\n -B,C,…- -C,…- -A | | | | | | | |\n ^ | | | | | | | |\n \\ | | | | | | | |\n ———————————B,C,…- <———C,…- <———C,…- <—B,D,…- <—B,C,…- <———C,…- <—B,C,…- <———C,…-\n\n X\n j 0 1 2 3 4 5 6 7 8 9 10\npat.charAt(j) A B A A B C A B A A B\n A 1 1 3 4 1 3 7 1 9 10 1\n dfa[][j] B 0 2 0 2 5 0 0 8 0 2 11\n C 0 0 0 0 0 6 0 0 0 0 0\n … 0 0 0 0 0 0 0 0 0 0 0\n\n ————————————————————————————————————————————————————————————————————————————————A—\n | ——————————————————————————————————————————————————————————————B— |\n |————————|———————————————————————————————————————————A— | |\n | | ————————————————A— | | |\n |————————|—————————|——————A— | | | |\n | |—————B———| | | | | |\n A V B V A |V A | B | C A | B A | A j| B\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> 11\n / ^ <- |^ | | | | | | | | |\n / \\ | / \\\\ | | | | | | | | |\n -B,C,…- -C,…- -A | | | | | | | | |\n ^ | | | | | | | | |\n \\ | | | | | | | | |\n ———————————B,C,…- <———C,…- <———C,…- <—B,D,…- <—B,C,…- <———C,…- <—B,C,…- <———C,…- <———C,…-\n\n X\n j 0 1 2 3 4 5 6 7 8 9 10 11\npat.charAt(j) A B A A B C A B A A B C\n A 1 1 3 4 1 3 7 1 9 10 1 3\n dfa[][j] B 0 2 0 2 5 0 0 8 0 2 11 0\n C 0 0 0 0 0 6 0 0 0 0 0 12\n … 0 0 0 0 0 0 0 0 0 0 0 0\n\n ——————————————————————————————————————————————————————————————————————A—\n ———————————————————|————————————————————————————————————————————————————————————A— |\n | ——————————|———————————————————————————————————————————————————B— | |\n |————————|—————————|—————————————————————————————————A— | | |\n | | |———————————————A— | | | |\n |————————|—————————|——————A— | | | | |\n | |—————B———| | | | | | |\n A V B V A |V A | B | C A | B A | A | B j| C\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> 11 —> 12\n / ^ <- |^ | | | | | | | | | |\n / \\ | / \\\\ | | | | | | | | | |\n -B,C,…- -C,…- -A | | | | | | | | | |\n ^ | | | | | | | | | |\n \\ | | | | | | | | | |\n ———————————B,C,…- <———C,…- <———C,…- <—B,D,…- <—B,C,…- <———C,…- <—B,C,…- <———C,…- <———C,…- <—B,D,…-\n\n X\n j 0 1 2 3 4 5 6 7 8 9 10 11 12\npat.charAt(j) A B A A B C A B A A B C B\n A 1 1 3 4 1 3 7 1 9 10 1 3 7\n dfa[][j] B 0 2 0 2 5 0 0 8 0 2 11 0 13\n C 0 0 0 0 0 6 0 0 0 0 0 12 0\n … 0 0 0 0 0 0 0 0 0 0 0 0 0\n\n ———————————————————————————————————————————A—\n ————————————————————————————————————|—————————————————————————————————A— |\n ———————————————————|———————————————————————————————————|————————————————————————A— | |\n | ——————————|———————————————————————————————————|———————————————B— | | |\n |————————|—————————|—————————————————————————————————A—| | | | |\n | | |———————————————A— || | | | |\n |————————|—————————|——————A— | || | | | |\n | |—————B———| | | || | | | |\n A V B V A |V A | B | C A |V B A | A | B | C j| B\n 0 —> 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> 11 —> 12 —> 13\n / ^ <- |^ | | | | | | | | | | |\n / \\ | / \\\\ | | | | | | | | | | |\n -B,C,…- -C,…- -A | | | | | | | | | | |\n ^ | | | | | | | | | | |\n \\ | | | | | | | | | | |\n ———————————B,C,…- <———C,…- <———C,…- <—B,D,…- <—B,C,…- <———C,…- <—B,C,…- <———C,…- <———C,…- <—B,D,…- <———C,…-\n", "support_files": [], "metadata": {"number": "5.3.17", "chapter": 5, "chapter_title": "Strings", "section": 5.3, "section_title": "Substring Search", "type": "Exercise", "code_execution": false}} {"question": "How would you modify the Rabin-Karp algorithm to search for an H-by-V pattern in an N-by-N text?", "answer": "5.3.22\n\nWe could compute a pattern hash that is based on each row of V characters in the following way:\nWe would compute H hashes (one hash for each row), in the same way as RabinKarp algorithm, and would add each value to the patternHash variable.\n\nSo the 1-by-4 pattern RENE and the 2-by-2 pattern RE would have different pattern hashes.\n NE\n\nWe would then use the same method to compute a hash for every sub matrix H-by-V in the text and would compare this value with the pattern hash. If there is a match in the hashes, we could check each character in the sub matrix (as in the Las Vegas version of Rabin Karp) to check if the pattern was found in the text.\n\nWe would use the rolling hash technique in the following way: an initialColumnsHash value would be computed with the hash value of the first H-by-V characters in the text. Every time we moved to a new row in the text (row i), the (i - 1)th row would be subtracted from the initialColumnsHash rolling hash computation and the (i + patternRowLength - 1)th row would be added to the initialColumnsHash rolling hash computation. After this, initialColumnsHash would be compared to patternHash to search for a match.\nWe then would copy initialColumnsHash’s value to a textHash variable to search horizontally in the text.\nEvery time we moved to a new column in the text (column j), the (j - patternColumnLength)th column would be subtracted from the textHash rolling hash computation and the jth column would be added to the textHash rolling hash computation. After this, textHash would be compared to patternHash to search for a match.\n\nWe would also precompute the powers of alphabetSize^i, for i = 0 … (patternColumnLength - 1) to effectively subtract rows and columns from the rolling hash computations.\n\nExample:\n\nPattern: RE\n NE\n(2-by-2 pattern)\n\nText: ABCD\n RERE\n DRNE\n XPQZ\n(4-by-4 text)\n\nWe start by computing the hash of RE in the variable patternHash.\n NE\n\n1- We compute the hash of characters AB in initialColumnsHash and compare with patternHash.\n RE\nThey have different values, so we move to the next column.\nWe also copy the value of initialColumnsHash to textHash.\n\n2- We subtract the value of column A from textHash and add the value of column C, resulting in the hash of BC.\n R R ER\nWe compare textHash with patternHash. They have different values, so we move to the next column.\n\n3- We subtract the value of column B from textHash and add the value of column D, resulting in the hash of CD.\n E E RE\nWe compare textHash with patternHash. They have different values. There are no more columns to the right, so we move to the next row and to the first column.\n\n4- We subtract the value of row AB from initialColumnsHash and add the value of row DR, resulting in the hash of RE.\n DR\nWe compare initialColumnsHash with patternHash. They have different values, so we copy the value of initialColumnsHash to textHash and move to the next column.\n\n5- We subtract the value of column R from textHash and add the value of column R, resulting in the hash of ER.\n D N RN\nWe compare textHash with patternHash. They have different values, so we move to the next column.\n\n6- We subtract the value of column E from textHash and add the value of column E, resulting in the hash of RE.\n R E NE\nWe compare textHash with patternHash. They have the same values, so we compare each character in the pattern with the current text sub matrix.\nThere is a match and the pattern was found. We return the result (1,2) which indicates that the pattern was found on row 1 and column 2.\n\nThe implementation of this algorithm can be found here:\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/blob/master/src/chapter5/section3/Exercise30_TwoDimensionalSearch.java\n", "support_files": [], "metadata": {"number": "5.3.22", "chapter": 5, "chapter_title": "Strings", "section": 5.3, "section_title": "Substring Search", "type": "Exercise", "code_execution": false}} {"question": "Write a program that reads characters one at a time and reports at each instant if the current string is a palindrome. Hint : Use the Rabin-Karp hashing idea.", "answer": "package chapter5.section3;\n\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.math.BigInteger;\nimport java.util.Random;\n\n/**\n * Created by Rene Argento on 01/03/18.\n */\n// Based on https://www.geeksforgeeks.org/online-algorithm-for-checking-palindrome-in-a-stream/\n\n// Monte Carlo version - O(N + M) with a probabilistic guarantee of giving the correct output.\n// Las Vegas version - Always gives the correct output with a probabilistic guarantee of running in N + M.\npublic class Exercise23 {\n\n public class PalindromeStreamChecker {\n\n // Pattern\n private StringBuilder currentString;\n\n private long largePrimeNumber; // prime number used to evaluate Rabin-Karp's rolling hash\n private int alphabetSize;\n\n private long hash;\n\n // Hash of the left half of the pattern reversed\n private long leftHalfReversedHash;\n // Hash of the right half of the pattern\n private long rightHalfHash;\n\n PalindromeStreamChecker() {\n currentString = new StringBuilder();\n\n alphabetSize = 256;\n hash = 1;\n\n largePrimeNumber = longRandomPrime();\n }\n\n // A random 31-bit prime\n private long longRandomPrime() {\n BigInteger prime = BigInteger.probablePrime(31, new Random());\n return prime.longValue();\n }\n\n public boolean checkPalindromeOnline(char character) {\n\n currentString.append(character);\n int patternLength = currentString.length();\n\n // Base cases: strings of lengths 1 and 2\n if (patternLength == 1) {\n leftHalfReversedHash = character % largePrimeNumber;\n\n return true;\n } else if (patternLength == 2) {\n rightHalfHash = character % largePrimeNumber;\n\n return currentString.charAt(0) == currentString.charAt(1);\n }\n\n if (patternLength % 2 == 0) {\n // Left string -> add trailing character in left half\n // Right string -> add trailing character in right half\n char characterToBeAddedInLeftString = currentString.charAt((patternLength - 1) / 2);\n\n hash = (hash * alphabetSize) % largePrimeNumber;\n\n leftHalfReversedHash = (leftHalfReversedHash + hash * characterToBeAddedInLeftString) % largePrimeNumber;\n rightHalfHash = (rightHalfHash * alphabetSize + character) % largePrimeNumber;\n } else {\n // Left string -> no changes\n // Right string -> remove leading character and add trailing character\n char characterToRemove = currentString.charAt(patternLength / 2);\n\n rightHalfHash = (alphabetSize * (rightHalfHash + largePrimeNumber\n - characterToRemove * hash) % largePrimeNumber\n + character) % largePrimeNumber;\n }\n\n // Monte Carlo version - If hashes match, a palindrome was found.\n// if (leftHalfReversedHash == rightHalfHash) {\n// return true;\n// }\n\n // Las Vegas version - If hashes match, compare characters.\n if (leftHalfReversedHash == rightHalfHash) {\n boolean isPalindrome = true;\n\n for (int index = 0; index < currentString.length() / 2; index++) {\n if (currentString.charAt(index) != currentString.charAt(currentString.length() - 1 - index)) {\n isPalindrome = false;\n break;\n }\n }\n\n return isPalindrome;\n }\n\n return false;\n }\n }\n\n public static void main(String[] args) {\n Exercise23 exercise23 = new Exercise23();\n\n StdOut.println(\"Test 1:\");\n PalindromeStreamChecker palindromeStreamChecker1 = exercise23.new PalindromeStreamChecker();\n StdOut.println(\"Check r: \" + palindromeStreamChecker1.checkPalindromeOnline('r') + \" Expected: true\");\n StdOut.println(\"Check re: \" + palindromeStreamChecker1.checkPalindromeOnline('e') + \" Expected: false\");\n StdOut.println(\"Check ree: \" + palindromeStreamChecker1.checkPalindromeOnline('e') + \" Expected: false\");\n StdOut.println(\"Check reer: \" + palindromeStreamChecker1.checkPalindromeOnline('r') + \" Expected: true\");\n\n StdOut.println();\n\n StdOut.println(\"Test 2:\");\n PalindromeStreamChecker palindromeStreamChecker2 = exercise23.new PalindromeStreamChecker();\n StdOut.println(\"Check a: \" + palindromeStreamChecker2.checkPalindromeOnline('a') + \" Expected: true\");\n StdOut.println(\"Check ab: \" + palindromeStreamChecker2.checkPalindromeOnline('b') + \" Expected: false\");\n StdOut.println(\"Check abc: \" + palindromeStreamChecker2.checkPalindromeOnline('c') + \" Expected: false\");\n StdOut.println(\"Check abcb: \" + palindromeStreamChecker2.checkPalindromeOnline('b') + \" Expected: false\");\n StdOut.println(\"Check abcba: \" + palindromeStreamChecker2.checkPalindromeOnline('a') + \" Expected: true\");\n\n StdOut.println();\n\n StdOut.println(\"Test 3:\");\n PalindromeStreamChecker palindromeStreamChecker3 = exercise23.new PalindromeStreamChecker();\n StdOut.println(\"Check L: \" + palindromeStreamChecker3.checkPalindromeOnline('L') + \" Expected: true\");\n StdOut.println(\"Check LE: \" + palindromeStreamChecker3.checkPalindromeOnline('E') + \" Expected: false\");\n StdOut.println(\"Check LEV: \" + palindromeStreamChecker3.checkPalindromeOnline('V') + \" Expected: false\");\n StdOut.println(\"Check LEVE: \" + palindromeStreamChecker3.checkPalindromeOnline('E') + \" Expected: false\");\n StdOut.println(\"Check LEVEL: \" + palindromeStreamChecker3.checkPalindromeOnline('L') + \" Expected: true\");\n StdOut.println(\"Check LEVEL0: \" + palindromeStreamChecker3.checkPalindromeOnline('0') + \" Expected: false\");\n }\n\n}\n", "support_files": [], "metadata": {"number": "5.3.23", "chapter": 5, "chapter_title": "Strings", "section": 5.3, "section_title": "Substring Search", "type": "Exercise", "code_execution": false}} {"question": "Find all occurrences. Add a method findAll() to each of the four substring search algorithms given in the text that returns an Iterable that allows clients to iterate through all offsets of the pattern in the text.", "answer": "package chapter5.section3;\n\nimport chapter1.section3.Queue;\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.StringJoiner;\n\n/**\n * Created by Rene Argento on 02/03/18.\n */\npublic class Exercise24_FindAllOccurrences {\n\n public class BruteForceSubstringSearchFindAll extends BruteForceSubstringSearch {\n\n BruteForceSubstringSearchFindAll(String pattern) {\n super(pattern);\n }\n\n // Finds all the occurrences of pattern in the text\n public Iterable findAll(String text) {\n Queue offsets = new Queue<>();\n\n int occurrenceIndex = searchFromIndex(text, 0);\n\n while (occurrenceIndex != text.length()) {\n offsets.enqueue(occurrenceIndex);\n occurrenceIndex = searchFromIndex(text, occurrenceIndex + 1);\n }\n\n return offsets;\n }\n }\n\n public class KnuthMorrisPrattFindAll extends KnuthMorrisPratt {\n\n KnuthMorrisPrattFindAll(String pattern) {\n super(pattern);\n }\n\n // Finds all the occurrences of pattern in the text\n public Iterable findAll(String text) {\n Queue offsets = new Queue<>();\n\n int occurrenceIndex = searchFromIndex(text, 0);\n\n while (occurrenceIndex != text.length()) {\n offsets.enqueue(occurrenceIndex);\n occurrenceIndex = searchFromIndex(text, occurrenceIndex + 1);\n }\n\n return offsets;\n }\n }\n\n public class BoyerMooreFindAll extends BoyerMoore {\n\n BoyerMooreFindAll(String pattern) {\n super(pattern);\n }\n\n // Finds all the occurrences of pattern in the text\n public Iterable findAll(String text) {\n Queue offsets = new Queue<>();\n\n int occurrenceIndex = searchFromIndex(text, 0);\n\n while (occurrenceIndex != text.length()) {\n offsets.enqueue(occurrenceIndex);\n occurrenceIndex = searchFromIndex(text, occurrenceIndex + 1);\n }\n\n return offsets;\n }\n }\n\n public class RabinKarpFindAll extends RabinKarp {\n\n RabinKarpFindAll(String pattern, boolean isMonteCarloVersion) {\n super(pattern, isMonteCarloVersion);\n }\n\n // Finds all the occurrences of pattern in the text\n public Iterable findAll(String text) {\n Queue offsets = new Queue<>();\n\n int occurrenceIndex = searchFromIndex(text, 0);\n\n while (occurrenceIndex != text.length()) {\n offsets.enqueue(occurrenceIndex);\n\n if (occurrenceIndex + 1 >= text.length()) {\n break;\n }\n\n occurrenceIndex = searchFromIndex(text, occurrenceIndex + 1);\n }\n\n return offsets;\n }\n }\n\n public static void main(String[] args) {\n Exercise24_FindAllOccurrences findAllOccurrences = new Exercise24_FindAllOccurrences();\n\n StdOut.println(\"*** Bruteforce implementation tests ***\");\n findAllOccurrences.test(SubstringSearch.BRUTEFORCE);\n\n StdOut.println(\"*** Knuth-Morris-Pratt tests ***\");\n findAllOccurrences.test(SubstringSearch.KNUTH_MORRIS_PRATT);\n\n StdOut.println(\"*** Boyer-Moore tests ***\");\n findAllOccurrences.test(SubstringSearch.BOYER_MOORE);\n\n StdOut.println(\"*** Rabin-Karp tests ***\");\n findAllOccurrences.test(SubstringSearch.RABIN_KARP);\n }\n\n private void test(int substringSearchMethodId) {\n\n String text = \"abcdrenetestreneabdreneabcdd\";\n\n String pattern1 = \"rene\";\n SubstringSearch substringSearch1 = createSubstringSearch(substringSearchMethodId, pattern1);\n\n if (substringSearch1 == null) {\n return;\n }\n\n StringJoiner offsets1 = new StringJoiner(\", \");\n for (int offset : substringSearch1.findAll(text)) {\n offsets1.add(String.valueOf(offset));\n }\n\n StdOut.println(\"Offsets 1: \" + offsets1.toString());\n StdOut.println(\"Expected: 4, 12, 19\\n\");\n\n\n String pattern2 = \"abcd\";\n SubstringSearch substringSearch2 = createSubstringSearch(substringSearchMethodId, pattern2);\n\n StringJoiner offsets2 = new StringJoiner(\", \");\n for (int offset : substringSearch2.findAll(text)) {\n offsets2.add(String.valueOf(offset));\n }\n\n StdOut.println(\"Offsets 2: \" + offsets2.toString());\n StdOut.println(\"Expected: 0, 23\\n\");\n\n\n String pattern3 = \"d\";\n SubstringSearch substringSearch3 = createSubstringSearch(substringSearchMethodId, pattern3);\n\n StringJoiner offsets3 = new StringJoiner(\", \");\n for (int offset : substringSearch3.findAll(text)) {\n offsets3.add(String.valueOf(offset));\n }\n\n StdOut.println(\"Offsets 3: \" + offsets3.toString());\n StdOut.println(\"Expected: 3, 18, 26, 27\\n\");\n\n\n String pattern4 = \"zzz\";\n SubstringSearch substringSearch4 = createSubstringSearch(substringSearchMethodId, pattern4);\n\n StringJoiner offsets4 = new StringJoiner(\", \");\n for (int offset : substringSearch4.findAll(text)) {\n offsets4.add(String.valueOf(offset));\n }\n\n StdOut.println(\"Offsets 4: \" + offsets4.toString());\n StdOut.println(\"Expected: \\n\");\n }\n\n private SubstringSearch createSubstringSearch(int substringSearchMethodId, String pattern) {\n SubstringSearch substringSearch = null;\n\n switch (substringSearchMethodId) {\n case SubstringSearch.BRUTEFORCE:\n substringSearch = new BruteForceSubstringSearchFindAll(pattern);\n break;\n case SubstringSearch.KNUTH_MORRIS_PRATT:\n substringSearch = new KnuthMorrisPrattFindAll(pattern);\n break;\n case SubstringSearch.BOYER_MOORE:\n substringSearch = new BoyerMooreFindAll(pattern);\n break;\n case SubstringSearch.RABIN_KARP:\n substringSearch = new RabinKarpFindAll(pattern, true);\n break;\n }\n\n return substringSearch;\n }\n\n}\n", "support_files": [], "metadata": {"number": "5.3.24", "chapter": 5, "chapter_title": "Strings", "section": 5.3, "section_title": "Substring Search", "type": "Creative Problem", "code_execution": false}} {"question": "Tandem repeat search. A tandem repeat of a base string b in a string s is a substring of s having at least two consecutive copies b (nonoverlapping). Develop and implement a linear-time algorithm that, given two strings b and s, returns the index of the beginning of the longest tandem repeat of b in s. For example, your program should return 3 when b is abcab and s is abcabcababcababcababcab.", "answer": "package chapter5.section3;\n\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 03/03/18.\n */\npublic class Exercise27_TandemRepeatSearch {\n\n // Based on https://algs4.cs.princeton.edu/53substring/\n // O(N + M)\n public class KnuthMorrisPrattTandemRepeat {\n\n private String pattern;\n private int[][] dfa; // deterministic-finite-automaton\n private int baseStringLength;\n private int tandemRepeat;\n\n public KnuthMorrisPrattTandemRepeat(String baseString, String text) {\n if (baseString == null || baseString.length() == 0) {\n throw new IllegalArgumentException(\"Invalid base string\");\n }\n if (text == null) {\n throw new IllegalArgumentException(\"Invalid text\");\n }\n\n // Create the Knuth-Morris-Pratt DFA for k concatenated copies of baseString,\n // where k = textLength / baseStringLength\n StringBuilder pattern = new StringBuilder();\n\n int maxNumberOfRepeats = text.length() / baseString.length();\n\n for (int repeat = 0; repeat < maxNumberOfRepeats; repeat++) {\n pattern.append(baseString);\n }\n\n this.pattern = pattern.toString();\n int patternLength = pattern.length();\n int alphabetSize = 256;\n baseStringLength = baseString.length();\n tandemRepeat = -1;\n\n dfa = new int[alphabetSize][patternLength];\n dfa[pattern.charAt(0)][0] = 1;\n\n int restartState = 0;\n\n for (int patternIndex = 1; patternIndex < patternLength; patternIndex++) {\n // Compute dfa[][patternIndex]\n for (int currentChar = 0; currentChar < alphabetSize; currentChar++) {\n dfa[currentChar][patternIndex] = dfa[currentChar][restartState]; // Copy mismatch cases\n }\n dfa[pattern.charAt(patternIndex)][patternIndex] = patternIndex + 1; // Set match case\n restartState = dfa[pattern.charAt(patternIndex)][restartState]; // Update restart state\n }\n\n computeTandemRepeat(text);\n }\n\n private void computeTandemRepeat(String text) {\n int textIndex;\n int patternIndex;\n\n // A tandem repeat is composed of at least 2 consecutive occurrences of the base string.\n // If 1 occurrence were enough, we would initialize maxPatternIndexMatched with 0.\n int maxPatternIndexMatched = baseStringLength;\n\n for (textIndex = 0, patternIndex = 0; textIndex < text.length() && patternIndex < pattern.length(); textIndex++) {\n patternIndex = dfa[text.charAt(textIndex)][patternIndex];\n\n if (patternIndex % baseStringLength == 0 && patternIndex > maxPatternIndexMatched) {\n tandemRepeat = textIndex - patternIndex + 1;\n maxPatternIndexMatched = patternIndex;\n }\n }\n }\n\n public int findTandemRepeat() {\n return tandemRepeat;\n }\n }\n\n public static void main(String[] args) {\n Exercise27_TandemRepeatSearch tandemRepeatSearch = new Exercise27_TandemRepeatSearch();\n\n String baseString1 = \"abcab\";\n String text1 = \"abcabcababcababcababcab\";\n\n KnuthMorrisPrattTandemRepeat knuthMorrisPrattTandemRepeat1 =\n tandemRepeatSearch.new KnuthMorrisPrattTandemRepeat(baseString1, text1);\n int tandemRepeat1 = knuthMorrisPrattTandemRepeat1.findTandemRepeat();\n StdOut.println(\"Tandem repeat 1: \" + tandemRepeat1 + \" Expected: 3\");\n\n\n String baseString2 = \"rene\";\n String text2 = \"renereneabrenerenereneab\";\n\n KnuthMorrisPrattTandemRepeat knuthMorrisPrattTandemRepeat2 =\n tandemRepeatSearch.new KnuthMorrisPrattTandemRepeat(baseString2, text2);\n int tandemRepeat2 = knuthMorrisPrattTandemRepeat2.findTandemRepeat();\n StdOut.println(\"Tandem repeat 2: \" + tandemRepeat2 + \" Expected: 10\");\n\n\n String baseString3 = \"abcab\";\n String text3 = \"abcababcababcababcabreabcab\";\n\n KnuthMorrisPrattTandemRepeat knuthMorrisPrattTandemRepeat3 =\n tandemRepeatSearch.new KnuthMorrisPrattTandemRepeat(baseString3, text3);\n int tandemRepeat3 = knuthMorrisPrattTandemRepeat3.findTandemRepeat();\n StdOut.println(\"Tandem repeat 3: \" + tandemRepeat3 + \" Expected: 0\");\n\n\n String baseString4 = \"rene\";\n String text4 = \"abcabcabrenereneababcab\";\n\n KnuthMorrisPrattTandemRepeat knuthMorrisPrattTandemRepeat4 =\n tandemRepeatSearch.new KnuthMorrisPrattTandemRepeat(baseString4, text4);\n int tandemRepeat4 = knuthMorrisPrattTandemRepeat4.findTandemRepeat();\n StdOut.println(\"Tandem repeat 4: \" + tandemRepeat4 + \" Expected: 8\");\n\n\n String baseString5 = \"rene\";\n String text5 = \"abcabcababcababcababcab\";\n\n KnuthMorrisPrattTandemRepeat knuthMorrisPrattTandemRepeat5 =\n tandemRepeatSearch.new KnuthMorrisPrattTandemRepeat(baseString5, text5);\n int tandemRepeat5 = knuthMorrisPrattTandemRepeat5.findTandemRepeat();\n StdOut.println(\"Tandem repeat 5: \" + tandemRepeat5 + \" Expected: -1\");\n\n\n // A tandem repeat requires at least 2 consecutive occurrences of baseString in the text,\n // so the two following tests should return -1.\n\n String baseString6 = \"a\";\n String text6 = \"abcde\";\n\n KnuthMorrisPrattTandemRepeat knuthMorrisPrattTandemRepeat6 =\n tandemRepeatSearch.new KnuthMorrisPrattTandemRepeat(baseString6, text6);\n int tandemRepeat6 = knuthMorrisPrattTandemRepeat6.findTandemRepeat();\n StdOut.println(\"Tandem repeat 6: \" + tandemRepeat6 + \" Expected: -1\");\n\n String baseString7 = \"a\";\n String text7 = \"abada\";\n\n KnuthMorrisPrattTandemRepeat knuthMorrisPrattTandemRepeat7 =\n tandemRepeatSearch.new KnuthMorrisPrattTandemRepeat(baseString7, text7);\n int tandemRepeat7 = knuthMorrisPrattTandemRepeat7.findTandemRepeat();\n StdOut.println(\"Tandem repeat 7: \" + tandemRepeat7 + \" Expected: -1\");\n }\n\n}\n", "support_files": [], "metadata": {"number": "5.3.27", "chapter": 5, "chapter_title": "Strings", "section": 5.3, "section_title": "Substring Search", "type": "Creative Problem", "code_execution": false}} {"question": "Random patterns. How many character compares are needed to do a substring search for a random pattern of length 100 in a given text?", "answer": "5.3.31 - Random patterns\n\nNone. The method\npublic boolean search(char[] text) {\n return false;\n}\nis quite effective for this problem, since the chances of a random pattern of length 100 appearing in any text are so low that you may consider it to be 0.\n", "support_files": [], "metadata": {"number": "5.3.31", "chapter": 5, "chapter_title": "Strings", "section": 5.3, "section_title": "Substring Search", "type": "Creative Problem", "code_execution": false}} {"question": "Timings. Write a program that times the four methods for the task of searchng for the substring\nit is a far far better thing that i do than i have ever done\nin the text of Tale of Two Cities (tale.txt). Discuss the extent to which your results validate the hypthotheses about performance that are stated in the text.", "answer": "// Exercise39_Timings.java\npackage chapter5.section3;\n\nimport edu.princeton.cs.algs4.StdOut;\nimport edu.princeton.cs.algs4.Stopwatch;\nimport util.Constants;\nimport util.FileUtil;\n\n/**\n * Created by Rene Argento on 09/03/18.\n */\n// The original text in the Tale of Two Cities file is:\n// \"It is a far, far better thing that I do, than I have ever done\"\npublic class Exercise39_Timings {\n\n private void doExperiment() {\n String taleOfTwoCitiesFile = Constants.FILES_PATH + Constants.TALE_OF_TWO_CITIES_FILE;\n String taleOfTwoCitiesText = FileUtil.getAllCharactersFromFile(taleOfTwoCitiesFile, true, true);\n String pattern = \"it is a far far better thing that I do than I have ever done\";\n\n String[] substringSearchMethods = {\n SubstringSearch.BRUTEFORCE_METHOD,\n SubstringSearch.KNUTH_MORRIS_PRATT_METHOD,\n SubstringSearch.BOYER_MOORE_METHOD,\n SubstringSearch.RABIN_KARP_METHOD\n };\n\n StdOut.printf(\"%20s %10s\\n\", \"Method |\", \"Time spent\");\n\n for (int substringSearchMethod = 0; substringSearchMethod < substringSearchMethods.length; substringSearchMethod++) {\n SubstringSearch substringSearch;\n\n switch (substringSearchMethod) {\n case SubstringSearch.BRUTEFORCE:\n substringSearch = new BruteForceSubstringSearch(pattern);\n break;\n case SubstringSearch.KNUTH_MORRIS_PRATT:\n substringSearch = new KnuthMorrisPratt(pattern);\n break;\n case SubstringSearch.BOYER_MOORE:\n substringSearch = new BoyerMoore(pattern);\n break;\n default:\n substringSearch = new RabinKarp(pattern, true);\n break;\n }\n\n Stopwatch stopwatch = new Stopwatch();\n substringSearch.search(taleOfTwoCitiesText);\n double timeSpent = stopwatch.elapsedTime();\n\n printResults(substringSearchMethods[substringSearchMethod], timeSpent);\n }\n }\n\n private void printResults(String substringSearchMethod, double timeSpent) {\n StdOut.printf(\"%18s %12.2f\\n\", substringSearchMethod, timeSpent);\n }\n\n public static void main(String[] args) {\n new Exercise39_Timings().doExperiment();\n }\n\n}\n\nAdditional notes/results:\n5.3.39 - Timings\n\n Method | Time spent\n Bruteforce 0.01\nKnuth-Morris-Pratt 0.01\n Boyer-Moore 0.00\n Rabin-Karp 0.04\n\nThe results validate the hypotheses about performance stated in the text:\nBoth brute force and Knuth-Morris-Pratt methods took 0.01 seconds to do the search, which is aligned with their expected performance of 1.1N operations when searching in typical texts.\nBoyer-Moore took 0.00 seconds to do the search, which suggests that it did a sublinear number of operations. This is aligned with its expected performance of N / M operations when searching in typical texts.\nRabin-Karp took 0.04 seconds to do the search, a longer time than all other three methods. However, this is expected according to the hypothesis in the text that it performs 7N operations when searching in typical texts.", "support_files": [], "metadata": {"number": "5.3.39", "chapter": 5, "chapter_title": "Strings", "section": 5.3, "section_title": "Substring Search", "type": "Experiment", "code_execution": false}} {"question": "Give a brief English description of each of the following REs:\na. .*\nb. A.*A | A\nc. .*ABBABBA.*\nd. .* A.*A.*A.*A.*", "answer": "5.4.2\n\na. Any string (including the empty string).\nb. Strings that start and end with an A.\nc. Strings that contain the palindrome ABBABBA.\nd. Strings that contain at least 4 A's, not necessarily consecutive.\n", "support_files": [], "metadata": {"number": "5.4.2", "chapter": 5, "chapter_title": "Strings", "section": 5.4, "section_title": "Regular Expressions", "type": "Exercise", "code_execution": false}} {"question": "What is the maximum number of different strings that can be described by a regular expression with M or operators and no closure operators (parentheses and concatenation are allowed)?", "answer": "5.4.3\n\nThe maximum number of different strings that can be described by a regular expression with M or operators and no closure operators is 2^M, which happens when every position yields two choices.\n\nExample pattern with M = 4:\n(A|B)(A|B)(A|B)(A|B)\n\nOn that pattern every position has two choices, which will yield 2^4 = 16 strings:\nAAAA\nBAAA, ABAA, AABA, AAAB\nBBAA, BABA, BAAB, ABBA, ABAB, AABB\nBBBA, BBAB, BABB, ABBB\nBBBB\n\nThanks to luowyang (https://github.com/luowyang) for the correct solution to this exercise:\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/97\n", "support_files": [], "metadata": {"number": "5.4.3", "chapter": 5, "chapter_title": "Strings", "section": 5.4, "section_title": "Regular Expressions", "type": "Exercise", "code_execution": false}} {"question": "Draw the NFA corresponding to the pattern ( ( ( A | B ) * | C D * | E F G ) * ) * .", "answer": "5.4.4\n\nPattern: (((A|B)*|CD*|EFG)*)*\n\nNFA: \n ————————————————————————————————————————————————————————————————————————————————————————————————\n | ————————————————————————————————————————————————————————————————————————————————— |\n | | ————————————————————————————————————————— | |\n | | —————————————————————————— | —————— | | | |\n | | | | | | | | | | |\n0V 1V 2V 3 4 5 6 7| 8| 9 10V 11| 12| 13 14 15 16V 17| 18 19| 20\n ( -> ( -> ( -> A -> | B -> ) -> * -> | C -> D -> * -> | E -> F -> G -> ) -> * -> ) -> * ->\n | | | | ^ ^ ^ ^ | ^ ^ ^ ^\n | | | |____|____| | | | | | | |\n | | |______________| | | ————— | | |\n | | |________________________| | | | |\n | | | | | |\n | ————————————————————————————————————————————————————————————————————————————————— |\n | |\n ———————————————————————————————————————————————————————————————————————————————————————————————\n", "support_files": [], "metadata": {"number": "5.4.4", "chapter": 5, "chapter_title": "Strings", "section": 5.4, "section_title": "Regular Expressions", "type": "Exercise", "code_execution": false}} {"question": "Draw the digraph of ε-transitions for the NFA from Exercise 5.4.4.", "answer": "5.4.5\n\nDigraph of e-transitions:\n\n———————————————————————————————————————————————————————————————————————————————————————————————————————————\n| —————————————————————————————————————————————————————————————————————————————————————————— |\n| | ——————————————————————————— ———————————————————————————————————————————————— | |\n| | | ____________ | | _______ | | | |\n| | | | | | | | | | | | |\nV V V | V | | | V | V | |\n0 -> 1 -> 2 -> 3 4 5 6 -> 7 -> 8 9 10 11 -> 12 13 14 15 16 -> 17 -> 18 -> 19 -> 20\n| | | ^ ^ ^ ^ | ^ ^ ^\n| | |_______________| | | | | | | |\n| | |_________________________| | ——————— | | |\n| | | | | |\n| —————————————————————————————————————————————————————————————————————————————————————————— |\n———————————————————————————————————————————————————————————————————————————————————————————————————————————\n", "support_files": [], "metadata": {"number": "5.4.5", "chapter": 5, "chapter_title": "Strings", "section": 5.4, "section_title": "Regular Expressions", "type": "Exercise", "code_execution": false}} {"question": "Give the sets of states reachable by your NFA from EXERCISE 5.4.4 after each character match and susbsequent ε-transitions for the input A B B A C E F G E F G C A A B .", "answer": "5.4.6\n\nInput: A B B A C E F G E F G C A A B\n\n0 1 2 3 5 7 8 9 13 16 17 18 19 20 : set of states reachable via e-transitions from start\n\n4 : set of states reachable after matching A\n\n0 1 2 3 4 5 6 7 8 9 13 16 17 18 19 20 : set of states reachable via e-transitions after matching A\n\n6 : set of states reachable after matching A B\n\n0 1 2 3 5 6 7 8 9 13 16 17 18 19 20 : set of states reachable via e-transitions after matching A B\n\n6 : set of states reachable after matching A B B\n\n0 1 2 3 5 6 7 8 9 13 16 17 18 19 20 : set of states reachable via e-transitions after matching A B B\n\n4 : set of states reachable after matching A B B A\n\n0 1 2 3 4 5 6 7 8 9 13 16 17 18 19 20 : set of states reachable via e-transitions after matching A B B A\n\n10 : set of states reachable after matching A B B A C\n\n0 1 2 3 5 7 8 9 10 11 12 13 16 17 18 19 20 : set of states reachable via e-transitions after matching A B B A C\n\n14 : set of states reachable after matching A B B A C E\n\n14 : set of states reachable via e-transitions after matching A B B A C E\n\n15 : set of states reachable after matching A B B A C E F\n\n15 : set of states reachable via e-transitions after matching A B B A C E F\n\n16 : set of states reachable after matching A B B A C E F G\n\n0 1 2 3 5 7 8 9 13 16 17 18 19 20 : set of states reachable via e-transitions after matching A B B A C E F G\n\n14 : set of states reachable after matching A B B A C E F G E\n\n14 : set of states reachable via e-transitions after matching A B B A C E F G E\n\n15 : set of states reachable after matching A B B A C E F G E F\n\n15 : set of states reachable via e-transitions after matching A B B A C E F G E F\n\n16 : set of states reachable after matching A B B A C E F G E F G\n\n0 1 2 3 5 7 8 9 13 16 17 18 19 20 : set of states reachable via e-transitions after matching A B B A C E F G E F G\n\n10 : set of states reachable after matching A B B A C E F G E F G C\n\n0 1 2 3 5 7 8 9 10 11 12 13 16 17 18 19 20 : set of states reachable via e-transitions after matching A B B A C E F G E F G C\n\n4 : set of states reachable after matching A B B A C E F G E F G C A\n\n0 1 2 3 4 5 6 7 8 9 13 16 17 18 19 20 : set of states reachable via e-transitions after matching A B B A C E F G E F G C A\n\n4 : set of states reachable after matching A B B A C E F G E F G C A A\n\n0 1 2 3 4 5 6 7 8 9 13 16 17 18 19 20 : set of states reachable via e-transitions after matching A B B A C E F G E F G C A A\n\n6 : set of states reachable after matching A B B A C E F G E F G C A A B\n\n0 1 2 3 5 6 7 8 9 13 16 17 18 19 20 : set of states reachable via e-transitions after matching A B B A C E F G E F G C A A B\n", "support_files": [], "metadata": {"number": "5.4.6", "chapter": 5, "chapter_title": "Strings", "section": 5.4, "section_title": "Regular Expressions", "type": "Exercise", "code_execution": false}} {"question": "Write a regular expression for each of the following sets of binary strings:\na. Contains at least three consecutive 1s\nb. Contains the substring 110\nc. Contains the substring 1101100\nd. Does not contain the substring 110", "answer": "5.4.8\n\na. Contains at least three consecutive 1s: (0|1)*(111)+(0|1)*\nb. Contains the substring 110: (0|1)*110(0|1)*\nc. Contains the substring 1101100: (0|1)*1101100(0|1)*\nd. Does not contain the substring 110: (0|10)*1*\n", "support_files": [], "metadata": {"number": "5.4.8", "chapter": 5, "chapter_title": "Strings", "section": 5.4, "section_title": "Regular Expressions", "type": "Exercise", "code_execution": false}} {"question": "Write a regular expression for each of the following sets of binary strings:\na. Has at least 3 characters, and the third character is 0\nb. Number of 0s is a multiple of 3\nc. Starts and ends with the same character\nd. Odd length\ne. Starts with 0 and has odd length, or starts with 1 and has even length\nf. Length is at least 1 and at most 3", "answer": "a. At least 3 characters, third character is 0:\n`(0|1)(0|1)0(0|1)*`\n\nb. Number of 0s is a multiple of 3:\n`1*(01*01*01*)*`\n\nc. Starts and ends with the same character:\n`0|1|0(0|1)*0|1(0|1)*1`\n\nd. Odd length:\n`((0|1)(0|1))*(0|1)`\n\ne. Starts with 0 and has odd length, or starts with 1 and has even length:\n`0((0|1)(0|1))*|1(0|1)((0|1)(0|1))*`\n\nf. Length is at least 1 and at most 3:\n`(0|1)|(0|1)(0|1)|(0|1)(0|1)(0|1)`", "support_files": [], "metadata": {"number": "5.4.10", "chapter": 5, "chapter_title": "Strings", "section": 5.4, "section_title": "Regular Expressions", "type": "Exercise", "code_execution": false}} {"question": "Challenging REs. Construct an RE that describes each of the following sets of strings over the binary alphabet:\na. All strings except 11 or 111\nb. Strings with 1 in every odd-number bit position\nc. Strings with at least two 0s and at most one 1\nd. Strings with no two consecutive 1s", "answer": "5.4.13 - Challenging REs\n\na. All strings except 11 or 111: 1|(1*01*|1111(0|1)*)*\nb. Strings with 1 in every odd-number bit position: (10|11)*1*\nc. Strings with at least two 0s and at most one 1: 1?00+|0+1?0+|00+1?\nd. Strings with no two consecutive 1s: (0|10)*1?\n", "support_files": [], "metadata": {"number": "5.4.13", "chapter": 5, "chapter_title": "Strings", "section": 5.4, "section_title": "Regular Expressions", "type": "Creative Problem", "code_execution": false}} {"question": "Wildcard. Add to NFA the capability to handle wildcards.", "answer": "package chapter5.section4;\n\nimport chapter1.section3.Bag;\nimport chapter4.section2.DirectedDFS;\nimport edu.princeton.cs.algs4.StdOut;\n\n/**\n * Created by Rene Argento on 23/03/18.\n */\npublic class Exercise17_Wildcard {\n\n public class RegularExpressionMatcherWildcard extends RegularExpressionMatcher {\n\n public RegularExpressionMatcherWildcard(String regularExpressionString) {\n super(regularExpressionString);\n }\n\n @Override\n public boolean recognizes(String text) {\n Bag allPossibleStates = new Bag<>();\n DirectedDFS directedDFS = new DirectedDFS(digraph, 0);\n\n for (int vertex = 0; vertex < digraph.vertices(); vertex++) {\n if (directedDFS.marked(vertex)) {\n allPossibleStates.add(vertex);\n }\n }\n\n for (int i = 0; i < text.length(); i++) {\n // Compute possible NFA states for text[i + 1]\n Bag states = new Bag<>();\n\n for (int vertex : allPossibleStates) {\n if (vertex < numberOfStates) {\n if (regularExpression[vertex] == text.charAt(i) || regularExpression[vertex] == '.') {\n states.add(vertex + 1);\n }\n }\n }\n\n allPossibleStates = new Bag<>();\n directedDFS = new DirectedDFS(digraph, states);\n\n for (int vertex = 0; vertex < digraph.vertices(); vertex++) {\n if (directedDFS.marked(vertex)) {\n allPossibleStates.add(vertex);\n }\n }\n\n // Optimization if no states are reachable\n if (allPossibleStates.size() == 0) {\n return false;\n }\n }\n\n\n for (int vertex : allPossibleStates) {\n if (vertex == numberOfStates) {\n return true;\n }\n }\n\n return false;\n }\n\n }\n\n public static void main(String[] args) {\n Exercise17_Wildcard wildcard = new Exercise17_Wildcard();\n\n String pattern1 = \".*NEEDLE.*\";\n RegularExpressionMatcherWildcard regularExpressionMatcherWildcard1 =\n wildcard.new RegularExpressionMatcherWildcard(pattern1);\n String text1 = \"A HAYSTACK NEEDLE IN\";\n boolean matches1 = regularExpressionMatcherWildcard1.recognizes(text1);\n StdOut.println(\"Text 1 check: \" + matches1 + \" Expected: true\");\n\n String pattern2 = \"R.N.1.3\";\n RegularExpressionMatcherWildcard regularExpressionMatcherWildcard2 =\n wildcard.new RegularExpressionMatcherWildcard(pattern2);\n String text2 = \"RENE123\";\n boolean matches2 = regularExpressionMatcherWildcard2.recognizes(text2);\n StdOut.println(\"Text 2 check: \" + matches2 + \" Expected: true\");\n\n String text3 = \"RRNN193\";\n boolean matches3 = regularExpressionMatcherWildcard2.recognizes(text3);\n StdOut.println(\"Text 3 check: \" + matches3 + \" Expected: true\");\n\n String text4 = \"RENE333\";\n boolean matches4 = regularExpressionMatcherWildcard2.recognizes(text4);\n StdOut.println(\"Text 4 check: \" + matches4 + \" Expected: false\");\n }\n\n}\n", "support_files": [], "metadata": {"number": "5.4.17", "chapter": 5, "chapter_title": "Strings", "section": 5.4, "section_title": "Regular Expressions", "type": "Creative Problem", "code_execution": false}} {"question": "Proof. Develop a version of NFA that prints a proof that a given string is in the language recognized by the NFA (a sequence of state transitions that ends in the accept state).", "answer": "package chapter5.section4;\n\nimport chapter1.section3.Bag;\nimport chapter1.section3.Stack;\nimport chapter4.section2.Digraph;\nimport edu.princeton.cs.algs4.StdOut;\n\nimport java.util.StringJoiner;\n\n/**\n * Created by Rene Argento on 25/03/18.\n */\n@SuppressWarnings(\"unchecked\")\npublic class Exercise22_Proof {\n\n private class State {\n private int id;\n private State previous;\n\n State(int id, State previous) {\n this.id = id;\n this.previous = previous;\n }\n }\n\n public class RegularExpressionMatcherWithProof extends RegularExpressionMatcher {\n\n public RegularExpressionMatcherWithProof(String regularExpression) {\n super(regularExpression);\n }\n\n @Override\n public boolean recognizes(String text) {\n Bag allPossibleStates = new Bag<>();\n State sourceState = new State(0, null);\n DirectedDFS directedDFS = new DirectedDFS(digraph, sourceState);\n\n for (State newSate : directedDFS.getNewStates()) {\n allPossibleStates.add(newSate);\n }\n\n for (int i = 0; i < text.length(); i++) {\n // Compute possible NFA states for text[i + 1]\n Bag states = new Bag<>();\n\n for (State state : allPossibleStates) {\n if (state.id < numberOfStates) {\n\n if (setsMatchMap.contains(state.id)) {\n recognizeSet(text, i, state, states);\n } else if (regularExpression[state.id] == text.charAt(i)\n || regularExpression[state.id] == '.') {\n addNextState(states, state, state.id + 1);\n }\n }\n }\n\n allPossibleStates = new Bag<>();\n directedDFS = new DirectedDFS(digraph, states);\n\n if (directedDFS.getNewStates() != null) {\n for (State newSate : directedDFS.getNewStates()) {\n allPossibleStates.add(newSate);\n }\n } else {\n // Optimization if no states are reachable\n StdOut.println(\"Text was not recognized by the DFA\");\n return false;\n }\n }\n\n for (State state : allPossibleStates) {\n if (state.id == numberOfStates) {\n printProof(state);\n return true;\n }\n }\n\n StdOut.println(\"Text was not recognized by the DFA\");\n return false;\n }\n\n private void recognizeSet(String text, int index, State state, Bag states) {\n int indexOfRightSquareBracket = setsMatchMap.get(state.id);\n\n // Is it a range?\n if (regularExpression[state.id + 1] == '-') { // No need to worry about out of bounds indexes\n char leftRangeIndex = regularExpression[state.id];\n char rightRangeIndex = regularExpression[state.id + 2];\n\n if (leftRangeIndex <= text.charAt(index) && text.charAt(index) <= rightRangeIndex) {\n if (!isCharPartOfComplementSet(text, index, state.id)) {\n addNextState(states, state, indexOfRightSquareBracket);\n }\n } else if (setsComplementMap.contains(state.id)\n && !isCharPartOfComplementSet(text, index, state.id)) {\n addNextState(states, state, indexOfRightSquareBracket);\n }\n } else if (regularExpression[state.id] == text.charAt(index) || regularExpression[state.id] == '.') {\n if (!isCharPartOfComplementSet(text, index, state.id)) {\n addNextState(states, state, indexOfRightSquareBracket);\n }\n } else if (setsComplementMap.contains(state.id) && !isCharPartOfComplementSet(text, index, state.id)) {\n addNextState(states, state, indexOfRightSquareBracket);\n }\n }\n\n private void addNextState(Bag states, State currentState, int nextStateId) {\n states.add(new State(nextStateId, currentState));\n }\n\n private void printProof(State state) {\n Stack states = new Stack<>();\n\n states.push(state);\n while (state.previous != null) {\n states.push(state.previous);\n state = state.previous;\n }\n\n StringJoiner proof = new StringJoiner(\" -> \");\n while (!states.isEmpty()) {\n proof.add(String.valueOf(states.pop().id));\n }\n\n StdOut.println(proof);\n }\n }\n\n public class DirectedDFS {\n\n private boolean[] visited;\n private Bag newStates;\n\n public DirectedDFS(Digraph digraph, State source) {\n visited = new boolean[digraph.vertices()];\n newStates = new Bag<>();\n\n dfs(digraph, source);\n }\n\n public DirectedDFS(Digraph digraph, Iterable sources) {\n visited = new boolean[digraph.vertices()];\n newStates = new Bag<>();\n\n for (State source : sources) {\n if (!visited[source.id]) {\n dfs(digraph, source);\n }\n }\n }\n\n private void dfs(Digraph digraph, State source) {\n visited[source.id] = true;\n newStates.add(source);\n\n for (int neighbor : digraph.adjacent(source.id)) {\n if (!visited[neighbor]) {\n State newState = new State(neighbor, source);\n newStates.add(newState);\n\n dfs(digraph, newState);\n }\n }\n }\n\n public boolean marked(int vertex) {\n return visited[vertex];\n }\n\n public Bag getNewStates() {\n return newStates;\n }\n }\n\n public static void main(String[] args) {\n Exercise22_Proof proof = new Exercise22_Proof();\n\n String pattern1 = \"RENE[^ABC]\";\n Exercise22_Proof.RegularExpressionMatcherWithProof regularExpressionMatcherWithProof1 =\n proof.new RegularExpressionMatcherWithProof(pattern1);\n String text1 = \"RENED\";\n StdOut.print(\"Proof 1: \");\n regularExpressionMatcherWithProof1.recognizes(text1);\n StdOut.println(\"Expected: 0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 9 -> 10\");\n\n String pattern2 = \"A[^A-Z0]+Z\";\n Exercise22_Proof.RegularExpressionMatcherWithProof regularExpressionMatcherWithProof2 =\n proof.new RegularExpressionMatcherWithProof(pattern2);\n String text2 = \"AbZ\";\n StdOut.print(\"\\nProof 2: \");\n regularExpressionMatcherWithProof2.recognizes(text2);\n StdOut.println(\"Expected: 0 -> 1 -> 2 -> 3 -> 7 -> 8 -> 9 -> 10\");\n\n String text3 = \"AabcdeZ\";\n StdOut.print(\"\\nProof 3: \");\n regularExpressionMatcherWithProof2.recognizes(text3);\n StdOut.println(\"Expected: 0 -> 1 -> 2 -> 3 -> 7 -> 8 -> 1 -> 2 -> 3 -> 7 -> 8 \" +\n \"-> 1 -> 2 -> 3 -> 7 -> 8 -> 1 -> 2 -> 3 -> 7 -> 8 -> 1 -> 2 -> 3 -> 7 -> 8 -> 9 -> 10\");\n\n String pattern3 = \"A[^A-Z0]+ZZ\";\n Exercise22_Proof.RegularExpressionMatcherWithProof regularExpressionMatcherWithProof3 =\n proof.new RegularExpressionMatcherWithProof(pattern3);\n String text4 = \"AbcZZ\";\n StdOut.print(\"\\nProof 4: \");\n regularExpressionMatcherWithProof3.recognizes(text4);\n StdOut.println(\"Expected: 0 -> 1 -> 2 -> 3 -> 7 -> 8 -> 1 -> 2 -> 3 -> 7 -> 8 -> 9 -> 10 -> 11\");\n\n String pattern4 = \"A[^A-Z0]*ZZ\";\n Exercise22_Proof.RegularExpressionMatcherWithProof regularExpressionMatcherWithProof4 =\n proof.new RegularExpressionMatcherWithProof(pattern4);\n String text5 = \"AZZ\";\n StdOut.print(\"\\nProof 5: \");\n regularExpressionMatcherWithProof4.recognizes(text5);\n StdOut.println(\"Expected: 0 -> 1 -> 8 -> 9 -> 10 -> 11\");\n\n String text6 = \"Abcdef123ZZ\";\n StdOut.print(\"\\nProof 6: \");\n regularExpressionMatcherWithProof4.recognizes(text6);\n StdOut.println(\"Expected: 0 -> 1 -> 2 -> 3 -> 7 -> 8 \" +\n \"-> 1 -> 2 -> 3 -> 7 -> 8 \" +\n \"-> 1 -> 2 -> 3 -> 7 -> 8 \" +\n \"-> 1 -> 2 -> 3 -> 7 -> 8 \" +\n \"-> 1 -> 2 -> 3 -> 7 -> 8 \" +\n \"-> 1 -> 2 -> 3 -> 7 -> 8 \" +\n \"-> 1 -> 2 -> 3 -> 7 -> 8 \" +\n \"-> 1 -> 2 -> 3 -> 7 -> 8 \" +\n \"-> 9 -> 10 -> 11\");\n\n String pattern5 = \"A([^A-Z0]|[^a-f])+[^a-f]Z\";\n Exercise22_Proof.RegularExpressionMatcherWithProof regularExpressionMatcherWithProof5 =\n proof.new RegularExpressionMatcherWithProof(pattern5);\n String text7 = \"ABgZ\";\n StdOut.print(\"\\nProof 7: \");\n regularExpressionMatcherWithProof5.recognizes(text7);\n StdOut.println(\"Expected: 0 -> 1 -> 10 -> 11 -> 12 -> 15 -> 16 -> 17 -> 18 -> 19 -> 20 -> 23 -> 24 -> 25\");\n\n String text8 = \"ABCDEFGagZ\";\n StdOut.print(\"\\nProof 8: \");\n regularExpressionMatcherWithProof5.recognizes(text8);\n StdOut.println(\"Expected: 0 -> 1 -> 10 -> 11 -> 12 -> 15 -> 16 -> 17 -> \" +\n \"1 -> 10 -> 11 -> 12 -> 15 -> 16 -> 17 -> \" +\n \"1 -> 10 -> 11 -> 12 -> 15 -> 16 -> 17 -> \" +\n \"1 -> 10 -> 11 -> 12 -> 15 -> 16 -> 17 -> \" +\n \"1 -> 10 -> 11 -> 12 -> 15 -> 16 -> 17 -> \" +\n \"1 -> 10 -> 11 -> 12 -> 15 -> 16 -> 17 -> \" +\n \"1 -> 2 -> 3 -> 4 -> 8 -> 9 -> 16 -> 17 -> \" +\n \"18 -> 19 -> 20 -> 23 -> 24 -> 25\");\n\n String text9 = \"ABZ\";\n StdOut.print(\"\\nProof 9: \");\n regularExpressionMatcherWithProof5.recognizes(text9);\n StdOut.println(\"Expected: Text was not recognized by the DFA\");\n }\n}\n", "support_files": [], "metadata": {"number": "5.4.22", "chapter": 5, "chapter_title": "Strings", "section": 5.4, "section_title": "Regular Expressions", "type": "Creative Problem", "code_execution": false}} {"question": "Given a example of a uniquely decodable code that is not prefix-free.", "answer": "5.5.2\n\nExample of a uniquely decodable code that is not prefix-free:\nAny suffix-free code is uniquely decodable.\n\nExample: { 0, 01, 011, 0111 }\n", "support_files": [], "metadata": {"number": "5.5.2", "chapter": 5, "chapter_title": "Strings", "section": 5.5, "section_title": "Data Compression", "type": "Exercise", "code_execution": false}} {"question": "Give an example of a uniquely decodable code that is not prefix free or suffix free.", "answer": "5.5.3\n\nExample of a uniquely decodable code that is not prefix-free or suffix-free:\n{ 0011, 011, 11, 1110 } or { 01, 10, 011, 110 }\n", "support_files": [], "metadata": {"number": "5.5.3", "chapter": 5, "chapter_title": "Strings", "section": 5.5, "section_title": "Data Compression", "type": "Exercise", "code_execution": false}} {"question": "Are { 1, 100000, 00 } and { 01, 1001, 1011, 111, 1110 } uniquely decodable? If not, find a string with two encodings.", "answer": "5.5.4\n\n{ 1, 100000, 00 } is uniquely decodable.\n\n{ 01, 1001, 1011, 111, 1110 } is not uniquely decodable. \nThe string 11101111001 can be decoded both as 1110-111-1001 and 111-01-1110-01.\n", "support_files": [], "metadata": {"number": "5.5.4", "chapter": 5, "chapter_title": "Strings", "section": 5.5, "section_title": "Data Compression", "type": "Exercise", "code_execution": false}} {"question": "Use RunLength on the file q64x96.bin from the booksite. How many bits are there in the compressed file?", "answer": "5.5.5\n\nThe file q128x192.bin was not found anywhere on the booksite or in the data URL https://algs4.cs.princeton.edu/code/algs4-data.zip\nHowever, the file q64x96.bin exists in the booksite on the aforementioned algs4-data.zip and on the hidden URL https://algs4.cs.princeton.edu/55compression/q64x96.bin .\n\nIn the uncompressed file there are 6144 bits.\nIn the compressed file there are 2296 bits.\n\nCommands used:\n% javac -cp algs4.jar BinaryDump.java\n% javac -cp algs4.jar RunLengthEncoding.java\n% java -cp algs4.jar:. RunLengthEncoding - < q64x96.bin | java -cp algs4.jar:. BinaryDump 0\n", "support_files": [], "metadata": {"number": "5.5.5", "chapter": 5, "chapter_title": "Strings", "section": 5.5, "section_title": "Data Compression", "type": "Exercise", "code_execution": false}} {"question": "How many bits are needed to encode N copies of the symbol a (as a function of N)? N copies of the sequence abc?", "answer": "5.5.6 \n\nCopies of symbol a:\n\n% more 5.5_input_1a.txt\na\n\n% more 5.5_input_2a.txt\naa\n\n% more 5.5_input_3a.txt\naaa\n\n% more 5.5_input_20a.txt\naaaaaaaaaaaaaaaaaaaa\n\n*** Run-length encoding ***\n\n% java -cp algs4.jar:. RunLengthEncoding - < 5.5_input_1a.txt | java -cp algs4.jar:. BinaryDump 0\n32 bits\n\n% java -cp algs4.jar:. RunLengthEncoding - < 5.5_input_2a.txt | java -cp algs4.jar:. BinaryDump 0\n64 bits\n\n% java -cp algs4.jar:. RunLengthEncoding - < 5.5_input_3a.txt | java -cp algs4.jar:. BinaryDump 0\n96 bits\n\n% java -cp algs4.jar:. RunLengthEncoding - < 5.5_input_20a.txt | java -cp algs4.jar:. BinaryDump 0\n640 bits\n\nBits needed to encode N copies of the symbol a: 32N\n\n*** Huffman encoding ***\n\n% java -cp algs4.jar:. edu.princeton.cs.algs4.Huffman - < 5.5_input_1a.txt | java -cp algs4.jar:. BinaryDump 0\n56 bits\n\n% java -cp algs4.jar:. edu.princeton.cs.algs4.Huffman - < 5.5_input_2a.txt | java -cp algs4.jar:. BinaryDump 0\n56 bits\n\n% java -cp algs4.jar:. edu.princeton.cs.algs4.Huffman - < 5.5_input_3a.txt | java -cp algs4.jar:. BinaryDump 0\n56 bits\n\n% java -cp algs4.jar:. edu.princeton.cs.algs4.Huffman - < 5.5_input_20a.txt | java -cp algs4.jar:. BinaryDump 0\n72 bits\n\nNumber of a symbols - bits needed to encode\n1-5: 56\n6-13 : 64\n14-21: 72\n22-29: 80\n30-37: 88\n38: 96\n\nBits needed to encode N copies of the symbol a: 56 + ((N - 6) / 8 + 1) * 8\n\n*** LZW encoding ***\n\n% java -cp algs4.jar:. edu.princeton.cs.algs4.LZW - < 5.5_input_1a.txt | java -cp algs4.jar:. BinaryDump 0\n24 bits\n\n% java -cp algs4.jar:. edu.princeton.cs.algs4.LZW - < 5.5_input_2a.txt | java -cp algs4.jar:. BinaryDump 0\n40 bits\n\n% java -cp algs4.jar:. edu.princeton.cs.algs4.LZW - < 5.5_input_3a.txt | java -cp algs4.jar:. BinaryDump 0\n40 bits\n\n% java -cp algs4.jar:. edu.princeton.cs.algs4.LZW - < 5.5_input_20a.txt | java -cp algs4.jar:. BinaryDump 0\n88 bits\n\nNumber of a symbols - bits needed to encode\n1: 24\n2-3: 40\n4-6: 48\n7-10: 64\n11-15: 72 bits\n16-21: 88 bits\n22-28: 96 bits\n29: 112 bits\n\n i<=N\nBits needed to encode N copies of the symbol a: 16 + E 8 if j % 2 == 1\n 16 if j % 2 == 0\n i=1, j=1\n i+=j; j++\n\nCopies of symbol abc:\n\n% more 5.5_input_1abc.txt\nabc\n\n% more 5.5_input_2abc.txt\nabcabc\n\n% more 5.5_input_3abc.txt\nabcabcabc\n\n% more 5.5_input_20a.txt\nabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc\n\n*** Run-length encoding ***\n\n% java -cp algs4.jar:. RunLengthEncoding - < 5.5_input_1abc.txt | java -cp algs4.jar:. BinaryDump 0\n96 bits\n\n% java -cp algs4.jar:. RunLengthEncoding - < 5.5_input_2abc.txt | java -cp algs4.jar:. BinaryDump 0\n192 bits\n\n% java -cp algs4.jar:. RunLengthEncoding - < 5.5_input_3abc.txt | java -cp algs4.jar:. BinaryDump 0\n288 bits\n\n% java -cp algs4.jar:. RunLengthEncoding - < 5.5_input_20abc.txt | java -cp algs4.jar:. BinaryDump 0\n1920 bits\n\nBits needed to encode N copies of the sequence abc: 96N\n\n*** Huffman encoding ***\n\n% java -cp algs4.jar:. edu.princeton.cs.algs4.Huffman - < 5.5_input_1abc.txt | java -cp algs4.jar:. BinaryDump 0\n72 bits\n\n% java -cp algs4.jar:. edu.princeton.cs.algs4.Huffman - < 5.5_input_2abc.txt | java -cp algs4.jar:. BinaryDump 0\n72 bits\n\n% java -cp algs4.jar:. edu.princeton.cs.algs4.Huffman - < 5.5_input_3abc.txt | java -cp algs4.jar:. BinaryDump 0\n80 bits\n\n% java -cp algs4.jar:. edu.princeton.cs.algs4.Huffman - < 5.5_input_20abc.txt | java -cp algs4.jar:. BinaryDump 0\n168 bits\n\nNumber of abc sequences - bits needed to encode\n1-2: 72\n3: 80\n4-5: 88\n6-7: 96\n8: 104\n9-10: 112\n11: 120\n12-13: 128\n14-15: 136\n16: 144\n17-18: 152\n19: 160\n20-21: 168\n22-23: 176\n24: 184\n\n i<=N\nBits needed to encode N copies of the sequence abc: 64 + E 8\n i=1, j=2\n i+=j; j=2 if j == 1 || (i - 4) % 8 == 0 || (i - 6) % 8 == 0\n j=1 [else]\n\n*** LZW encoding ***\n\n% java -cp algs4.jar:. edu.princeton.cs.algs4.LZW - < 5.5_input_1abc.txt | java -cp algs4.jar:. BinaryDump 0\n48 bits\n\n% java -cp algs4.jar:. edu.princeton.cs.algs4.LZW - < 5.5_input_2abc.txt | java -cp algs4.jar:. BinaryDump 0\n72 bits\n\n% java -cp algs4.jar:. edu.princeton.cs.algs4.LZW - < 5.5_input_3abc.txt | java -cp algs4.jar:. BinaryDump 0\n88 bits\n\n% java -cp algs4.jar:. edu.princeton.cs.algs4.LZW - < 5.5_input_20abc.txt | java -cp algs4.jar:. BinaryDump 0\n232 bits\n\nNumber of abc sequences - bits needed to encode\n1: 48\n2: 72\n3: 88\n4: 96\n5: 112\n6: 120\n7: 136\n8: 144\n9-10: 160\n11: 168\n12-13: 184\n14-15: 192\n16-17: 208\n18-19: 216\n20-21: 232\n22-23: 240\n\n i<=N\nBits needed to encode N copies of the sequence abc: E 48 if i == 1\n 24 [else] if i == 2\n 16 [else] if k == 1\n 8 [else] if k == 2\n i=1, j=1, k=1\n i+=j; k=1 if k == 2; j=1 if i < 9 || i == 11\n k=2 if k == 1; j=2 [else]\n", "support_files": [], "metadata": {"number": "5.5.6", "chapter": 5, "chapter_title": "Strings", "section": 5.5, "section_title": "Data Compression", "type": "Exercise", "code_execution": false}} {"question": "Give the result of encoding the strings ab, abab, ababab, abababab, ... (strings consisting of N repetitions of ab) with run-length, Huffman, and LZW encoding. What is the compression ratio as a function of N?", "answer": "Let the input be `(ab)^N`, so the uncompressed input has `2N` 8-bit characters, or `16N` bits.\n\nRun-length encoding in the algs4 binary format emits `64N + 8` bits for this alternating input. Its compression ratio is therefore\n\n`(64N + 8) / (16N) = 4 + 1/(2N)`.\n\nSo run-length encoding expands the data by about 4x.\n\nHuffman coding has two symbols with equal frequency, so the data portion uses one bit per input character, or `2N` data bits. The algs4 format also writes a trie for the two leaves and a 32-bit character count, for `2N + 51` bits before byte padding. With byte padding:\n\n`8 * ceil((2N + 51) / 8)` bits,\n\nand the compression ratio is\n\n`8 * ceil((2N + 51) / 8) / (16N)`,\n\nwhich tends to `1/8`.\n\nLZW parses the alternating string into longer and longer repeated phrases. If `c(N)` is the number of LZW phrases produced by the greedy parse of `(ab)^N`, algs4 writes `c(N) + 1` fixed-width 12-bit codes including EOF, rounded to a byte boundary:\n\n`8 * ceil(12(c(N) + 1) / 8)` bits.\n\nHere `c(N) = Theta(sqrt(N))`, so the LZW compression ratio is `Theta(1 / sqrt(N))`. For example, the measured algs4 outputs are 40, 48, 64, 72, 160, and 352 bits for `N = 1, 2, 3, 4, 20, 100`, respectively; for `N = 100`, the ratio is `352 / 1600 = 22%`, not `352%`.", "support_files": [], "metadata": {"number": "5.5.8", "chapter": 5, "chapter_title": "Strings", "section": 5.5, "section_title": "Data Compression", "type": "Exercise", "code_execution": false}} {"question": "In the style of the figure in the text, show the Huffman coding tree construction process when you use Huffman for the string \"it was the age of foolishness”. How many bits does the compressed bitstream require?", "answer": "5.5.10\n\ntext: it was the age of foolishness\n\nFrequencies\n2 2 5 1 2 4 2 3 1 3 2 1 1\ni t SP w a s h e g o f l n\n\nOrdered frequencies and trie construction\n1 1 1 1 2 2 2 2 2 3 3 4 5\nw g l n i t a h f e o s SP\n \n\n1 1 2 2 2 2 2 2 3 3 4 5\nl n 1 1 i t a h f e o s SP\n w g\n\n 2 2 2 2 2 2 2 3 3 4 5\n1 1 1 1 i t a h f e o s SP\nl n w g\n\n2 2 2 2 2 3 3 4 4 5\ni t a h f e o 2 2 s SP\n 1 1 1 1\n l n w g\n\n2 2 2 3 3 4 4 4 5\na h f e o 2 2 2 2 s SP\n i t 1 1 1 1\n l n w g\n\n2 3 3 4 4 4 4 5\nf e o 2 2 2 2 2 2 s SP\n a h i t 1 1 1 1\n l n w g\n\n3 4 4 4 4 5 5\no 2 2 2 2 2 2 s 2 3 SP\n a h i t 1 1 1 1 f e\n l n w g\n\n 4 4 4 5 5 7\n2 2 2 2 s 2 3 SP 3 4\ni t 1 1 1 1 f e o 2 2\n l n w g a h\n\n4 5 5 7 8\ns 2 3 SP 3 4 4 4\n f e o 2 2 2 2 2 2\n a h i t 1 1 1 1\n l n w g\n\n 5 7 8 9\nSP 3 4 4 4 4 5\n o 2 2 2 2 2 2 s 2 3\n a h i t 1 1 1 1 f e\n l n w g\n\n 8 9 12\n 4 4 4 5 5 7\n2 2 2 2 s 2 3 SP 3 4\ni t 1 1 1 1 f e o 2 2\n l n w g a h\n\n 12 17\n 5 7 8 9\nSP 3 4 4 4 4 5\n o 2 2 2 2 2 2 s 2 3 \n a h i t 1 1 1 1 f e\n l n w g \n\n 29\n 12 17\n 5 7 8 9\nSP 3 4 4 4 4 5\n o 2 2 2 2 2 2 s 2 3 \n a h i t 1 1 1 1 f e\n l n w g \n\nCodeword table\nkey value\nSP 00\na 0110\ne 1111\nf 1110\ng 10111\nh 0111\ni 1000\nl 10100\nn 10101\no 010\ns 110\nt 1001\nw 10110\n\nCompressed bitstream (characters only): 1000 1001 10110 0110 110 1001 0111 1111 0110 10111 1111 010 1110 1110 010 010 10100 1000 110 0111 10101 1111 110 110\n\nCompressed bitstream (trie):\n0001 00100000 001 01101111 001 01100001 01 01101000 00001 01101001 01 01110100 0001 01101100 01 01101110 001 01110111 01 01100111 001 01110011 001 01100110 01 01100101\n\nCompressed bitstream (number of characters: 29):\n00011101\n\nBits required: 103 + 142 + 8 = 253\n", "support_files": [], "metadata": {"number": "5.5.10", "chapter": 5, "chapter_title": "Strings", "section": 5.5, "section_title": "Data Compression", "type": "Exercise", "code_execution": false}} {"question": "Suppose that all of the symbol frequencies are equal. Describe the Huffman code.", "answer": "If all symbol frequencies are equal, Huffman has no reason to prefer one symbol over another, so the code is a balanced prefix code. The code is not unique: ties in the priority queue may be broken in many ways.\n\nIf the alphabet size `R` is a power of two, every codeword has length `lg R`. If `R` is not a power of two, codeword lengths differ by at most one: each length is either `floor(lg R)` or `ceil(lg R)`.\n\nIt is not correct to say that Huffman always produces the same length as the original input. Compression depends on the original fixed-width representation and on the header/trie overhead.", "support_files": [], "metadata": {"number": "5.5.13", "chapter": 5, "chapter_title": "Strings", "section": 5.5, "section_title": "Data Compression", "type": "Exercise", "code_execution": false}} {"question": "Characterize the tricky situation in LZW coding.", "answer": "5.5.17\n\nThe tricky situation in LZW coding happens during expansion when the codeword read to get the lookahead character has the same value as the next codeword to be added in the codeword table. This happens whenever the algorithm encounters cScSc, where c is a symbol and S is a string, cS is in the dictionary already but cSc is not.\n", "support_files": [], "metadata": {"number": "5.5.17", "chapter": 5, "chapter_title": "Strings", "section": 5.5, "section_title": "Data Compression", "type": "Exercise", "code_execution": false}} {"question": "Prove the following fact about Huffman codes: If the frequency of symbol i is strictly larger than the frequency of symbol j, then the length of the codeword for symbol i is less than or equal to the length of the codeword for symbol j.", "answer": "5.5.22\n\nIf the frequency of symbol i is strictly larger than the frequency of symbol j, then the length of the codeword for symbol i is less than or equal to the length of the codeword for symbol j.\n\nProof:\nSuppose that C is an optimal Huffman code, L(C) is the sum of all the codeword lengths in the code C, C(x) is the codeword associated to the symbol x in C, f(x) is the frequency of occurrence of symbol x and l(x) is the length of C(x). \nLet C’ be the code interchanging C(i) and C(j), and, as mentioned on the exercise statement, f(i) > f(j).\nThen\n0 <= L(C’) - L(C)\n = E f(k) * l’(k) - E f(k) * l(k)\n k k \n = f(i) * l(j) + f(j) * l(i) - f(i) * l(i) - f(j) * l(j)\n = (f(i) - f(j)) * (l(j) - l(i)) \n\nand hence l(j) - l(i) >= 0, or equivalently, l(i) <= l(j).\n\nReference: http://www.cs.cmu.edu/~aarti/Class/10704_Fall16/lec10.pdf\n", "support_files": [], "metadata": {"number": "5.5.22", "chapter": 5, "chapter_title": "Strings", "section": 5.5, "section_title": "Data Compression", "type": "Exercise", "code_execution": false}} {"question": "What would be the result of breaking up a Huffman-encoded string into five-bit characters and Huffman-encoding that string?", "answer": "5.5.23\n\nBreaking up a Huffman-encoded string into five-bit characters and Huffman-encoding that string is a process called Double Huffman Coding and it would lead to a string of final length between N / 5 and N.\n\nProof:\n\nConsider that the string has N bits. The best case happens when all 5-bit strings are equal: the resulting compressed string length is N / 5.\n\nExample: \n01010010100101001010\nis broken into \n01010 01010 01010 01010\n\nWith the Huffman code 01010 -> 0, the string becomes:\n0000\n\nThe original Huffman-encoded string length was 20 (N) and the final string length is 4 (N / 5).\n\nWith 5 bits there are 2^5 possible five-bit characters. The worst case happens when all five-bit characters are different and there is one occurrence of each possible five-bit character. In this case, the Huffman encoding tree will be a complete binary tree and all codewords will have length 5. All five-bit characters will be encoded to codewords of length 5 and the final string length will be N (the same length as the original Huffman-encoded string).\n\n\nThis is an idealized data-bit bound. A real Huffman file also stores a trie/header and may need padding, so for short inputs the second Huffman encoding can be larger than this bound suggests.\n", "support_files": [], "metadata": {"number": "5.5.23", "chapter": 5, "chapter_title": "Strings", "section": 5.5, "section_title": "Data Compression", "type": "Exercise", "code_execution": false}} {"question": "In the style of the figures in the text, show the encoding trie and the compression and expansion processes when LZW is used for the string\nit was the best of times it was the worst of times", "answer": "5.5.24\n\ntext: it was the best of times it was the worst of times\n\nCompression process\n\ninput I T W A S T H E B E S T O F T I M E S I T W A S T H E W O R S T O F T I M E S\nmatches I T W A S T H E B E ST O F T I M ES IT WA ST HE W O R STO FT IM ES \noutput 49 54 57 41 53 54 48 45 42 45 85 4F 46 54 49 4D 8A 81 83 85 87 57 4F 52 8B 8D 8F 8A 80\n\n IT 81 IT IT IT IT IT IT IT IT IT IT IT IT IT IT IT IT IT IT IT IT IT IT IT IT IT IT IT \n TW 82 TW TW TW TW TW TW TW TW TW TW TW TW TW TW TW TW TW TW TW TW TW TW TW TW TW TW \n WA 83 WA WA WA WA WA WA WA WA WA WA WA WA WA WA WA WA WA WA WA WA WA WA WA WA WA \n AS 84 AS AS AS AS AS AS AS AS AS AS AS AS AS AS AS AS AS AS AS AS AS AS AS AS \n ST 85 ST ST ST ST ST ST ST ST ST ST ST ST ST ST ST ST ST ST ST ST ST ST ST \n TH 86 TH TH TH TH TH TH TH TH TH TH TH TH TH TH TH TH TH TH TH TH TH TH \n HE 87 HE HE HE HE HE HE HE HE HE HE HE HE HE HE HE HE HE HE HE HE HE \n EB 88 EB EB EB EB EB EB EB EB EB EB EB EB EB EB EB EB EB EB EB EB \n BE 89 BE BE BE BE BE BE BE BE BE BE BE BE BE BE BE BE BE BE BE \n ES 8A ES ES ES ES ES ES ES ES ES ES ES ES ES ES ES ES ES ES \n STO 8B STO STO STO STO STO STO STO STO STO STO STO STO STO STO STO STO STO \n OF 8C OF OF OF OF OF OF OF OF OF OF OF OF OF OF OF OF \n FT 8D FT FT FT FT FT FT FT FT FT FT FT FT FT FT FT \n TI 8E TI TI TI TI TI TI TI TI TI TI TI TI TI TI \n IM 8F IM IM IM IM IM IM IM IM IM IM IM IM IM \n ME 90 ME ME ME ME ME ME ME ME ME ME ME ME \n ESI 91 ESI ESI ESI ESI ESI ESI ESI ESI ESI ESI ESI \n ITW 92 ITW ITW ITW ITW ITW ITW ITW ITW ITW ITW \n WAS 93 WAS WAS WAS WAS WAS WAS WAS WAS WAS \n STH 94 STH STH STH STH STH STH STH STH \n HEW 95 HEW HEW HEW HEW HEW HEW HEW \n WO 96 WO WO WO WO WO WO \n OR 97 OR OR OR OR OR \n RS 98 RS RS RS RS \n STOF 99 STOF STOF STOF \n FTI 9A FTI FTI \n IME 9B IME \n\nCodeword table\nkey value\nIT 81\nTW 82\nWA 83\nAS 84\nST 85\nTH 86\nHE 87\nEB 88\nBE 89\nES 8A\nSTO 8B\nOF 8C\nFT 8D\nTI 8E\nIM 8F\nME 90\nESI 91\nITW 92\nWAS 93\nSTH 94\nHEW 95\nWO 96\nOR 97\nRS 98\nSTOF 99\nFTI 9A\nIME 9B\n\nEncoding trie\n Root\n |\n ________________________________________________________________________________________________________\n / | | | | | | | | | | \\\n A 41 B 42 E 45 F 46 H 48 I 49 M 4D O 4F R 52 S 53 T 54 W 57\n | | | | | | | | | | | |\n S 84 E 89 ____ T 8D E 87 ____ E 90 ____ S 98 T 85 ________ ____ \n / \\ | | / \\ / \\ | / | \\ / \\\n B 88 S 8A I 9A W 95 M 8F T 81 F 8C R 97 ____ H 86 I 8E W 82 A 83 O 96\n | | | / \\ |\n I 91 E 9B W 92 H 94 O 8B S 93\n |\n F 99\n\nExpansion process\n\ninput 49 54 57 41 53 54 48 45 42 45 85 4F 46 54 49 4D 8A 81 83 85 87 57 4F 52 8B 8D 8F 8A 80\noutput I T W A S T H E B E ST O F T I M ES IT WA ST HE W O R STO FT IM ES\n\n 81 IT IT IT IT IT IT IT IT IT IT IT IT IT IT IT IT IT IT IT IT IT IT IT IT IT IT IT IT\n 82 TW TW TW TW TW TW TW TW TW TW TW TW TW TW TW TW TW TW TW TW TW TW TW TW TW TW TW\n 83 WA WA WA WA WA WA WA WA WA WA WA WA WA WA WA WA WA WA WA WA WA WA WA WA WA WA\n 84 AS AS AS AS AS AS AS AS AS AS AS AS AS AS AS AS AS AS AS AS AS AS AS AS AS\n 85 ST ST ST ST ST ST ST ST ST ST ST ST ST ST ST ST ST ST ST ST ST ST ST ST\n 86 TH TH TH TH TH TH TH TH TH TH TH TH TH TH TH TH TH TH TH TH TH TH TH\n 87 HE HE HE HE HE HE HE HE HE HE HE HE HE HE HE HE HE HE HE HE HE HE\n 88 EB EB EB EB EB EB EB EB EB EB EB EB EB EB EB EB EB EB EB EB EB\n 89 BE BE BE BE BE BE BE BE BE BE BE BE BE BE BE BE BE BE BE BE\n 8A ES ES ES ES ES ES ES ES ES ES ES ES ES ES ES ES ES ES ES\n 8B STO STO STO STO STO STO STO STO STO STO STO STO STO STO STO STO STO STO\n 8C OF OF OF OF OF OF OF OF OF OF OF OF OF OF OF OF OF\n 8D FT FT FT FT FT FT FT FT FT FT FT FT FT FT FT FT\n 8E TI TI TI TI TI TI TI TI TI TI TI TI TI TI TI\n 8F IM IM IM IM IM IM IM IM IM IM IM IM IM IM\n 90 ME ME ME ME ME ME ME ME ME ME ME ME ME\n 91 ESI ESI ESI ESI ESI ESI ESI ESI ESI ESI ESI ESI\n 92 ITW ITW ITW ITW ITW ITW ITW ITW ITW ITW ITW\n 93 WAS WAS WAS WAS WAS WAS WAS WAS WAS WAS\n 94 STH STH STH STH STH STH STH STH STH\n 95 HEW HEW HEW HEW HEW HEW HEW HEW\n 96 WO WO WO WO WO WO WO\n 97 OR OR OR OR OR OR\n 98 RS RS RS RS RS\n 99 STOF STOF STOF STOF\n 9A FTI FTI FTI\n 9B IME IME\n\nInverse codeword table\nkey value\n81 IT\n82 TW\n83 WA\n84 AS\n85 ST\n86 TH\n87 HE\n88 EB\n89 BE\n8A ES\n8B STO\n8C OF\n8D FT\n8E TI\n8F IM\n90 ME\n91 ESI\n92 ITW\n93 WAS\n94 STH\n95 HEW\n96 WO\n97 OR\n98 RS\n99 STOF\n9A FTI\n9B IME\n", "support_files": [], "metadata": {"number": "5.5.24", "chapter": 5, "chapter_title": "Strings", "section": 5.5, "section_title": "Data Compression", "type": "Exercise", "code_execution": false}} {"question": "Long repeats. Estimate the compression ratio achieved by run-length, Huffman, and LZW encoding for a string of length 2N formed by concatenating two copies of a random ASCII string of length N (see EXERCISE 5.5.9), under any assumptions that you think are reasonable.", "answer": "5.5.27 - Long repeats\n\nCompressing 2 * 1000 random characters (for N = 1000), with 16000 bits (8 bits per character).\n\n% java -cp algs4.jar:. RunLengthEncoding - < 5.5.27_random.txt | java -cp algs4.jar:. BinaryDump 0\n53736 bits\n\nCompression ratio: 53736 / 16000 = 335%\n\n% java -cp algs4.jar:. edu.princeton.cs.algs4.Huffman - < 5.5.27_random.txt | java -cp algs4.jar:. BinaryDump 0\n12624 bits\n\nCompression ratio: 12624 / 16000 = 79%\n\n% java -cp algs4.jar:. edu.princeton.cs.algs4.LZW - < 5.5.27_random.txt | java -cp algs4.jar:. BinaryDump 0\n13416 bits\n\nCompression ratio: 13416 / 16000 = 83%\n", "support_files": [], "metadata": {"number": "5.5.27", "chapter": 5, "chapter_title": "Strings", "section": 5.5, "section_title": "Data Compression", "type": "Creative Problem", "code_execution": false}} {"question": "Molecules travel very quickly (faster than a speeding jet) but diffuse slowly because they collide with other molecules, thereby changing their direction. Extend the model to have a boundary shape where two vessels are connected by a pipe containing two different types of particles. Run a simulation and measure the fraction of particles of each type in each vessel as a function of time.", "answer": "6.9\n\nResults\n\nTime 0\nLEFT VESSEL: 10 particles\nType 1: 10/10 Type 2: 0/10\nRIGHT VESSEL: 10 particles\nType 1: 0/10 Type 2: 10/10\n\nTime 1000\nLEFT VESSEL: 14 particles\nType 1: 9/14 Type 2: 5/14\nRIGHT VESSEL: 6 particles\nType 1: 1/6 Type 2: 5/6\n\nTime 2000\nLEFT VESSEL: 11 particles\nType 1: 6/11 Type 2: 5/11\nRIGHT VESSEL: 9 particles\nType 1: 4/9 Type 2: 5/9\n\nTime 3000\nLEFT VESSEL: 13 particles\nType 1: 7/13 Type 2: 6/13\nRIGHT VESSEL: 6 particles\nType 1: 2/6 Type 2: 4/6\n\nTime 4000\nLEFT VESSEL: 13 particles\nType 1: 7/13 Type 2: 6/13\nRIGHT VESSEL: 7 particles\nType 1: 3/7 Type 2: 4/7\n\nTime 5000\nLEFT VESSEL: 10 particles\nType 1: 6/10 Type 2: 4/10\nRIGHT VESSEL: 10 particles\nType 1: 4/10 Type 2: 6/10\n\nTime 6000\nLEFT VESSEL: 11 particles\nType 1: 6/11 Type 2: 5/11\nRIGHT VESSEL: 9 particles\nType 1: 4/9 Type 2: 5/9\n\nTime 7000\nLEFT VESSEL: 10 particles\nType 1: 5/10 Type 2: 5/10\nRIGHT VESSEL: 10 particles\nType 1: 5/10 Type 2: 5/10\n\nTime 8000\nLEFT VESSEL: 8 particles\nType 1: 3/8 Type 2: 5/8\nRIGHT VESSEL: 12 particles\nType 1: 7/12 Type 2: 5/12\n\nTime 9000\nLEFT VESSEL: 10 particles\nType 1: 3/10 Type 2: 7/10\nRIGHT VESSEL: 10 particles\nType 1: 7/10 Type 2: 3/10\n\nTime 10000\nLEFT VESSEL: 9 particles\nType 1: 5/9 Type 2: 4/9\nRIGHT VESSEL: 11 particles\nType 1: 5/11 Type 2: 6/11\n\nThe system tends to achieve a balance between the number of particles of both types on both vessels.\n", "support_files": [], "metadata": {"number": "6.9", "chapter": 6, "chapter_title": "Context", "section": 6.1, "section_title": "Collision Simulation", "type": "Exercise", "code_execution": false}} {"question": "After running a simulation, negate all velocities and then run the system backward. It should return to its original state! Measure roundoff error by measuring the difference between the final and original states of the system.", "answer": "6.10\n\nRoundoff error: 0.22176242098152166\n", "support_files": [], "metadata": {"number": "6.10", "chapter": 6, "chapter_title": "Context", "section": 6.1, "section_title": "Collision Simulation", "type": "Exercise", "code_execution": false}} {"question": "Add a method pressure() to Particle that measures pressure by accumulating the number and magnitude of collisions against walls. The pressure of the system is the sum of these quantities. Then add a method pressure() to CollisionSystem and write a client that validates the equation pv = nRT.", "answer": "The pressure measurement should use impulse delivered to the container walls, not particle volume.\n\nFor a vertical-wall collision, add impulse `2m|vx|`; for a horizontal-wall collision, add `2m|vy|`. Over elapsed time `t`, the 2D pressure analogue is force per boundary length:\n\n`P = totalWallImpulse / (perimeter * t)`.\n\nFor the ideal-gas comparison in this 2D simulation, use the container area as `V` (the unit square has `V = 1`), and compute temperature from mean kinetic energy:\n\n`T = average(m(vx^2 + vy^2)) / (2 kB)`.\n\nThen compare the wall-collision measurement with\n\n`P V = N kB T`,\n\nor equivalently `P V = n R T` with `n = N / NA` and `R = NA kB`. The previous answer incorrectly used each particle's disk/sphere volume as the gas volume and squared the velocity magnitude again in the temperature calculation.", "support_files": [], "metadata": {"number": "6.11", "chapter": 6, "chapter_title": "Context", "section": 6.1, "section_title": "Collision Simulation", "type": "Exercise", "code_execution": false}} {"question": "Instrument the priority queue and test Pressure at various temperatures to identify the computational bottleneck. If warranted, try switching to a different priority-queue implementation for better performance at high temperatures.", "answer": "// Exercise13_PriorityQueuePerformance.java\npackage chapter6.eventdrivensimulation;\n\nimport chapter2.section4.IndexMinPriorityQueue;\nimport chapter2.section4.PriorityQueueResize;\nimport edu.princeton.cs.algs4.StdDraw;\nimport edu.princeton.cs.algs4.StdOut;\nimport edu.princeton.cs.algs4.StdRandom;\nimport edu.princeton.cs.algs4.Stopwatch;\n\n/**\n * Created by Rene Argento on 12/07/18.\n */\npublic class Exercise13_PriorityQueuePerformance {\n\n private final double BOLTZMANN_CONSTANT = 1.3806488e-23;\n\n public class ParticleWithPressureAndId extends Particle {\n\n private static final int DIMENSION = 2;\n\n private int id;\n private double pressure;\n\n ParticleWithPressureAndId(int id, double positionX, double positionY, double velocityX, double velocityY,\n double radius, double mass) {\n super(positionX, positionY, velocityX, velocityY, radius, mass);\n this.id = id;\n }\n\n public double pressure() {\n return pressure;\n }\n\n private void addWallCollisionToPressure(boolean isHorizontal) {\n if (isHorizontal) {\n pressure += Math.abs(2 * mass * velocityY);\n } else {\n pressure += Math.abs(2 * mass * velocityX);\n }\n }\n\n // V = 4/3 (pi r^3)\n // V = volume\n // r = radius\n public double volume() {\n double volumeInCm3 = 4.0/3.0 * Math.PI * Math.pow(radius, 3);\n // Volume in dm^3\n return volumeInCm3 / 1000;\n }\n\n public double temperature() {\n double velocityMagnitude = Math.pow(velocityX, 2) + Math.pow(velocityY, 2);\n return mass * Math.pow(velocityMagnitude, 2) / (DIMENSION * BOLTZMANN_CONSTANT);\n }\n\n public void setVelocityX(double velocityX) {\n this.velocityX = velocityX;\n }\n\n public void setVelocityY(double velocityY) {\n this.velocityY = velocityY;\n }\n }\n\n public class CollisionSystemWithPressure {\n\n private class Event implements Comparable {\n\n private final double time;\n private final ParticleWithPressureAndId particleA;\n private final ParticleWithPressureAndId particleB;\n private final int collisionsCountA;\n private final int collisionsCountB;\n\n public Event(double time, ParticleWithPressureAndId particleA, ParticleWithPressureAndId particleB) {\n this.time = time;\n this.particleA = particleA;\n this.particleB = particleB;\n\n if (particleA != null) {\n collisionsCountA = particleA.count();\n } else {\n collisionsCountA = -1;\n }\n\n if (particleB != null) {\n collisionsCountB = particleB.count();\n } else {\n collisionsCountB = -1;\n }\n }\n\n public int compareTo(Event otherEvent) {\n if (this.time < otherEvent.time) {\n return -1;\n } else if (this.time > otherEvent.time) {\n return +1;\n } else {\n return 0;\n }\n }\n\n public boolean isValid() {\n if (particleA != null && particleA.count() != collisionsCountA) {\n return false;\n }\n\n if (particleB != null && particleB.count() != collisionsCountB) {\n return false;\n }\n\n return true;\n }\n }\n\n private PriorityQueueResize priorityQueue;\n private IndexMinPriorityQueue indexMinPriorityQueue;\n private double time;\n\n private ParticleWithPressureAndId[] particles;\n private final int DRAW_EVENT_ID;\n\n private int numberOfParticles;\n private boolean useIndexPriorityQueue;\n\n private final double IDEAL_GAS_CONSTANT = 0.082057;\n private final double AVOGADROS_NUMBER = 6.022e23;\n\n private double totalTimeSpentOnInsert = 0;\n private double totalTimeSpentOnDeleteMin = 0;\n private double totalTimeSpentOnIsEmpty = 0;\n\n // Index min priority queue specific metrics\n private double totalTimeSpentOnContains = 0;\n private double totalTimeSpentOnMin = 0;\n private double totalTimeSpentOnDelete = 0;\n\n public CollisionSystemWithPressure(ParticleWithPressureAndId[] particles, boolean useIndexPriorityQueue) {\n StdDraw.enableDoubleBuffering();\n this.particles = particles;\n numberOfParticles = particles.length;\n\n DRAW_EVENT_ID = particles.length;\n this.useIndexPriorityQueue = useIndexPriorityQueue;\n }\n\n private void predictCollisions(ParticleWithPressureAndId particle, double limit) {\n if (particle == null) {\n return;\n }\n\n int particleId = particle.id;\n double currentSmallestEventTime = Double.POSITIVE_INFINITY;\n\n if (useIndexPriorityQueue) {\n Stopwatch timer = new Stopwatch();\n boolean containsParticleId = indexMinPriorityQueue.contains(particleId);\n totalTimeSpentOnContains += timer.elapsedTime();\n\n if (containsParticleId) {\n timer = new Stopwatch();\n indexMinPriorityQueue.delete(particleId);\n totalTimeSpentOnDelete += timer.elapsedTime();\n }\n }\n\n for (int i = 0; i < particles.length; i++) {\n double deltaTime = particle.timeToHit(particles[i]);\n double eventTime = time + deltaTime;\n\n if (eventTime <= limit\n && (!useIndexPriorityQueue || eventTime <= currentSmallestEventTime)) {\n if (!useIndexPriorityQueue) {\n Stopwatch timer = new Stopwatch();\n priorityQueue.insert(new Event(eventTime, particle, particles[i]));\n totalTimeSpentOnInsert += timer.elapsedTime();\n } else {\n Stopwatch timer = new Stopwatch();\n boolean containsParticleId = indexMinPriorityQueue.contains(particleId);\n totalTimeSpentOnContains += timer.elapsedTime();\n\n if (containsParticleId) {\n timer = new Stopwatch();\n indexMinPriorityQueue.delete(particleId);\n totalTimeSpentOnDelete += timer.elapsedTime();\n }\n\n timer = new Stopwatch();\n indexMinPriorityQueue.insert(particleId, new Event(eventTime, particle, particles[i]));\n totalTimeSpentOnInsert += timer.elapsedTime();\n\n currentSmallestEventTime = eventTime;\n }\n }\n }\n\n double deltaTimeVerticalWall = particle.timeToHitVerticalWall();\n double verticalWallEventTime = time + deltaTimeVerticalWall;\n\n if (verticalWallEventTime <= limit\n && (!useIndexPriorityQueue || verticalWallEventTime <= currentSmallestEventTime)) {\n if (!useIndexPriorityQueue) {\n Stopwatch timer = new Stopwatch();\n priorityQueue.insert(new Event(verticalWallEventTime, particle, null));\n totalTimeSpentOnInsert += timer.elapsedTime();\n } else {\n Stopwatch timer = new Stopwatch();\n boolean containsParticleId = indexMinPriorityQueue.contains(particleId);\n totalTimeSpentOnContains += timer.elapsedTime();\n\n if (containsParticleId) {\n timer = new Stopwatch();\n indexMinPriorityQueue.delete(particleId);\n totalTimeSpentOnDelete += timer.elapsedTime();\n }\n\n timer = new Stopwatch();\n indexMinPriorityQueue.insert(particleId, new Event(verticalWallEventTime, particle, null));\n totalTimeSpentOnInsert += timer.elapsedTime();\n\n currentSmallestEventTime = verticalWallEventTime;\n }\n }\n\n double deltaTimeHorizontalWall = particle.timeToHitHorizontalWall();\n double horizontalWallEventTime = time + deltaTimeHorizontalWall;\n\n if (horizontalWallEventTime <= limit\n && (!useIndexPriorityQueue || horizontalWallEventTime <= currentSmallestEventTime)) {\n if (!useIndexPriorityQueue) {\n Stopwatch timer = new Stopwatch();\n priorityQueue.insert(new Event(horizontalWallEventTime, null, particle));\n totalTimeSpentOnInsert += timer.elapsedTime();\n } else {\n Stopwatch timer = new Stopwatch();\n boolean containsParticleId = indexMinPriorityQueue.contains(particleId);\n totalTimeSpentOnContains += timer.elapsedTime();\n\n if (containsParticleId) {\n timer = new Stopwatch();\n indexMinPriorityQueue.delete(particleId);\n totalTimeSpentOnDelete += timer.elapsedTime();\n }\n\n timer = new Stopwatch();\n indexMinPriorityQueue.insert(particleId, new Event(horizontalWallEventTime, null, particle));\n totalTimeSpentOnInsert += timer.elapsedTime();\n }\n }\n }\n\n public void redraw(double limit, double hertz) {\n StdDraw.clear();\n\n for (int i = 0; i < particles.length; i++) {\n particles[i].draw();\n }\n\n StdDraw.pause(20);\n StdDraw.show();\n\n if (time < limit) {\n if (!useIndexPriorityQueue) {\n Stopwatch timer = new Stopwatch();\n priorityQueue.insert(new Event(time + 1.0 / hertz, null, null));\n totalTimeSpentOnInsert += timer.elapsedTime();\n } else {\n Stopwatch timer = new Stopwatch();\n indexMinPriorityQueue.insert(DRAW_EVENT_ID, new Event(time + 1.0 / hertz, null, null));\n totalTimeSpentOnInsert += timer.elapsedTime();\n }\n }\n }\n\n public void simulate(double limit, double hertz) {\n if (!useIndexPriorityQueue) {\n priorityQueue = new PriorityQueueResize<>(PriorityQueueResize.Orientation.MIN);\n\n Stopwatch timer = new Stopwatch();\n priorityQueue.insert(new Event(0, null, null));\n totalTimeSpentOnInsert += timer.elapsedTime();\n } else {\n // Add 1 extra space for the draw event\n indexMinPriorityQueue = new IndexMinPriorityQueue<>(particles.length + 1);\n\n Stopwatch timer = new Stopwatch();\n indexMinPriorityQueue.insert(DRAW_EVENT_ID, new Event(0, null, null));\n totalTimeSpentOnInsert += timer.elapsedTime();\n }\n\n for (int i = 0; i < particles.length; i++) {\n predictCollisions(particles[i], limit);\n }\n\n StdOut.println(\"Testing with temperature: \" + temperature());\n\n int nextCheckpoint = 1000;\n\n while (!isPriorityQueueEmpty()) {\n Event event;\n\n if (!useIndexPriorityQueue) {\n Stopwatch timer = new Stopwatch();\n event = priorityQueue.deleteTop();\n totalTimeSpentOnDeleteMin += timer.elapsedTime();\n } else {\n Stopwatch timer = new Stopwatch();\n event = indexMinPriorityQueue.minKey();\n totalTimeSpentOnMin += timer.elapsedTime();\n\n timer = new Stopwatch();\n indexMinPriorityQueue.deleteMin();\n totalTimeSpentOnDeleteMin += timer.elapsedTime();\n }\n\n // ValidateEquation method is only used to simulate a Pressure test, but its results are not used\n if (event.time >= nextCheckpoint) {\n validateEquation(time);\n nextCheckpoint += 1000;\n }\n\n if (!event.isValid()) {\n continue;\n }\n\n // Update particle positions\n for (int i = 0; i < particles.length; i++) {\n particles[i].move(event.time - time);\n }\n // Update time\n time = event.time;\n\n ParticleWithPressureAndId particleA = event.particleA;\n ParticleWithPressureAndId particleB = event.particleB;\n\n if (particleA != null && particleB != null) {\n particleA.bounceOff(particleB);\n } else if (particleA != null && particleB == null) {\n particleA.bounceOffVerticalWall();\n particleA.addWallCollisionToPressure(false);\n } else if (particleA == null && particleB != null) {\n particleB.bounceOffHorizontalWall();\n particleB.addWallCollisionToPressure(true);\n } else if (particleA == null && particleB == null) {\n redraw(limit, hertz);\n }\n\n predictCollisions(particleA, limit);\n predictCollisions(particleB, limit);\n }\n\n identifyBottleneck();\n }\n\n private boolean isPriorityQueueEmpty() {\n boolean isEmpty;\n\n if (!useIndexPriorityQueue) {\n Stopwatch timer = new Stopwatch();\n isEmpty = priorityQueue.isEmpty();\n totalTimeSpentOnIsEmpty += timer.elapsedTime();\n } else {\n Stopwatch timer = new Stopwatch();\n isEmpty = indexMinPriorityQueue.isEmpty();\n totalTimeSpentOnIsEmpty += timer.elapsedTime();\n }\n\n return isEmpty;\n }\n\n private void validateEquation(double time) {\n double pressureMeasuredWithEquation = pressure();\n double pressureMeasuredWithWallCollisions = pressureWithWallCollisions(time);\n boolean unusedTest = pressureMeasuredWithEquation == pressureMeasuredWithWallCollisions;\n }\n\n // Ideal gas formula: P V = n R T\n // P = pressure\n // V = volume\n // n = number of moles\n // R = ideal gas constant\n // T = temperature\n //\n // P V = n R T\n // P = (n R T) / V\n public double pressure() {\n return (numberOfMoles() * IDEAL_GAS_CONSTANT * temperature()) / volume();\n }\n\n public double pressureWithWallCollisions(double time) {\n double systemPressure = 0;\n\n for (ParticleWithPressureAndId particle : particles) {\n systemPressure += particle.pressure();\n }\n\n return systemPressure / time;\n }\n\n public double volume() {\n double systemVolume = 0;\n\n for (ParticleWithPressureAndId particle : particles) {\n systemVolume += particle.volume();\n }\n\n return systemVolume;\n }\n\n // n = m / mw\n // n = number of moles\n // m = total mass\n // mw = molecular weight\n //\n // mw = pm * AC\n // pm = mass of one particle\n // AC = Avogadro's number\n public double numberOfMoles() {\n // All particle masses are the same\n double particleMass = particles[0].mass;\n double totalMass = particleMass * particles.length;\n\n double molecularWeight = particleMass * AVOGADROS_NUMBER;\n return totalMass / molecularWeight;\n }\n\n public double temperature() {\n double totalTemperature = 0;\n\n for (ParticleWithPressureAndId particle : particles) {\n totalTemperature += particle.temperature();\n }\n\n return totalTemperature / numberOfParticles;\n }\n\n // V = SQRT(2 kb T / M)\n // SQRT(V / 2) = (vx + vy) / 2\n private void setTemperature(double temperature) {\n for (ParticleWithPressureAndId particle : particles) {\n double newVelocityMagnitude =\n Math.sqrt(2 * BOLTZMANN_CONSTANT * temperature / particle.getMass());\n double velocityComponent = Math.sqrt(newVelocityMagnitude / 2);\n particle.setVelocityX(velocityComponent);\n particle.setVelocityY(velocityComponent);\n }\n }\n\n private void identifyBottleneck() {\n double highestTimeSpent = 0;\n String computationalBottleneck = \"\";\n\n StdOut.printf(\"Total time spent on insert operations: %.5f\\n\", totalTimeSpentOnInsert);\n if (totalTimeSpentOnInsert > highestTimeSpent) {\n highestTimeSpent = totalTimeSpentOnInsert;\n computationalBottleneck = \"insert\";\n }\n\n StdOut.printf(\"Total time spent on deleteMin operations: %.5f\\n\", totalTimeSpentOnDeleteMin);\n if (totalTimeSpentOnDeleteMin > highestTimeSpent) {\n highestTimeSpent = totalTimeSpentOnDeleteMin;\n computationalBottleneck = \"deleteMin\";\n }\n\n StdOut.printf(\"Total time spent on isEmpty operations: %.5f\\n\", totalTimeSpentOnIsEmpty);\n if (totalTimeSpentOnIsEmpty > highestTimeSpent) {\n highestTimeSpent = totalTimeSpentOnIsEmpty;\n computationalBottleneck = \"isEmpty\";\n }\n\n if (useIndexPriorityQueue) {\n StdOut.printf(\"Total time spent on contains operations: %.5f\\n\", totalTimeSpentOnContains);\n if (totalTimeSpentOnContains > highestTimeSpent) {\n highestTimeSpent = totalTimeSpentOnContains;\n computationalBottleneck = \"contains\";\n }\n\n StdOut.printf(\"Total time spent on min operations: %.5f\\n\", totalTimeSpentOnMin);\n if (totalTimeSpentOnMin > highestTimeSpent) {\n highestTimeSpent = totalTimeSpentOnMin;\n computationalBottleneck = \"min\";\n }\n\n StdOut.printf(\"Total time spent on delete operations: %.5f\\n\", totalTimeSpentOnDelete);\n if (totalTimeSpentOnDelete > highestTimeSpent) {\n computationalBottleneck = \"delete\";\n }\n }\n\n StdOut.println(\"Computational bottleneck: \" + computationalBottleneck + \" operations\");\n }\n }\n\n private ParticleWithPressureAndId getRandomParticle(int id) {\n double positionX = StdRandom.uniform(0.0, 1.0);\n double positionY = StdRandom.uniform(0.0, 1.0);\n\n double velocityX = StdRandom.uniform(-0.005, 0.005);\n double velocityY = StdRandom.uniform(-0.005, 0.005);\n\n double radius = 0.0025;\n double mass = 0.5;\n\n return new ParticleWithPressureAndId(id, positionX, positionY, velocityX, velocityY, radius, mass);\n }\n\n private void doExperiment(int numberOfParticles, int simulationTime, double hertz) {\n StdOut.println(\"**** Standard priority queue tests ****\");\n StdOut.println();\n\n double baseLineTemperature = doBaselineTest(numberOfParticles, simulationTime, hertz);\n\n double[] testTemperatures = {\n baseLineTemperature * 100,\n baseLineTemperature * 10000,\n baseLineTemperature * 1000000,\n baseLineTemperature * 100000000\n };\n\n for (int t = 0; t < testTemperatures.length; t++) {\n simulate(numberOfParticles, simulationTime, hertz, testTemperatures[t], false);\n }\n\n StdOut.println();\n StdOut.println(\"**** Index priority queue tests ****\");\n\n // Also test the high temperatures with the index priority-queue\n for (int t = 2; t < testTemperatures.length; t++) {\n simulate(numberOfParticles, simulationTime, hertz, testTemperatures[t], true);\n }\n }\n\n private double doBaselineTest(int numberOfParticles, int simulationTime, double hertz) {\n ParticleWithPressureAndId[] particles = new ParticleWithPressureAndId[numberOfParticles];\n\n for (int i = 0; i < numberOfParticles; i++) {\n particles[i] = getRandomParticle(i);\n }\n\n CollisionSystemWithPressure collisionSystem = new CollisionSystemWithPressure(particles, false);\n collisionSystem.simulate(simulationTime, hertz);\n\n return collisionSystem.temperature();\n }\n\n private void simulate(int numberOfParticles, int simulationTime, double hertz, double testTemperature,\n boolean useIndexPriorityQueue) {\n StdDraw.clear();\n StdOut.println();\n\n ParticleWithPressureAndId[] particles = new ParticleWithPressureAndId[numberOfParticles];\n for (int i = 0; i < numberOfParticles; i++) {\n particles[i] = getRandomParticle(i);\n }\n\n CollisionSystemWithPressure collisionSystemWithPressure =\n new CollisionSystemWithPressure(particles, useIndexPriorityQueue);\n collisionSystemWithPressure.setTemperature(testTemperature);\n\n collisionSystemWithPressure.simulate(simulationTime, hertz);\n }\n\n public static void main(String[] args) {\n int numberOfParticles = 30;\n int simulationTime = 10000;\n double hertz = 0.5;\n\n new Exercise13_PriorityQueuePerformance().doExperiment(numberOfParticles, simulationTime, hertz);\n }\n}\n\nAdditional notes/results:\n6.13\n\nTests done with a random baseline temperature T, 100 * T, 10000 * T, 1000000 * T and 100000000 * T.\nThe standard priority queue was used to test all the temperatures.\nThe index priority queue was also used to test the highest temperatures: 1000000 * T and 100000000 * T.\n\nResults:\n\n**** Standard priority queue tests ****\n\nTesting with temperature: 5.817661439511093E12\nTotal time spent on insert operations: 0.02200\nTotal time spent on deleteMin operations: 0.01300\nTotal time spent on isEmpty operations: 0.00200\nComputational bottleneck: insert operations\n\nTesting with temperature: 8.270951314920601E14\nTotal time spent on insert operations: 0.00700\nTotal time spent on deleteMin operations: 0.01400\nTotal time spent on isEmpty operations: 0.00000\nComputational bottleneck: delete min operations\n\nTesting with temperature: 8.2709513149206064E16\nTotal time spent on insert operations: 0.00800\nTotal time spent on deleteMin operations: 0.01500\nTotal time spent on isEmpty operations: 0.00300\nComputational bottleneck: delete min operations\n\nTesting with temperature: 8.2709513149206047E18\nTotal time spent on insert operations: 0.01900\nTotal time spent on deleteMin operations: 0.06700\nTotal time spent on isEmpty operations: 0.00300\nComputational bottleneck: delete min operations\n\nTesting with temperature: 8.270951314920604E20\nTotal time spent on insert operations: 0.04700\nTotal time spent on deleteMin operations: 0.12100\nTotal time spent on isEmpty operations: 0.02500\nComputational bottleneck: delete min operations\n\n**** Index priority queue tests ****\n\nTesting with temperature: 6.3274920297362524E18\nTotal time spent on insert operations: 0.00900\nTotal time spent on deleteMin operations: 0.00500\nTotal time spent on isEmpty operations: 0.00000\nTotal time spent on contains operations: 0.00300\nTotal time spent on min operations: 0.00100\nTotal time spent on delete operations: 0.00400\nComputational bottleneck: insert operations\n\nTesting with temperature: 6.327492029736252E20\nTotal time spent on insert operations: 0.00600\nTotal time spent on deleteMin operations: 0.00700\nTotal time spent on isEmpty operations: 0.00000\nTotal time spent on contains operations: 0.00300\nTotal time spent on min operations: 0.00200\nTotal time spent on delete operations: 0.00500\nComputational bottleneck: deleteMin operations\n\nFor the standard priority queue on a lower temperature the computational bottleneck were the insert operations. However, for all higher temperatures, the computational bottleneck were the deleteMin operations.\nFor the index priority queue the computational bottleneck were also both the insert and deleteMin operations. In the first test the computational bottleneck were the insert operations. In the second test, with a higher temperature, the computational bottleneck were the deleteMin operations.", "support_files": [], "metadata": {"number": "6.13", "chapter": 6, "chapter_title": "Context", "section": 6.1, "section_title": "Collision Simulation", "type": "Exercise", "code_execution": false}} {"question": "Suppose that, in a three-level tree, we can afford to keep a links in internal memory, between b and 2b links in pages representing internal nodes, and between c and 2c items in pages representing external nodes. What is the maximum number of items that we can hold in such a tree, as a function of a, b, and c?", "answer": "6.14\n\nThe maximum number of items that we can hold in such a tree is achieved when there are \"a\" links in internal memory (the links between the first and second level of the tree), 2b links in pages representing internal nodes (the highest branching possible) and 2c items in pages representing external nodes (the highest number of items per external node).\n\nMaximum number of items = a * 2b * 2c\n", "support_files": [], "metadata": {"number": "6.14", "chapter": 6, "chapter_title": "Context", "section": 6.2, "section_title": "B-Trees", "type": "Exercise", "code_execution": false}} {"question": "Estimate the average number of probes per search in a B-tree for S random searches, in a typical cache system, where the T most-recently-accessed pages are kept in memory (and therefore add 0 to the probe count). Assume that S is much larger than T.", "answer": "6.18\n\nLet h be the number of pages examined by a search when nothing useful is cached; for a B-tree of order M with N keys, h is about log_M N to log_{M/2} N.\n\nWith random searches and S much larger than T, there is little locality among the leaf pages. The pages that reliably stay in the cache are the pages near the root, because every search touches them. If the cache can hold the top L levels of the tree, where\n\n 1 + M + M^2 + ... + M^(L - 1) <= T,\n\nthen those L page probes usually cost 0, and the average number of disk probes per search is approximately\n\n max(0, h - L)\n\nLower-level pages may occasionally be among the T most recently accessed pages, but for random searches this contribution is small when S is much larger than T and the number of leaf/subtree pages is much larger than T.\n", "support_files": [], "metadata": {"number": "6.18", "chapter": 6, "chapter_title": "Context", "section": 6.2, "section_title": "B-Trees", "type": "Exercise", "code_execution": false}} {"question": "Consider the sibling split (or B*-tree) heuristic for B-trees: When it comes time to split a node because it contains M entries, we combine the node with its sibling. If the sibling has k entries with k < M - 1, we reallocate the items giving the sibling and the full node each about (M+k)/2 entries. Otherwise, we create a new node and give each of the three nodes about 2M/3 entries. Also, we allow the root to grow to hold about 4M/3 items, splitting it and creating a new root node with two entries when it reaches that bound. State bounds on the number of probes used for a search or an insertion in a B*-tree of order M with N items. Compare your bounds with the corresponding bounds for B-trees (see PROPOSITION B). Develop an insert implementation for B*-trees.", "answer": "6.20 - B* trees\n\nBounds on the number of probes used for a search or an insertion in a B*-tree of order M with N items:\nBetween log(M) N and log(2M/3) N probes.\nThis is because almost all internal nodes of the tree have between 2M / 3 and M - 1 links, since they are formed from a split of a full node with M keys and can only grow in size. \nThe only exception in which an internal node can have less than 2M / 3 links is when a node's child keys are reallocated with the creation of a new child node and its rightmost child does not get allocated enough entries. This happens when there are K keys to be reallocated to C child nodes and K / C < 2M / 3.\n\nAs seen in Proposition B, the bounds on the number of probes used for a search or an insertion in a B-tree of order M with N items is between log(M) N and log(M/2) N probes.\nSince log(2M/3) N < log(M/2) N, B*-trees are more efficient for both search and insert operations. This efficiency comes with a tradeoff that the split() operation, which has a runtime complexity of O(M / 2) in B-trees, changes its runtime complexity to O(M^2).\n\n\nB*-tree insertion outline:\n\n```text\ninsert(key):\n if root is over the 4M/3 root limit:\n split root into two children and create a new root\n insert(root, key)\n\ninsert(page, key):\n if page is external:\n insert key into page in sorted order\n return\n\n child = page.childThatCanContain(key)\n insert(child, key)\n\n if child has M entries:\n sibling = an adjacent sibling of child under the same parent\n if sibling exists and sibling has fewer than M - 1 entries:\n redistribute child + separator key + sibling so each gets about (M + k) / 2 entries\n update the separator key in parent\n else:\n allocate a new page\n redistribute child + separator key + full sibling into three pages,\n each with about 2M / 3 entries\n replace the old separator in parent by two separator keys\n```\n\nThe implementation differs from ordinary B-tree insertion at the overflow point: try redistribution with a sibling first; split two full siblings into three pages only when redistribution is impossible.\n", "support_files": [], "metadata": {"number": "6.20", "chapter": 6, "chapter_title": "Context", "section": 6.2, "section_title": "B-Trees", "type": "Exercise", "code_execution": false}} {"question": "Write a program to compute the average number of external pages for a B-tree of order M built from N random insertions into an initially empty tree. Run your program for reasonable values of M and N.", "answer": "6.21\n\nResults:\n\n Order M | Number of items | AVG Number of External Pages\n 4 100000 42865\n 4 1000000 428592\n 4 10000000 4276006\n 16 100000 9424\n 16 1000000 94288\n 16 10000000 940648\n 64 100000 2277\n 64 1000000 22822\n 64 10000000 227472\n 256 100000 542\n 256 1000000 5650\n 256 10000000 57418\n\nAs expected, the higher the value of the order (M), the lower the number of external pages in the B-tree.\nAlso, when comparing experiments with the same order (M) but with different number of items (N), the higher the number of items, the higher the number of external pages in the B-tree.\n\n\nProgram structure:\n\n```java\nfor (int m : new int[] {4, 16, 64, 256}) {\n for (int n : new int[] {100000, 1000000, 10000000}) {\n long total = 0;\n for (int t = 0; t < trials; t++) {\n BTreeSETWithExternalPageCounter set =\n new BTreeSETWithExternalPageCounter<>(0, m);\n for (int i = 0; i < n; i++) {\n set.add(StdRandom.uniformInt(Integer.MAX_VALUE));\n }\n total += set.externalPages();\n }\n StdOut.printf(\"%8d %12d %12.0f\\n\", m, n, total / (double) trials);\n }\n}\n```\n\n`externalPages()` is maintained by incrementing the counter whenever an external page splits and a new external page is created.\n", "support_files": [], "metadata": {"number": "6.21", "chapter": 6, "chapter_title": "Context", "section": 6.2, "section_title": "B-Trees", "type": "Exercise", "code_execution": false}} {"question": "If your system supports virtual memory, design and conduct experiments to compare the performance of B-trees with that of binary search, for random searches in a huge symbol table.", "answer": "6.22\n\nResults:\n\nNumber of searches | B-tree time | Binary search time\n 1000 0.005 0.001\n 100000 0.082 0.013\n 10000000 6.352 0.910\n\nFor random searches in a huge symbol table (with 10,000,000 entries) binary search has a better performance than B-trees.\n\nReference related to virtual memory in macs:\nhttps://www.howtogeek.com/319151/why-you-shouldnt-turn-off-virtual-memory-on-your-mac/\n", "support_files": [], "metadata": {"number": "6.22", "chapter": 6, "chapter_title": "Context", "section": 6.2, "section_title": "B-Trees", "type": "Exercise", "code_execution": false}} {"question": "For your internal-memory implementation of Page in EXERCISE 6.15, run experiments to determine the value of M that leads to the fastest search times for a B-tree implementation supporting random search operations in a huge symbol table. Restrict your attention to values of M that are multiples of 100.", "answer": "6.23\n\nResults:\n\n Order M | Number of searches | Total time\n 100 1000 0.005\n 100 100000 0.198\n 100 10000000 19.973\n 200 1000 0.002\n 200 100000 0.195\n 200 10000000 18.331\n 400 1000 0.003\n 400 100000 0.188\n 400 10000000 17.533\n 1000 1000 0.002\n 1000 100000 0.176\n 1000 10000000 16.818\n 1500 1000 0.002\n 1500 100000 0.162\n 1500 10000000 15.784\n 2000 1000 0.003\n 2000 100000 0.205\n 2000 10000000 17.821\n\nThe value of M (order) that leads to the fastest search times for a B-tree doing random search operations in a huge symbol table (with 10,000,000 entries) is 1500.\n", "support_files": [], "metadata": {"number": "6.23", "chapter": 6, "chapter_title": "Context", "section": 6.2, "section_title": "B-Trees", "type": "Exercise", "code_execution": false}} {"question": "Run experiments to compare search times for internal B-trees (using the value of M determined in the previous exercise), linear probing hashing, and red-black trees for random search operations in a huge symbol table.", "answer": "6.24\n\nResults:\n\nNumber of searches | B-tree time | Linear probing hashing time | Red-Black tree time\n 1000 0.004 0.001 0.002\n 100000 0.173 0.019 0.114\n 10000000 16.659 1.931 11.297\n\nOn the experiments using B-trees with order 1500, linear probing hashing and red-black trees for random searches in a huge symbol table (with 10,000,000 entries), the best search performance by far was achieved by linear probing hashing, which took 1.931 seconds to search 10 million random keys.\nIt was followed by red-black trees, with 11.297 seconds to search 10 million random keys. B-trees had the worst search performance, taking 16.659 seconds to do the same searches.\nSuch results can be explained by the fact that linear probing hashing perform searches in O(1) while B-trees perform searches in O(log(M/2) N) - O(log(750) N) in this case - and red-black trees perform searches in O(lgN).\n", "support_files": [], "metadata": {"number": "6.24", "chapter": 6, "chapter_title": "Context", "section": 6.2, "section_title": "B-Trees", "type": "Exercise", "code_execution": false}} {"question": "Give, in the style of the figure on page 882, the suffixes, sorted suffixes, index() and lcp() tables for the following strings:\na. abacadaba\nb. mississippi\nc. abcdefghij\nd. aaaaaaaaaa", "answer": "6.25\n\na. abacadaba\n\nsuffixes sorted suffix array\n i index(i) lcp(i)\n0 abacadaba 0 8 0 a\n1 bacadaba 1 6 1 aba\n2 acadaba 2 0 3 abacadaba\n3 cadaba 3 2 1 acadaba\n4 adaba 4 4 1 adaba\n5 daba 5 7 0 ba\n6 aba 6 1 2 bacadaba\n7 ba 7 3 0 cadaba\n8 a 8 5 0 daba\n\nb. mississippi\n\nsuffixes sorted suffix array\n i index(i) lcp(i)\n 0 mississippi 0 10 0 i\n 1 ississippi 1 7 1 ippi\n 2 ssissippi 2 4 1 issippi\n 3 sissippi 3 1 4 ississippi\n 4 issippi 4 0 0 mississippi\n 5 ssippi 5 9 0 pi\n 6 sippi 6 8 1 ppi\n 7 ippi 7 6 0 sippi\n 8 ppi 8 3 2 sissippi\n 9 pi 9 5 1 ssippi\n10 i 10 2 3 ssissippi\n\nc. abcdefghij\n\nsuffixes sorted suffix array\n i index(i) lcp(i)\n0 abcdefghij 0 0 0 abcdefghij\n1 bcdefghij 1 1 0 bcdefghij\n2 cdefghij 2 2 0 cdefghij\n3 defghij 3 3 0 defghij\n4 efghij 4 4 0 efghij\n5 fghij 5 5 0 fghij\n6 ghij 6 6 0 ghij\n7 hij 7 7 0 hij\n8 ij 8 8 0 ij\n9 j 9 9 0 j\n\nd. aaaaaaaaaa\n\nsuffixes sorted suffix array\n i index(i) lcp(i)\n0 aaaaaaaaaa 0 9 0 a\n1 aaaaaaaaa 1 8 1 aa\n2 aaaaaaaa 2 7 2 aaa\n3 aaaaaaa 3 6 3 aaaa\n4 aaaaaa 4 5 4 aaaaa\n5 aaaaa 5 4 5 aaaaaa\n6 aaaa 6 3 6 aaaaaaa\n7 aaa 7 2 7 aaaaaaaa\n8 aa 8 1 8 aaaaaaaaa\n9 a 9 0 9 aaaaaaaaaa\n", "support_files": [], "metadata": {"number": "6.25", "chapter": 6, "chapter_title": "Context", "section": 6.3, "section_title": "Suffix Arrays", "type": "Exercise", "code_execution": false}} {"question": "Identify the problem with the following code fragment to compute all the suffixes for suffix sort:\nsuffix = \"\";\nfor (int i = s.length() - 1; i >= 0; i--)\n{\n suffix = s.charAt(i) + suffix;\n suffixes[i] = suffix;\n}", "answer": "The problem is that Java strings are immutable. Each statement\n\n suffix = s.charAt(i) + suffix;\n\ncreates a new String and copies all characters in the old suffix. The copied suffix lengths are 1, 2, 3, ..., N, so the total time and total character storage are quadratic, not linear.\n\nA suffix-sort implementation should store integer starting positions, use a suffix object/view, or otherwise avoid materializing every suffix string by repeated concatenation.\n", "support_files": [], "metadata": {"number": "6.26", "chapter": 6, "chapter_title": "Context", "section": 6.3, "section_title": "Suffix Arrays", "type": "Exercise", "code_execution": false}} {"question": "Under the assumptions described in SECTION 1.4. give the memory usage of a SuffixArray object with a string of length N.", "answer": "For the textbook `SuffixArray` representation with an inner `Suffix` object, each suffix object stores a reference to the shared text string and an `int` index.\n\nPer `Suffix` object:\n\n`16` object overhead + `8` text reference + `4` int index + `4` padding = `32` bytes.\n\n`SuffixArray` object excluding the input `String` object itself:\n\n`16` object overhead + `8` reference to `Suffix[]` + `24` array overhead + `8N` suffix references + `32N` suffix objects\n\n`= 40N + 48` bytes.\n\nIf the `String` of length `N` is counted as part of the object graph under the Section 1.4 assumptions, add `56 + 2N` bytes for the string, giving\n\n`42N + 104` bytes.\n\nThe previous `40N + 40` total was missing the outer object's reference to the suffix array.", "support_files": [], "metadata": {"number": "6.29", "chapter": 6, "chapter_title": "Context", "section": 6.3, "section_title": "Suffix Arrays", "type": "Exercise", "code_execution": false}} {"question": "Write a SuffixArray client LCS that take two file-names as command-line arguments, reads the two text files, and finds the longest substring that appears in both in linear time. (In 1970, D. Knuth conjectured that this task was impossible.) Hint: Create a suffix array for s#t where s and t are the two text strings and # is a character that does not appear in either.", "answer": "```java\nimport edu.princeton.cs.algs4.In;\nimport edu.princeton.cs.algs4.StdOut;\nimport edu.princeton.cs.algs4.SuffixArray;\n\npublic class LCS {\n private static boolean inFirstText(int index, int firstLength) {\n return index < firstLength;\n }\n\n private static char delimiter(String a, String b) {\n for (char c = 1; c < Character.MAX_VALUE; c++) {\n if (a.indexOf(c) < 0 && b.indexOf(c) < 0) return c;\n }\n throw new IllegalArgumentException(\"no delimiter available\");\n }\n\n public static void main(String[] args) {\n String s = new In(args[0]).readAll();\n String t = new In(args[1]).readAll();\n char sep = delimiter(s, t);\n String text = s + sep + t;\n int n1 = s.length();\n\n SuffixArray sa = new SuffixArray(text);\n String best = \"\";\n\n for (int i = 1; i < sa.length(); i++) {\n int a = sa.index(i);\n int b = sa.index(i - 1);\n if (a == n1 || b == n1) continue;\n if (inFirstText(a, n1) == inFirstText(b, n1)) continue;\n\n int length = sa.lcp(i);\n if (length > best.length()) {\n best = text.substring(a, a + length);\n }\n }\n StdOut.println(best);\n }\n}\n```\n\nThe scan after suffix-array construction is linear: the longest common substring must be the LCP of two adjacent suffixes that originate in different input files. To satisfy the exercise's linear-time requirement end to end, use a linear-time suffix-array construction for `s + sep + t`; the adjacent-LCP scan is already linear.", "support_files": [], "metadata": {"number": "6.30", "chapter": 6, "chapter_title": "Context", "section": 6.3, "section_title": "Suffix Arrays", "type": "Exercise", "code_execution": false}} {"question": "If capacities are positive integers less than M, what is the maximum possible flow value for any st-network with V vertices and E edges? Give two answers, depending on whether or not parallel edges are allowed.", "answer": "Let C = M - 1 be the largest possible capacity.\n\nIf parallel edges are allowed, the maximum flow can be E * C: put all E edges directly from s to t, each with capacity C.\n\nIf parallel edges are not allowed, the source can have at most V - 1 outgoing edges, and using d independent capacity-C paths from s to t requires at least 2d - 1 edges if one path is the direct edge s->t and the other d - 1 paths go through distinct intermediate vertices. Therefore the maximum possible value is\n\n C * min(V - 1, floor((E + 1) / 2))\n\nThis bound is achievable by using the direct edge s->t plus as many two-edge paths s->v->t through distinct intermediate vertices as the vertex and edge budgets allow.\n", "support_files": [], "metadata": {"number": "6.36", "chapter": 6, "chapter_title": "Context", "section": 6.4, "section_title": "Maxflow", "type": "Exercise", "code_execution": false}} {"question": "Give an algorithm to solve the maxflow problem for the case that the network forms a tree if the sink is removed.", "answer": "Root the tree obtained by removing t at the source s. For each vertex v, compute bottom-up the maximum amount of flow that can be sent from v to t through the subtree rooted at v.\n\nLet value(v) be:\n\n sum of capacities of edges v->t\n + sum over children w of min(capacity(v, w), value(w))\n\nCompute value(v) by a postorder traversal of the tree. The answer is value(s).\n\nThis is linear time because each tree edge and each edge into the sink is inspected once. The formula is necessary because different branches of the tree can share upstream capacity; simply summing one source-to-sink path per source child is not sufficient for a general tree.\n", "support_files": [], "metadata": {"number": "6.37", "chapter": 6, "chapter_title": "Context", "section": 6.4, "section_title": "Maxflow", "type": "Exercise", "code_execution": false}} {"question": "If true provide a short proof, if false give a counterexample:\na. In any max flow, there is no directed cycle on which every edge carries positive flow\nb. There exists a max flow for which there is no directed cycle on which every edge carries positive flow\nc. If all edge capacities are distinct, the max flow is unique\nd. If all edge capacities are increased by an additive constant, the min cut remains unchanged\ne. If all edge capacities are multiplied by a positive integer, the min cut remains unchanged", "answer": "6.38 - True of false\n\na. In any max flow, there is no directed cycle on which every edge carries positive flow.\nFalse.\nCounterexample:\n\n s\n | ^\n2/2| |1/1\n v |\n 1\n |\n |1/1\n v\n t\n\nb. There exists a max flow for which there is no directed cycle on which every edge carries positive flow.\nTrue.\nProof: Let f be a maximum flow and let C be a cycle on which every edge carries positive flow.\nLet g = min(e E C) f(e). In other words, g is equal to the value of the minimum edge flow among the edges in cycle C.\nReducing the flow of each edge in C by g maintains the value of the max flow and sets the flow f(e) of at least one of the edges e E C to zero.\n\nc. If all edge capacities are distinct, the max flow is unique.\nFalse.\nCounterexample:\n\n s\n | 1/1\n |\n v\n 1\n |\n / \\\n2/0 / |\n v |\n 2 | 3/1\n \\ |\n4/0 \\ |\n v v\n t\n\n s\n | 1/1\n |\n v\n 1\n |\n / \\\n2/1 / |\n v |\n 2 | 3/0\n \\ |\n4/1 \\ |\n v v\n t\n\nd. If all edge capacities are increased by an additive constant, the min cut remains unchanged.\nFalse.\nCounterexample:\n\noriginal network:\n\n s\n | 4/3\n v\n 1\n 1/1/ |1/1 \\ 1/1 <- min cut\n v v v\n \\ | /\n1/1 \\ |1/1 / 1/1\n v v v\n t\n\nAfter adding a constant value of 1 to all edge capacities:\n\n s\n | 5/3 <- min cut\n v\n 1\n 2/1/ |2/1 \\ 2/1\n v v v\n \\ | /\n2/1 \\ |2/1 / 2/1\n v v v\n t\n\ne. If all edge capacities are multiplied by a positive integer, the min cut remains unchanged.\nTrue.\nProof: Let g be the positive integer for which every edge capacity is multiplied.\nWhen all edge capacities are multiplied by g the value of every cut also gets multiplied by g.\nThus, the relative order of the cuts does not change and the min cut before the multiplication will remain the min cut after it.\n\nReferences:\nhttp://algo2.iti.kit.edu/sanders/courses/algdat03/sol3.pdf\nhttps://stackoverflow.com/questions/40277603/is-minimum-cut-same-for-the-graph-after-increasing-edge-capacity-by-1-for-all-ed\n", "support_files": [], "metadata": {"number": "6.38", "chapter": 6, "chapter_title": "Context", "section": 6.4, "section_title": "Maxflow", "type": "Exercise", "code_execution": false}} {"question": "Complete the proof of PROPOSITION G: Show that each time an edge is a critical edge, the length of the augmenting path through it must increase by 2.", "answer": "Let `d_f(x)` be the BFS distance from `s` to vertex `x` in the residual network just before an augmentation, and suppose residual edge `u->v` is critical on a shortest augmenting path. Then\n\n`d_f(v) = d_f(u) + 1`.\n\nFor `u->v` to become critical again later, the residual capacity of `u->v` must first be restored. The only way to restore it is to use the reverse edge `v->u` on some later augmenting path. At that later time, if the distance labels are `d'`, that path has\n\n`d'(u) = d'(v) + 1`.\n\nEdmonds-Karp BFS distances from `s` never decrease over the sequence of augmentations, so `d'(v) >= d_f(v)`. Therefore\n\n`d'(u) = d'(v) + 1 >= d_f(v) + 1 = d_f(u) + 2`.\n\nThus, before edge `u->v` can be critical again, the shortest augmenting path distance to `u` has increased by at least 2, so the length of any augmenting path through that edge has increased by at least 2.", "support_files": [], "metadata": {"number": "6.39", "chapter": 6, "chapter_title": "Context", "section": 6.4, "section_title": "Maxflow", "type": "Exercise", "code_execution": false}} {"question": "Prove that the shortest-paths problem reduces to linear programming.", "answer": "6.50\n\nReduction from shortest paths problem to linear programming:\n\nMethod 1:\nWe consider a system of inequalities and equations that involve the following variables:\nl(u,v) -> variable corresponding to the length of the directed edge u -> v.\nx(u,v) -> indicator variable for whether edge u -> v is in the shortest path. It has value 1 when the edge is, and 0 when the edge is not.\n\nGiven a directed graph G with a source vertex s and a target vertex t.\n\nLinear programming formulation:\n\n Minimize E l(u,v) * x(u,v)\n u->v\n\nSubject to the constraints\n\n E x(s,v) - E x(v,s) = 1\n v v\n\n E x(t,v) - E x(v,t) = -1\n v v\n\nfor every vertex u other than s and t:\n E x(u,v) - E x(v,u) = 0\n v v\n\n x(u,v) >= 0 for every edge u -> v\n\nThe constraints state that the path should start at s, end at t, and either pass through or avoid every other vertex v.\nThis selects the set of edges with minimal length, subject to the constraint that this set forms a path from s to t - represented by the constraints that ensure that for all vertices except s and t the number of incoming and outcoming edges that are part of the path must be the same.\n\nThe solution is easily converted to a solution of the shortest paths problem: the edges u -> v for which x(u,v) is equal to 1 are part of the shortest path and the sum of all their lengths is the length of the shortest path from s to t.\n\nMethod 2:\nWe consider a system of inequalities and equations that involve the following variables:\nd(v) -> variable corresponding to the shortest distance from s to vertex v.\nl(u,v) -> variable corresponding to the length of the directed edge u -> v.\n\nGiven a directed graph G with a set of vertices V, a set of edges E and with a source vertex s and a target vertex t.\n\nLinear programming formulation:\n\n Maximize d(t)\n\nSubject to the constraints\n\n d(s) = 0\n d(v) - d(u) <= l(u,v) for every edge u -> v\n\nThe constraints state that in a shortest path from s to t, d(v) is at most the shortest path distance from s to v. And the value of d(t) will be the shortest path distance from s to t.\nTo find the edges in the shortest path from s to t, the following method can be used:\nPre-process the edges to map each vertex with its incoming edges.\nStarting with vertex t, check which incoming neighbor vertex v has d(v) equal to d(t) - l(v,t).\nAdd the edge v -> t to the shortest path. Replace t with v and do the same check for its incoming neighbors, iterating this process until vertex s is reached.\n\nTo compute the shortest paths from s to every other vertex, the following linear programming formulation can be used:\n\n Maximize E d(v)\n v\n\nSubject to the constraints\n\n d(s) = 0\n d(v) - d(u) <= l(u,v) for every edge u -> v\n\nThe resulting values of d(v) will be the shortest path distances from s to every vertex v.\nTo find the edges in the shortest path from s to any vertex v, the same process mentioned above can be used, replacing vertex t with vertex v.\n\nTo compute the shortest paths from all vertices to every other vertex (all-pairs shortest paths), the following linear programming formulation can be used:\n\nd(u,v) -> variable corresponding to the shortest distance from vertex u to vertex v.\n\n Maximize E d(u,v)\n v\n\nSubject to the constraints\n\n d(v,v) = 0 for every vertex v\n d(u,w) - d(u,v) <= l(v,w) for every vertex u in V and every edge v -> w in E\n\nThe resulting values of d(u,v) will be the shortest path distances from every vertex u to every vertex v.\nTo find the edges in the shortest paths from every vertex u to every vertex v, the same process mentioned above can be used, replacing vertex t with vertex v and vertex s with vertex u.\n\nReferences:\nhttps://en.wikipedia.org/wiki/Shortest_path_problem#Linear_programming_formulation\nhttps://courses.engr.illinois.edu/cs498dl1/sp2015/notes/26-lp.pdf\nhttp://www.cs.yale.edu/homes/aspnes/pinewiki/attachments/LinearProgramming/lp.pdf\n", "support_files": [], "metadata": {"number": "6.50", "chapter": 6, "chapter_title": "Context", "section": 6.5, "section_title": "Reductions and Intractability", "type": "Exercise", "code_execution": false}} {"question": "Could there be an algorithm that solves an NP-complete problem in an average time of NlogN, if P != NP? Explain your answer.", "answer": "Yes, this would not contradict P != NP as stated, because the question asks about average time rather than worst-case time. P is defined using worst-case polynomial time. An algorithm could have average running time O(N log N) under some input distribution while still taking super-polynomial time on worst-case instances.\n\nIf the guarantee were worst-case O(N log N) for an NP-complete problem, then P would equal NP. But an average-time statement alone does not imply that.\n", "support_files": [], "metadata": {"number": "6.51", "chapter": 6, "chapter_title": "Context", "section": 6.5, "section_title": "Reductions and Intractability", "type": "Exercise", "code_execution": false}} {"question": "Suppose that someone discovers an algorithm that is guaranteed to solve the boolean satisfiability problem in time proportional to 1.1^N. Does this imply that we can solve other NP-complete problems in time proportional to 1.1^N?", "answer": "Not necessarily with the same 1.1^N bound. Since SAT is NP-complete, every NP problem has a polynomial-time reduction to SAT. If an instance of another NP-complete problem of size N reduces to a SAT instance of size p(N), then the resulting running time would be roughly\n\n poly(N) + 1.1^p(N)\n\nThat is exponential if p is polynomial, but it is not necessarily proportional to 1.1^N. The base/exponent bound is not preserved by arbitrary polynomial reductions.\n", "support_files": [], "metadata": {"number": "6.52", "chapter": 6, "chapter_title": "Context", "section": 6.5, "section_title": "Reductions and Intractability", "type": "Exercise", "code_execution": false}} {"question": "What would be the significance of a program that could solve the integer linear programming problem in time proportional to 1.1^N?", "answer": "Integer linear programming is NP-complete, so a 1.1^N algorithm for ILP would be a major exponential-time improvement for that NP-complete problem and, via reductions, would give exponential-time algorithms for other NP problems.\n\nIt would not imply P = NP, because 1.1^N is still exponential. It also would not automatically imply that every NP problem can be solved in time 1.1^N in its own input size, because polynomial reductions can increase the instance size to p(N).\n", "support_files": [], "metadata": {"number": "6.53", "chapter": 6, "chapter_title": "Context", "section": 6.5, "section_title": "Reductions and Intractability", "type": "Exercise", "code_execution": false}} {"question": "Give a poly-time reduction from vertex cover to 0-1 integer linear inequality satisfiability.", "answer": "Given a vertex-cover instance (G = (V, E), k), create one 0-1 variable x_v for each vertex v. The intended meaning is x_v = 1 if v is included in the cover.\n\nAdd the constraints\n\n x_u + x_v >= 1 for every edge (u, v) in E\n sum_{v in V} x_v <= k\n x_v in {0, 1} for every vertex v\n\nThe edge constraints require every edge to have at least one selected endpoint, and the sum constraint requires the selected set to have size at most k. Therefore the system is satisfiable if and only if G has a vertex cover of size at most k. The construction has one variable per vertex and one inequality per edge plus the size bound, so it is polynomial time.\n", "support_files": [], "metadata": {"number": "6.54", "chapter": 6, "chapter_title": "Context", "section": 6.5, "section_title": "Reductions and Intractability", "type": "Exercise", "code_execution": false}} {"question": "Prove that the problem of finding a Hamiltonian path in a directed graph is NP-complete, using the NP-completeness of the Hamiltonian-path problem for undirected graphs.", "answer": "6.55\n\nProve that the problem of finding a Hamiltonian path in a directed graph is NP-complete, using the NP-completeness of the Hamiltonian path problem for undirected graphs.\n\nLet's call the Hamiltonian path problem in undirected graphs HPg and the Hamiltonian path problem in directed graphs HPdg.\n\nReduction from HPg to HPdg:\nReplace every edge v - w in the undirected graph in HPg to two directed edges in the directed graph in HPdg:\nA v -> w directed edge and a w -> v directed edge.\nSolve HPdg.\nThe directed edges selected in the solution to HPdg can be mapped to the edges in the solution to HPg:\nIf either v -> w or w -> v are in HPdg solution, v - w is in HPg solution.\n\nA problem is NP-complete if it is in NP and all problems in NP poly-time reduce to it.\nHPdg is in NP because if given a Hamiltonian path as a solution, it is possible to check if all vertices are visited in polynomial time.\nSince HPg is NP-complete, all problems in NP poly-time reduce to it.\nAs seen above, there is a poly-time reduction from HPg to HPdg. By transitive relation this shows that all problems in NP poly-time reduce to HPdg, and it is, therefore, NP-complete.\n\n All problems in NP\n\n |\n V\n\n Hamiltonian path problem for undirected graphs\n\n |\n V\n\n Hamiltonian path problem for directed graphs\n", "support_files": [], "metadata": {"number": "6.55", "chapter": 6, "chapter_title": "Context", "section": 6.5, "section_title": "Reductions and Intractability", "type": "Exercise", "code_execution": false}} {"question": "Suppose that two problems are known to be NP-complete. Does this imply that there is a poly-time reduction from one to the other?", "answer": "6.56\n\nYes, if two problems are known to be NP-complete this implies that there is a poly-time reduction from one to the other.\nThis is because all problems in NP poly-time reduce to any NP-complete problem.\nAll NP-complete problems are in NP, therefore, both problems poly-time reduce from one to the other.\n", "support_files": [], "metadata": {"number": "6.56", "chapter": 6, "chapter_title": "Context", "section": 6.5, "section_title": "Reductions and Intractability", "type": "Exercise", "code_execution": false}} {"question": "Suppose that X is NP-complete, X poly-time reduces to Y, and Y poly-time reduces to X. Is Y necessarily NP-complete?", "answer": "Yes, under the standard many-one polynomial-time reduction used for NP-completeness.\n\nSince X is NP-complete, every problem in NP reduces to X. Because X <=p Y, every problem in NP also reduces to Y, so Y is NP-hard.\n\nAlso, Y <=p X and X is in NP. If y is an instance of Y, compute f(y), the corresponding instance of X. A certificate for f(y) can be verified in polynomial time, so Y is in NP.\n\nThus Y is both NP-hard and in NP, so Y is NP-complete.\n", "support_files": [], "metadata": {"number": "6.57", "chapter": 6, "chapter_title": "Context", "section": 6.5, "section_title": "Reductions and Intractability", "type": "Exercise", "code_execution": false}} {"question": "Suppose that we have an algorithm to solve the decision version of boolean satisfiability, which indicates that there exists an assignment of truth values to the variables that satisfies the boolean expression. Show how to find the assignment.", "answer": "Use the decision algorithm as a self-reduction oracle.\n\nFirst ask whether the original formula is satisfiable. If not, there is no assignment. Otherwise process the variables one at a time while permanently keeping the choices already made.\n\nFor variable `x_i`, substitute all previous choices into the formula. Try setting `x_i = true` and call the SAT decision algorithm on the restricted formula. If it remains satisfiable, keep `x_i = true`; otherwise set `x_i = false`, which must preserve satisfiability because the current restricted formula was satisfiable before trying `true`.\n\nAfter `n` oracle calls, all variables are fixed and the accumulated truth values form a satisfying assignment.", "support_files": [], "metadata": {"number": "6.58", "chapter": 6, "chapter_title": "Context", "section": 6.5, "section_title": "Reductions and Intractability", "type": "Exercise", "code_execution": false}} {"question": "Suppose that we have an algorithm to solve the decision version of the vertex cover problem, which indicates that there exists a vertex cover of a given size. Show how to solve the optimization version of finding the vertex cover of minimum cardinality.", "answer": "First find the optimum cardinality `k` by binary searching (or linearly searching) with the decision oracle: ask whether the graph has a vertex cover of size at most `k`.\n\nThen recover an actual cover by self-reduction. Maintain the current graph `G`, target size `k`, and an initially empty cover `C`.\n\nFor each vertex `v`, ask whether `G - v` has a vertex cover of size `k - 1`. If yes, include `v` in `C`, delete `v` and all incident edges from `G`, and decrement `k`. If no, leave `v` out and continue. Stop when no edges remain or `k = 0`.\n\nThe selected vertices form a minimum vertex cover because each inclusion is certified by the decision oracle to still allow a cover of the remaining required size.", "support_files": [], "metadata": {"number": "6.59", "chapter": 6, "chapter_title": "Context", "section": 6.5, "section_title": "Reductions and Intractability", "type": "Exercise", "code_execution": false}} {"question": "Explain why the optimization version of the vertex cover problem is not necessarily a search problem.", "answer": "6.60\n\nThe optimization version of the vertex cover problem is not necessarily a search problem because its output (a vertex cover of minimum cardinality) cannot be certified to be correct in polynomial time. It is possible to certify in polynomial time that the output is a vertex cover, but not that it is a minimum cardinality vertex cover.\n", "support_files": [], "metadata": {"number": "6.60", "chapter": 6, "chapter_title": "Context", "section": 6.5, "section_title": "Reductions and Intractability", "type": "Exercise", "code_execution": false}} {"question": "Suppose that X and Y are two search problems and that X poly-time reduces to Y. Which of the following can we infer?\na. If Y is NP-complete then so is X.\nb. If X is NP-complete then so is Y.\nc. If X is in P, then Y is in P.\nd. If Y is in P, then X is in P.", "answer": "6.61\n\nIf X and Y are two search problems and X poly-time reduces to Y, we can infer that:\n\nb. If X is NP-complete then so is Y.\nThis is because if both X and Y are search problems they are both in NP.\nIf X is NP-complete, then all problems in NP poly-time reduce to it. And if X poly-time reduces to Y, then all problems in NP also poly-time reduce to Y (through X).\nSince Y is both in NP and all problems in NP poly-time reduce to it, Y is NP-complete.\n\nd. If Y is in P, then X is in P.\nIf Y is in P it can be solved in polynomial time. If we can reduce X to Y then we can solve Y in polynomial time and consequently solve X in polynomial time, meaning that X is also in P.\n\nThe following alternatives are wrong:\n\na. If Y is NP-complete then so is X.\nNot necessarily, there may not exist reductions from all problems in NP to X.\n\nc. If X is in P, then Y is in P.\nNot necessarily, Y may be NP-complete and currently it is unknown whether P = NP.\n\n\nThis assumes that \"search problems\" means NP search problems, so membership in NP is part of the premise.", "support_files": [], "metadata": {"number": "6.61", "chapter": 6, "chapter_title": "Context", "section": 6.5, "section_title": "Reductions and Intractability", "type": "Exercise", "code_execution": false}} {"question": "Suppose that P != NP. Which of the following can we infer?\ne. If X is NP-complete, then X cannot be solved in polynomial time.\nf. If X is in NP, then X cannot be solved in polynomial time.\ng. If X is in NP but not NP-complete, then X can be solved in polynomial time.\nh. If X is in P, then X is not NP-complete.", "answer": "If P != NP, we can infer:\n\ne. If X is NP-complete, then X cannot be solved in polynomial time.\nIf some NP-complete X were in P, then every problem in NP would reduce to X and also be in P, implying P = NP.\n\nh. If X is in P, then X is not NP-complete.\nIf a problem in P were NP-complete, again all of NP would be in P.\n\nThe following do not follow:\n\nf. If X is in NP, then X cannot be solved in polynomial time.\nFalse: X might be in P, and P is a subset of NP.\n\ng. If X is in NP but not NP-complete, then X can be solved in polynomial time.\nNot necessarily. If P != NP, there may be problems in NP that are neither in P nor NP-complete.\n", "support_files": [], "metadata": {"number": "6.62", "chapter": 6, "chapter_title": "Context", "section": 6.5, "section_title": "Reductions and Intractability", "type": "Exercise", "code_execution": false}}