question
stringlengths
34
5.53k
answer
stringlengths
21
101k
support_files
listlengths
0
6
metadata
unknown
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.
5.3.3 pattern: A B R A C A D A B R A j 0 pat.charAt(j) A A 1 dfa[][j] B 0 C 0 D 0 … 0 R 0 … 0 j A 0 β€”> 1 / ^ / \ -B,C,D,…,R,…- X j 0 ...
[]
{ "number": "5.3.3", "chapter": 5, "chapter_title": "Strings", "section": 5.3, "section_title": "Substring Search", "type": "Exercise", "code_execution": false }
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.
package chapter5.section3; import edu.princeton.cs.algs4.StdOut; /** * Created by Rene Argento on 24/02/18. */ // Thanks to AdamShamaa (https://github.com/AdamShamaa) for suggesting an optimization to this exercise. // https://github.com/reneargento/algorithms-sedgewick-wayne/issues/174 // Number of character comp...
[]
{ "number": "5.3.4", "chapter": 5, "chapter_title": "Strings", "section": 5.3, "section_title": "Substring Search", "type": "Exercise", "code_execution": false }
Develop a brute-force substring search implementation BruteForceRL that processes the pattern from right to left (a simplified version of ALGORITHM 5.7).
package chapter5.section3; import edu.princeton.cs.algs4.StdOut; /** * Created by Rene Argento on 25/02/18. */ public class Exercise15 { public class BruteForceRL { private String pattern; private int patternLength; BruteForceRL(String pattern) { this.pattern = pattern; ...
[]
{ "number": "5.3.5", "chapter": 5, "chapter_title": "Strings", "section": 5.3, "section_title": "Substring Search", "type": "Exercise", "code_execution": false }
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.
5.3.6 pattern: A B R A C A D A B R A A B R A C A D A B R A c 0 1 2 3 4 5 6 7 8 9 10 right[c] A 0 0 0 3 3 5 5 7 7 7 10 10 B -1 1 1 1 1 1 1 1 8 8 8 8 C -1 -1 -1 -1 4 4 4 4 4 4 4 4 D -1 -1 -1 -1 -1 -1 6 6 6 6 6 6 … ...
[]
{ "number": "5.3.6", "chapter": 5, "chapter_title": "Strings", "section": 5.3, "section_title": "Substring Search", "type": "Exercise", "code_execution": false }
Add to KMP a count() method to count occurrences and a searchAll() method to print all occurrences.
package chapter5.section3; import edu.princeton.cs.algs4.StdOut; /** * Created by Rene Argento on 25/02/18. */ public class Exercise8 { public class KnuthMorrisPrattSearchAll extends KnuthMorrisPratt { KnuthMorrisPrattSearchAll(String pattern) { super(pattern); } // Count ...
[]
{ "number": "5.3.8", "chapter": 5, "chapter_title": "Strings", "section": 5.3, "section_title": "Substring Search", "type": "Exercise", "code_execution": false }
Add to RabinKarp a count() method to count occurrences and a searchAll() method to print all occurrences.
package chapter5.section3; import edu.princeton.cs.algs4.StdOut; /** * Created by Rene Argento on 25/02/18. */ public class Exercise10 { public class RabinKarpSearchAll extends RabinKarp { RabinKarpSearchAll(String pattern, boolean isMonteCarloVersion) { super(pattern, isMonteCarloVersion)...
[]
{ "number": "5.3.10", "chapter": 5, "chapter_title": "Strings", "section": 5.3, "section_title": "Substring Search", "type": "Exercise", "code_execution": false }
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.
5.3.13 Consider 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. Also, consider that the last character in the pattern is c, the index of its last occurrence in the patt...
[]
{ "number": "5.3.13", "chapter": 5, "chapter_title": "Strings", "section": 5.3, "section_title": "Substring Search", "type": "Exercise", "code_execution": false }
Draw the KMP DFA for the following pattern strings. a. AAAAAAB b. AACAAAB c. ABABABAB d. ABAABAAABAAAB e. ABAABCABAABCB
5.3.17 a. AAAAAAB j 0 pat.charAt(j) A A 1 dfa[][j] B 0 … 0 j A 0 β€”> 1 / ^ / \ -B,…- X j 0 1 pat.charAt(j) A A A 1 2 dfa[][j] B 0 0 … 0 0 A j A 0 β€”> 1 β€”> 2...
[]
{ "number": "5.3.17", "chapter": 5, "chapter_title": "Strings", "section": 5.3, "section_title": "Substring Search", "type": "Exercise", "code_execution": false }
How would you modify the Rabin-Karp algorithm to search for an H-by-V pattern in an N-by-N text?
5.3.22 We could compute a pattern hash that is based on each row of V characters in the following way: We 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. So the 1-by-4 pattern RENE and the 2-by-2 pattern RE would have differ...
[]
{ "number": "5.3.22", "chapter": 5, "chapter_title": "Strings", "section": 5.3, "section_title": "Substring Search", "type": "Exercise", "code_execution": false }
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.
package chapter5.section3; import edu.princeton.cs.algs4.StdOut; import java.math.BigInteger; import java.util.Random; /** * Created by Rene Argento on 01/03/18. */ // Based on https://www.geeksforgeeks.org/online-algorithm-for-checking-palindrome-in-a-stream/ // Monte Carlo version - O(N + M) with a probabilisti...
[]
{ "number": "5.3.23", "chapter": 5, "chapter_title": "Strings", "section": 5.3, "section_title": "Substring Search", "type": "Exercise", "code_execution": false }
Find all occurrences. Add a method findAll() to each of the four substring search algorithms given in the text that returns an Iterable<Integer> that allows clients to iterate through all offsets of the pattern in the text.
package chapter5.section3; import chapter1.section3.Queue; import edu.princeton.cs.algs4.StdOut; import java.util.StringJoiner; /** * Created by Rene Argento on 02/03/18. */ public class Exercise24_FindAllOccurrences { public class BruteForceSubstringSearchFindAll extends BruteForceSubstringSearch { ...
[]
{ "number": "5.3.24", "chapter": 5, "chapter_title": "Strings", "section": 5.3, "section_title": "Substring Search", "type": "Creative Problem", "code_execution": false }
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, you...
package chapter5.section3; import edu.princeton.cs.algs4.StdOut; /** * Created by Rene Argento on 03/03/18. */ public class Exercise27_TandemRepeatSearch { // Based on https://algs4.cs.princeton.edu/53substring/ // O(N + M) public class KnuthMorrisPrattTandemRepeat { private String pattern; ...
[]
{ "number": "5.3.27", "chapter": 5, "chapter_title": "Strings", "section": 5.3, "section_title": "Substring Search", "type": "Creative Problem", "code_execution": false }
Random patterns. How many character compares are needed to do a substring search for a random pattern of length 100 in a given text?
5.3.31 - Random patterns None. The method public boolean search(char[] text) { return false; } is 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.
[]
{ "number": "5.3.31", "chapter": 5, "chapter_title": "Strings", "section": 5.3, "section_title": "Substring Search", "type": "Creative Problem", "code_execution": false }
Timings. Write a program that times the four methods for the task of searchng for the substring it is a far far better thing that i do than i have ever done in 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.
// Exercise39_Timings.java package chapter5.section3; import edu.princeton.cs.algs4.StdOut; import edu.princeton.cs.algs4.Stopwatch; import util.Constants; import util.FileUtil; /** * Created by Rene Argento on 09/03/18. */ // The original text in the Tale of Two Cities file is: // "It is a far, far better thing th...
[]
{ "number": "5.3.39", "chapter": 5, "chapter_title": "Strings", "section": 5.3, "section_title": "Substring Search", "type": "Experiment", "code_execution": false }
Give a brief English description of each of the following REs: a. .* b. A.*A | A c. .*ABBABBA.* d. .* A.*A.*A.*A.*
5.4.2 a. Any string (including the empty string). b. Strings that start and end with an A. c. Strings that contain the palindrome ABBABBA. d. Strings that contain at least 4 A's, not necessarily consecutive.
[]
{ "number": "5.4.2", "chapter": 5, "chapter_title": "Strings", "section": 5.4, "section_title": "Regular Expressions", "type": "Exercise", "code_execution": false }
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)?
5.4.3 The 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. Example pattern with M = 4: (A|B)(A|B)(A|B)(A|B) On that pattern every position has two choices, which will yield 2^4 ...
[]
{ "number": "5.4.3", "chapter": 5, "chapter_title": "Strings", "section": 5.4, "section_title": "Regular Expressions", "type": "Exercise", "code_execution": false }
Draw the NFA corresponding to the pattern ( ( ( A | B ) * | C D * | E F G ) * ) * .
5.4.4 Pattern: (((A|B)*|CD*|EFG)*)* NFA: β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” | β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” | | | β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”...
[]
{ "number": "5.4.4", "chapter": 5, "chapter_title": "Strings", "section": 5.4, "section_title": "Regular Expressions", "type": "Exercise", "code_execution": false }
Draw the digraph of Ξ΅-transitions for the NFA from Exercise 5.4.4.
5.4.5 Digraph of e-transitions: β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” | β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” | | | β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”...
[]
{ "number": "5.4.5", "chapter": 5, "chapter_title": "Strings", "section": 5.4, "section_title": "Regular Expressions", "type": "Exercise", "code_execution": false }
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 .
5.4.6 Input: A B B A C E F G E F G C A A B 0 1 2 3 5 7 8 9 13 16 17 18 19 20 : set of states reachable via e-transitions from start 4 : set of states reachable after matching A 0 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 6 : set of states reachable after match...
[]
{ "number": "5.4.6", "chapter": 5, "chapter_title": "Strings", "section": 5.4, "section_title": "Regular Expressions", "type": "Exercise", "code_execution": false }
Write a regular expression for each of the following sets of binary strings: a. Contains at least three consecutive 1s b. Contains the substring 110 c. Contains the substring 1101100 d. Does not contain the substring 110
5.4.8 a. Contains at least three consecutive 1s: (0|1)*(111)+(0|1)* b. Contains the substring 110: (0|1)*110(0|1)* c. Contains the substring 1101100: (0|1)*1101100(0|1)* d. Does not contain the substring 110: (0|10)*1*
[]
{ "number": "5.4.8", "chapter": 5, "chapter_title": "Strings", "section": 5.4, "section_title": "Regular Expressions", "type": "Exercise", "code_execution": false }
Write a regular expression for each of the following sets of binary strings: a. Has at least 3 characters, and the third character is 0 b. Number of 0s is a multiple of 3 c. Starts and ends with the same character d. Odd length e. Starts with 0 and has odd length, or starts with 1 and has even length f. Length is at le...
a. At least 3 characters, third character is 0: `(0|1)(0|1)0(0|1)*` b. Number of 0s is a multiple of 3: `1*(01*01*01*)*` c. Starts and ends with the same character: `0|1|0(0|1)*0|1(0|1)*1` d. Odd length: `((0|1)(0|1))*(0|1)` e. Starts with 0 and has odd length, or starts with 1 and has even length: `0((0|1)(0|1))*|...
[]
{ "number": "5.4.10", "chapter": 5, "chapter_title": "Strings", "section": 5.4, "section_title": "Regular Expressions", "type": "Exercise", "code_execution": false }
Challenging REs. Construct an RE that describes each of the following sets of strings over the binary alphabet: a. All strings except 11 or 111 b. Strings with 1 in every odd-number bit position c. Strings with at least two 0s and at most one 1 d. Strings with no two consecutive 1s
5.4.13 - Challenging REs a. All strings except 11 or 111: 1|(1*01*|1111(0|1)*)* b. Strings with 1 in every odd-number bit position: (10|11)*1* c. Strings with at least two 0s and at most one 1: 1?00+|0+1?0+|00+1? d. Strings with no two consecutive 1s: (0|10)*1?
[]
{ "number": "5.4.13", "chapter": 5, "chapter_title": "Strings", "section": 5.4, "section_title": "Regular Expressions", "type": "Creative Problem", "code_execution": false }
Wildcard. Add to NFA the capability to handle wildcards.
package chapter5.section4; import chapter1.section3.Bag; import chapter4.section2.DirectedDFS; import edu.princeton.cs.algs4.StdOut; /** * Created by Rene Argento on 23/03/18. */ public class Exercise17_Wildcard { public class RegularExpressionMatcherWildcard extends RegularExpressionMatcher { public ...
[]
{ "number": "5.4.17", "chapter": 5, "chapter_title": "Strings", "section": 5.4, "section_title": "Regular Expressions", "type": "Creative Problem", "code_execution": false }
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).
package chapter5.section4; import chapter1.section3.Bag; import chapter1.section3.Stack; import chapter4.section2.Digraph; import edu.princeton.cs.algs4.StdOut; import java.util.StringJoiner; /** * Created by Rene Argento on 25/03/18. */ @SuppressWarnings("unchecked") public class Exercise22_Proof { private c...
[]
{ "number": "5.4.22", "chapter": 5, "chapter_title": "Strings", "section": 5.4, "section_title": "Regular Expressions", "type": "Creative Problem", "code_execution": false }
Given a example of a uniquely decodable code that is not prefix-free.
5.5.2 Example of a uniquely decodable code that is not prefix-free: Any suffix-free code is uniquely decodable. Example: { 0, 01, 011, 0111 }
[]
{ "number": "5.5.2", "chapter": 5, "chapter_title": "Strings", "section": 5.5, "section_title": "Data Compression", "type": "Exercise", "code_execution": false }
Give an example of a uniquely decodable code that is not prefix free or suffix free.
5.5.3 Example of a uniquely decodable code that is not prefix-free or suffix-free: { 0011, 011, 11, 1110 } or { 01, 10, 011, 110 }
[]
{ "number": "5.5.3", "chapter": 5, "chapter_title": "Strings", "section": 5.5, "section_title": "Data Compression", "type": "Exercise", "code_execution": false }
Are { 1, 100000, 00 } and { 01, 1001, 1011, 111, 1110 } uniquely decodable? If not, find a string with two encodings.
5.5.4 { 1, 100000, 00 } is uniquely decodable. { 01, 1001, 1011, 111, 1110 } is not uniquely decodable. The string 11101111001 can be decoded both as 1110-111-1001 and 111-01-1110-01.
[]
{ "number": "5.5.4", "chapter": 5, "chapter_title": "Strings", "section": 5.5, "section_title": "Data Compression", "type": "Exercise", "code_execution": false }
Use RunLength on the file q64x96.bin from the booksite. How many bits are there in the compressed file?
5.5.5 The file q128x192.bin was not found anywhere on the booksite or in the data URL https://algs4.cs.princeton.edu/code/algs4-data.zip However, 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 . In the uncom...
[]
{ "number": "5.5.5", "chapter": 5, "chapter_title": "Strings", "section": 5.5, "section_title": "Data Compression", "type": "Exercise", "code_execution": false }
How many bits are needed to encode N copies of the symbol a (as a function of N)? N copies of the sequence abc?
5.5.6 Copies of symbol a: % more 5.5_input_1a.txt a % more 5.5_input_2a.txt aa % more 5.5_input_3a.txt aaa % more 5.5_input_20a.txt aaaaaaaaaaaaaaaaaaaa *** Run-length encoding *** % java -cp algs4.jar:. RunLengthEncoding - < 5.5_input_1a.txt | java -cp algs4.jar:. BinaryDump 0 32 bits % java -cp algs4.jar:. R...
[]
{ "number": "5.5.6", "chapter": 5, "chapter_title": "Strings", "section": 5.5, "section_title": "Data Compression", "type": "Exercise", "code_execution": false }
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?
Let the input be `(ab)^N`, so the uncompressed input has `2N` 8-bit characters, or `16N` bits. Run-length encoding in the algs4 binary format emits `64N + 8` bits for this alternating input. Its compression ratio is therefore `(64N + 8) / (16N) = 4 + 1/(2N)`. So run-length encoding expands the data by about 4x. Huf...
[]
{ "number": "5.5.8", "chapter": 5, "chapter_title": "Strings", "section": 5.5, "section_title": "Data Compression", "type": "Exercise", "code_execution": false }
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?
5.5.10 text: it was the age of foolishness Frequencies 2 2 5 1 2 4 2 3 1 3 2 1 1 i t SP w a s h e g o f l n Ordered frequencies and trie construction 1 1 1 1 2 2 2 2 2 3 3 4 5 w g l n i t a h f e o s SP 1 1 2 2 2 2 2 2 3 3 4 5 l n 1 1 i t a h f...
[]
{ "number": "5.5.10", "chapter": 5, "chapter_title": "Strings", "section": 5.5, "section_title": "Data Compression", "type": "Exercise", "code_execution": false }
Suppose that all of the symbol frequencies are equal. Describe the Huffman code.
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. If the alphabet size `R` is a power of two, every codeword has length `lg R`. If `R` is not a power of two,...
[]
{ "number": "5.5.13", "chapter": 5, "chapter_title": "Strings", "section": 5.5, "section_title": "Data Compression", "type": "Exercise", "code_execution": false }
Characterize the tricky situation in LZW coding.
5.5.17 The 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 alread...
[]
{ "number": "5.5.17", "chapter": 5, "chapter_title": "Strings", "section": 5.5, "section_title": "Data Compression", "type": "Exercise", "code_execution": false }
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.
5.5.22 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. Proof: Suppose 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...
[]
{ "number": "5.5.22", "chapter": 5, "chapter_title": "Strings", "section": 5.5, "section_title": "Data Compression", "type": "Exercise", "code_execution": false }
What would be the result of breaking up a Huffman-encoded string into five-bit characters and Huffman-encoding that string?
5.5.23 Breaking 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. Proof: Consider that the string has N bits. The best case happens when all 5-bit strings are equal: the re...
[]
{ "number": "5.5.23", "chapter": 5, "chapter_title": "Strings", "section": 5.5, "section_title": "Data Compression", "type": "Exercise", "code_execution": false }
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 it was the best of times it was the worst of times
5.5.24 text: it was the best of times it was the worst of times Compression process input 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 ...
[]
{ "number": "5.5.24", "chapter": 5, "chapter_title": "Strings", "section": 5.5, "section_title": "Data Compression", "type": "Exercise", "code_execution": false }
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.
5.5.27 - Long repeats Compressing 2 * 1000 random characters (for N = 1000), with 16000 bits (8 bits per character). % java -cp algs4.jar:. RunLengthEncoding - < 5.5.27_random.txt | java -cp algs4.jar:. BinaryDump 0 53736 bits Compression ratio: 53736 / 16000 = 335% % java -cp algs4.jar:. edu.princeton.cs.algs4.Huf...
[]
{ "number": "5.5.27", "chapter": 5, "chapter_title": "Strings", "section": 5.5, "section_title": "Data Compression", "type": "Creative Problem", "code_execution": false }
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 fra...
6.9 Results Time 0 LEFT VESSEL: 10 particles Type 1: 10/10 Type 2: 0/10 RIGHT VESSEL: 10 particles Type 1: 0/10 Type 2: 10/10 Time 1000 LEFT VESSEL: 14 particles Type 1: 9/14 Type 2: 5/14 RIGHT VESSEL: 6 particles Type 1: 1/6 Type 2: 5/6 Time 2000 LEFT VESSEL: 11 particles Type 1: 6/11 Type 2: 5/11 RIGHT VESSEL: 9 ...
[]
{ "number": "6.9", "chapter": 6, "chapter_title": "Context", "section": 6.1, "section_title": "Collision Simulation", "type": "Exercise", "code_execution": false }
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.
6.10 Roundoff error: 0.22176242098152166
[]
{ "number": "6.10", "chapter": 6, "chapter_title": "Context", "section": 6.1, "section_title": "Collision Simulation", "type": "Exercise", "code_execution": false }
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.
The pressure measurement should use impulse delivered to the container walls, not particle volume. For 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: `P = totalWallImpulse / (perimeter * t)`....
[]
{ "number": "6.11", "chapter": 6, "chapter_title": "Context", "section": 6.1, "section_title": "Collision Simulation", "type": "Exercise", "code_execution": false }
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.
// Exercise13_PriorityQueuePerformance.java package chapter6.eventdrivensimulation; import chapter2.section4.IndexMinPriorityQueue; import chapter2.section4.PriorityQueueResize; import edu.princeton.cs.algs4.StdDraw; import edu.princeton.cs.algs4.StdOut; import edu.princeton.cs.algs4.StdRandom; import edu.princeton.cs...
[]
{ "number": "6.13", "chapter": 6, "chapter_title": "Context", "section": 6.1, "section_title": "Collision Simulation", "type": "Exercise", "code_execution": false }
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?
6.14 The 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 high...
[]
{ "number": "6.14", "chapter": 6, "chapter_title": "Context", "section": 6.2, "section_title": "B-Trees", "type": "Exercise", "code_execution": false }
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.
6.18 Let 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. With 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 r...
[]
{ "number": "6.18", "chapter": 6, "chapter_title": "Context", "section": 6.2, "section_title": "B-Trees", "type": "Exercise", "code_execution": false }
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 creat...
6.20 - B* trees Bounds on the number of probes used for a search or an insertion in a B*-tree of order M with N items: Between log(M) N and log(2M/3) N probes. This 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 ca...
[]
{ "number": "6.20", "chapter": 6, "chapter_title": "Context", "section": 6.2, "section_title": "B-Trees", "type": "Exercise", "code_execution": false }
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.
6.21 Results: Order M | Number of items | AVG Number of External Pages 4 100000 42865 4 1000000 428592 4 10000000 4276006 16 100000 9424 ...
[]
{ "number": "6.21", "chapter": 6, "chapter_title": "Context", "section": 6.2, "section_title": "B-Trees", "type": "Exercise", "code_execution": false }
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.
6.22 Results: Number of searches | B-tree time | Binary search time 1000 0.005 0.001 100000 0.082 0.013 10000000 6.352 0.910 For random searches in a huge symbol table (with 10,000,000 entries) binary sea...
[]
{ "number": "6.22", "chapter": 6, "chapter_title": "Context", "section": 6.2, "section_title": "B-Trees", "type": "Exercise", "code_execution": false }
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.
6.23 Results: Order M | Number of searches | Total time 100 1000 0.005 100 100000 0.198 100 10000000 19.973 200 1000 0.002 200 100000 0.195 200 10000000 ...
[]
{ "number": "6.23", "chapter": 6, "chapter_title": "Context", "section": 6.2, "section_title": "B-Trees", "type": "Exercise", "code_execution": false }
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.
6.24 Results: Number of searches | B-tree time | Linear probing hashing time | Red-Black tree time 1000 0.004 0.001 0.002 100000 0.173 0.019 0.114 10000000 16.659 ...
[]
{ "number": "6.24", "chapter": 6, "chapter_title": "Context", "section": 6.2, "section_title": "B-Trees", "type": "Exercise", "code_execution": false }
Give, in the style of the figure on page 882, the suffixes, sorted suffixes, index() and lcp() tables for the following strings: a. abacadaba b. mississippi c. abcdefghij d. aaaaaaaaaa
6.25 a. abacadaba suffixes sorted suffix array i index(i) lcp(i) 0 abacadaba 0 8 0 a 1 bacadaba 1 6 1 aba 2 acadaba 2 0 3 abacadaba 3 cadaba 3 2 1 acadaba 4 adaba 4 4 1 adaba 5 daba ...
[]
{ "number": "6.25", "chapter": 6, "chapter_title": "Context", "section": 6.3, "section_title": "Suffix Arrays", "type": "Exercise", "code_execution": false }
Identify the problem with the following code fragment to compute all the suffixes for suffix sort: suffix = ""; for (int i = s.length() - 1; i >= 0; i--) { suffix = s.charAt(i) + suffix; suffixes[i] = suffix; }
The problem is that Java strings are immutable. Each statement suffix = s.charAt(i) + suffix; creates 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. A suffix-sort implementation shou...
[]
{ "number": "6.26", "chapter": 6, "chapter_title": "Context", "section": 6.3, "section_title": "Suffix Arrays", "type": "Exercise", "code_execution": false }
Under the assumptions described in SECTION 1.4. give the memory usage of a SuffixArray object with a string of length N.
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. Per `Suffix` object: `16` object overhead + `8` text reference + `4` int index + `4` padding = `32` bytes. `SuffixArray` object excluding the input `String`...
[]
{ "number": "6.29", "chapter": 6, "chapter_title": "Context", "section": 6.3, "section_title": "Suffix Arrays", "type": "Exercise", "code_execution": false }
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 ...
```java import edu.princeton.cs.algs4.In; import edu.princeton.cs.algs4.StdOut; import edu.princeton.cs.algs4.SuffixArray; public class LCS { private static boolean inFirstText(int index, int firstLength) { return index < firstLength; } private static char delimiter(String a, String b) { f...
[]
{ "number": "6.30", "chapter": 6, "chapter_title": "Context", "section": 6.3, "section_title": "Suffix Arrays", "type": "Exercise", "code_execution": false }
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.
Let C = M - 1 be the largest possible capacity. If parallel edges are allowed, the maximum flow can be E * C: put all E edges directly from s to t, each with capacity C. If 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 a...
[]
{ "number": "6.36", "chapter": 6, "chapter_title": "Context", "section": 6.4, "section_title": "Maxflow", "type": "Exercise", "code_execution": false }
Give an algorithm to solve the maxflow problem for the case that the network forms a tree if the sink is removed.
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. Let value(v) be: sum of capacities of edges v->t + sum over children w of min(capacity(v, w), value(w)) Compute value(v) by a posto...
[]
{ "number": "6.37", "chapter": 6, "chapter_title": "Context", "section": 6.4, "section_title": "Maxflow", "type": "Exercise", "code_execution": false }
If true provide a short proof, if false give a counterexample: a. In any max flow, there is no directed cycle on which every edge carries positive flow b. There exists a max flow for which there is no directed cycle on which every edge carries positive flow c. If all edge capacities are distinct, the max flow is unique...
6.38 - True of false a. In any max flow, there is no directed cycle on which every edge carries positive flow. False. Counterexample: s | ^ 2/2| |1/1 v | 1 | |1/1 v t b. There exists a max flow for which there is no directed cycle on which every edge carries positive flow. True. Proof: ...
[]
{ "number": "6.38", "chapter": 6, "chapter_title": "Context", "section": 6.4, "section_title": "Maxflow", "type": "Exercise", "code_execution": false }
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.
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 `d_f(v) = d_f(u) + 1`. For `u->v` to become critical again later, the residual capacity of `u->v` must first be restored. The on...
[]
{ "number": "6.39", "chapter": 6, "chapter_title": "Context", "section": 6.4, "section_title": "Maxflow", "type": "Exercise", "code_execution": false }
Prove that the shortest-paths problem reduces to linear programming.
6.50 Reduction from shortest paths problem to linear programming: Method 1: We consider a system of inequalities and equations that involve the following variables: l(u,v) -> variable corresponding to the length of the directed edge u -> v. x(u,v) -> indicator variable for whether edge u -> v is in the shortest path....
[]
{ "number": "6.50", "chapter": 6, "chapter_title": "Context", "section": 6.5, "section_title": "Reductions and Intractability", "type": "Exercise", "code_execution": false }
Could there be an algorithm that solves an NP-complete problem in an average time of NlogN, if P != NP? Explain your 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 instance...
[]
{ "number": "6.51", "chapter": 6, "chapter_title": "Context", "section": 6.5, "section_title": "Reductions and Intractability", "type": "Exercise", "code_execution": false }
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?
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 poly(N) + 1.1^p(N) That is exponential if p...
[]
{ "number": "6.52", "chapter": 6, "chapter_title": "Context", "section": 6.5, "section_title": "Reductions and Intractability", "type": "Exercise", "code_execution": false }
What would be the significance of a program that could solve the integer linear programming problem in time proportional to 1.1^N?
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. It would not imply P = NP, because 1.1^N is still exponential. It also would not automati...
[]
{ "number": "6.53", "chapter": 6, "chapter_title": "Context", "section": 6.5, "section_title": "Reductions and Intractability", "type": "Exercise", "code_execution": false }
Give a poly-time reduction from vertex cover to 0-1 integer linear inequality satisfiability.
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. Add the constraints x_u + x_v >= 1 for every edge (u, v) in E sum_{v in V} x_v <= k x_v in {0, 1} for every vertex v The edge constra...
[]
{ "number": "6.54", "chapter": 6, "chapter_title": "Context", "section": 6.5, "section_title": "Reductions and Intractability", "type": "Exercise", "code_execution": false }
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.
6.55 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. Let's call the Hamiltonian path problem in undirected graphs HPg and the Hamiltonian path problem in directed graphs HPdg. Reduction from HPg ...
[]
{ "number": "6.55", "chapter": 6, "chapter_title": "Context", "section": 6.5, "section_title": "Reductions and Intractability", "type": "Exercise", "code_execution": false }
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?
6.56 Yes, if two problems are known to be NP-complete this implies that there is a poly-time reduction from one to the other. This is because all problems in NP poly-time reduce to any NP-complete problem. All NP-complete problems are in NP, therefore, both problems poly-time reduce from one to the other.
[]
{ "number": "6.56", "chapter": 6, "chapter_title": "Context", "section": 6.5, "section_title": "Reductions and Intractability", "type": "Exercise", "code_execution": false }
Suppose that X is NP-complete, X poly-time reduces to Y, and Y poly-time reduces to X. Is Y necessarily NP-complete?
Yes, under the standard many-one polynomial-time reduction used for NP-completeness. Since 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. Also, Y <=p X and X is in NP. If y is an instance of Y, compute f(y), the corresponding instance of X....
[]
{ "number": "6.57", "chapter": 6, "chapter_title": "Context", "section": 6.5, "section_title": "Reductions and Intractability", "type": "Exercise", "code_execution": false }
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.
Use the decision algorithm as a self-reduction oracle. First 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. For variable `x_i`, substitute all previous choices into the formula. Try sett...
[]
{ "number": "6.58", "chapter": 6, "chapter_title": "Context", "section": 6.5, "section_title": "Reductions and Intractability", "type": "Exercise", "code_execution": false }
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.
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`. Then recover an actual cover by self-reduction. Maintain the current graph `G`, target size `k`, and an initially empty cover `C`. For each vertex ...
[]
{ "number": "6.59", "chapter": 6, "chapter_title": "Context", "section": 6.5, "section_title": "Reductions and Intractability", "type": "Exercise", "code_execution": false }
Explain why the optimization version of the vertex cover problem is not necessarily a search problem.
6.60 The 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 car...
[]
{ "number": "6.60", "chapter": 6, "chapter_title": "Context", "section": 6.5, "section_title": "Reductions and Intractability", "type": "Exercise", "code_execution": false }
Suppose that X and Y are two search problems and that X poly-time reduces to Y. Which of the following can we infer? a. If Y is NP-complete then so is X. b. If X is NP-complete then so is Y. c. If X is in P, then Y is in P. d. If Y is in P, then X is in P.
6.61 If X and Y are two search problems and X poly-time reduces to Y, we can infer that: b. If X is NP-complete then so is Y. This is because if both X and Y are search problems they are both in NP. If 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...
[]
{ "number": "6.61", "chapter": 6, "chapter_title": "Context", "section": 6.5, "section_title": "Reductions and Intractability", "type": "Exercise", "code_execution": false }
Suppose that P != NP. Which of the following can we infer? e. If X is NP-complete, then X cannot be solved in polynomial time. f. If X is in NP, then X cannot be solved in polynomial time. g. If X is in NP but not NP-complete, then X can be solved in polynomial time. h. If X is in P, then X is not NP-complete.
If P != NP, we can infer: e. If X is NP-complete, then X cannot be solved in polynomial time. If some NP-complete X were in P, then every problem in NP would reduce to X and also be in P, implying P = NP. h. If X is in P, then X is not NP-complete. If a problem in P were NP-complete, again all of NP would be in P. T...
[]
{ "number": "6.62", "chapter": 6, "chapter_title": "Context", "section": 6.5, "section_title": "Reductions and Intractability", "type": "Exercise", "code_execution": false }