Certainly! Let's implement the Autocomplete class as described in Part 3 of your assignment. This class will utilize the previously provided Term and BinarySearchDeluxe classes to efficiently provide autocomplete functionality.
Overview
The Autocomplete class provides functionality to:
- Initialize with a given array of
Term objects.
- Find all matching terms that start with a given prefix, sorted in descending order of weight.
- Count the number of matching terms for a given prefix.
Key Steps in Implementation
-
Constructor:
- Validate the input array and its elements.
- Create a defensive copy of the input array to ensure immutability.
- Sort the copied array lexicographically (natural order).
-
allMatches(String prefix):
- Validate the input prefix.
- Use binary search to find the range of terms matching the prefix.
- Collect and sort these terms in descending order of weight.
- Return the sorted array of matching terms.
-
numberOfMatches(String prefix):
- Validate the input prefix.
- Use binary search to find the range of terms matching the prefix.
- Calculate and return the number of matching terms.
-
Unit Testing:
- Provide a
main method to demonstrate and test the functionality of the Autocomplete class.
Let's proceed with the implementation.
Implementation
import edu.princeton.cs.algs4.StdOut;
import java.util.Arrays;
import java.util.Comparator;
public class Autocomplete {
private final Term[] terms;
/**
* Initializes the data structure from the given array of terms.
* @param terms array of Term objects
* @throws IllegalArgumentException if the array is null or any term is null
*/
public Autocomplete(Term[] terms) {
if (terms == null) {
throw new IllegalArgumentException("Terms array cannot be null.");
}
// Defensive copy
this.terms = new Term[terms.length];
for (int i = 0; i < terms.length; i++) {
if (terms[i] == null) {
throw new IllegalArgumentException("Term at index " + i + " is null.");
}
this.terms[i] = terms[i];
}
// Sort the array in natural (lexicographic) order
Arrays.sort(this.terms);
}
/**
* Returns all terms that start with the given prefix,
* in descending order of weight.
* @param prefix the prefix string
* @return array of matching Term objects sorted by descending weight
* @throws IllegalArgumentException if prefix is null
*/
public Term[] allMatches(String prefix) {
if (prefix == null) {
throw new IllegalArgumentException("Prefix cannot be null.");
}
if (prefix.isEmpty()) {
// If prefix is empty, all terms match
Term[] allTerms = Arrays.copyOf(this.terms, this.terms.length);
Arrays.sort(allTerms, Term.byReverseWeightOrder());
return allTerms;
}
int prefixLength = prefix.length();
Term key = new Term(prefix, 0); // Weight is irrelevant for comparison
// Comparator that compares terms based on prefix
Comparator<Term> prefixComparator = Term.byPrefixOrder(prefixLength);
// Find the first and last index of terms matching the prefix
int firstIndex = BinarySearchDeluxe.firstIndexOf(this.terms, key, prefixComparator);
if (firstIndex == -1) {
// No matches found
return new Term[0];
}
int lastIndex = BinarySearchDeluxe.lastIndexOf(this.terms, key, prefixComparator);
// Number of matching terms
int numberOfMatches = lastIndex - firstIndex + 1;
Term[] matches = new Term[numberOfMatches];
for (int i = 0; i < numberOfMatches; i++) {
matches[i] = this.terms[firstIndex + i];
}
// Sort the matching terms in descending order of weight
Arrays.sort(matches, Term.byReverseWeightOrder());
return matches;
}
/**
* Returns the number of terms that start with the given prefix.
* @param prefix the prefix string
* @return number of matching terms
* @throws IllegalArgumentException if prefix is null
*/
public int numberOfMatches(String prefix) {
if (prefix == null) {
throw new IllegalArgumentException("Prefix cannot be null.");
}
if (prefix.isEmpty()) {
// All terms match
return this.terms.length;
}
int prefixLength = prefix.length();
Term key = new Term(prefix, 0); // Weight is irrelevant for comparison
// Comparator that compares terms based on prefix
Comparator<Term> prefixComparator = Term.byPrefixOrder(prefixLength);
// Find the first and last index of terms matching the prefix
int firstIndex = BinarySearchDeluxe.firstIndexOf(this.terms, key, prefixComparator);
if (firstIndex == -1) {
// No matches found
return 0;
}
int lastIndex = BinarySearchDeluxe.lastIndexOf(this.terms, key, prefixComparator);
return lastIndex - firstIndex + 1;
}
/**
* Unit testing for Autocomplete.
* Demonstrates the functionality of the Autocomplete class.
*/
public static void main(String[] args) {
// Sample terms
Term term1 = new Term("apple", 100);
Term term2 = new Term("app", 80);
Term term3 = new Term("application", 120);
Term term4 = new Term("banana", 90);
Term term5 = new Term("bandana", 70);
Term term6 = new Term("band", 60);
Term term7 = new Term("ape", 50);
Term term8 = new Term("apex", 110);
Term term9 = new Term("apply", 95);
Term term10 = new Term("appetite", 85);
// Create an array of terms
Term[] terms = {term1, term2, term3, term4, term5, term6, term7, term8, term9, term10};
// Initialize Autocomplete
Autocomplete autocomplete = new Autocomplete(terms);
// Test allMatches
String prefix1 = "app";
StdOut.println("All matches for prefix \"" + prefix1 + "\":");
Term[] matches1 = autocomplete.allMatches(prefix1);
for (Term term : matches1) {
StdOut.println(term);
}
// Test numberOfMatches
StdOut.println("\nNumber of matches for prefix \"" + prefix1 + "\": " + autocomplete.numberOfMatches(prefix1));
// Another test case
String prefix2 = "ban";
StdOut.println("\nAll matches for prefix \"" + prefix2 + "\":");
Term[] matches2 = autocomplete.allMatches(prefix2);
for (Term term : matches2) {
StdOut.println(term);
}
StdOut.println("\nNumber of matches for prefix \"" + prefix2 + "\": " + autocomplete.numberOfMatches(prefix2));
// Test with empty prefix
String prefix3 = "";
StdOut.println("\nAll matches for empty prefix:");
Term[] matches3 = autocomplete.allMatches(prefix3);
for (Term term : matches3) {
StdOut.println(term);
}
StdOut.println("\nNumber of matches for empty prefix: " + autocomplete.numberOfMatches(prefix3));
// Test with no matches
String prefix4 = "xyz";
StdOut.println("\nAll matches for prefix \"" + prefix4 + "\":");
Term[] matches4 = autocomplete.allMatches(prefix4);
for (Term term : matches4) {
StdOut.println(term);
}
StdOut.println("\nNumber of matches for prefix \"" + prefix4 + "\": " + autocomplete.numberOfMatches(prefix4));
}
}
Explanation
1. Constructor: Autocomplete(Term[] terms)
-
Validation:
- Checks if the input array
terms is null.
- Checks each
Term in the array to ensure none are null.
-
Defensive Copy:
- Creates a new array to prevent external modifications from affecting the internal state.
-
Sorting:
- Sorts the copied array in natural (lexicographic) order using
Arrays.sort(this.terms);. This sorting is essential for binary search operations.
2. Method: allMatches(String prefix)
3. Method: numberOfMatches(String prefix)
4. Unit Testing: main(String[] args)
Running the Unit Tests
When you run the main method of the Autocomplete class, you should observe output similar to the following:
All matches for prefix "app":
120 application
100 apple
95 apply
85 appetite
80 app
Number of matches for prefix "app": 5
All matches for prefix "ban":
90 banana
70 bandana
60 band
Number of matches for prefix "ban": 3
All matches for empty prefix:
120 application
110 apex
100 apple
95 apply
90 banana
85 appetite
80 app
70 bandana
60 band
50 ape
Number of matches for empty prefix: 10
All matches for prefix "xyz":
Number of matches for prefix "xyz": 0
This output demonstrates that the Autocomplete class correctly identifies and sorts matching terms based on the provided prefix.
Complete Code Listings
Ensure that you have the Term.java and BinarySearchDeluxe.java classes implemented as provided earlier. Below are the complete code listings for all three classes for reference.
Term.java
import edu.princeton.cs.algs4.StdOut;
import java.util.Comparator;
public class Term implements Comparable<Term> {
private final String query;
private final long weight;
// Initializes a term with the given query string and weight.
public Term(String query, long weight) {
if (query == null) {
throw new IllegalArgumentException("query cannot be null");
} else if (weight < 0) {
throw new IllegalArgumentException("weight cannot be negative");
}
this.query = query;
this.weight = weight;
}
// Compares the two terms in descending order by weight.
public static Comparator<Term> byReverseWeightOrder() {
return new Comparator<Term>() {
@Override
public int compare(Term t1, Term t2) {
return Long.compare(t2.weight, t1.weight); // Descending order
}
};
}
// Compares the two terms in lexicographic order,
// but using only the first r characters of each query.
public static Comparator<Term> byPrefixOrder(int r) {
if (r < 0) {
throw new IllegalArgumentException("r cannot be negative");
}
return new Comparator<Term>() {
@Override
public int compare(Term t1, Term t2) {
String t1SubString;
String t2SubString;
// Prevent out of bounds if prefix r > string length
if (r <= t1.query.length()) {
t1SubString = t1.query.substring(0, r);
} else {
t1SubString = t1.query;
}
if (r <= t2.query.length()) {
t2SubString = t2.query.substring(0, r);
} else {
t2SubString = t2.query;
}
return t1SubString.compareTo(t2SubString);
}
};
}
// Compares the two terms in lexicographic order by query.
@Override
public int compareTo(Term that) {
return this.query.compareTo(that.query);
}
// Returns a string representation of this term:
// the weight, followed by a tab, followed by the query.
@Override
public String toString() {
return weight + "\t" + query;
}
// Getters (optional, if needed)
public String getQuery() {
return query;
}
public long getWeight() {
return weight;
}
// Unit testing (required)
public static void main(String[] args) {
Term t1 = new Term("bleh bleh", 12345);
Term t2 = new Term("word", 41238);
StdOut.println(t1);
StdOut.println(t2);
StdOut.println(t1.compareTo(t2)); // Should be negative
StdOut.println(t2.compareTo(t1)); // Should be positive
Comparator<Term> reverseWeight = Term.byReverseWeightOrder();
StdOut.println("Reverse Weight Comparator Example:");
StdOut.println(reverseWeight.compare(t1, t2)); // Should compare based on weight
Comparator<Term> prefixComparator = Term.byPrefixOrder(3);
StdOut.println("Prefix Comparator Example (first 3 characters):");
StdOut.println(prefixComparator.compare(t1, t2)); // Depends on first 3 characters
}
}
BinarySearchDeluxe.java
import edu.princeton.cs.algs4.StdOut;
import java.util.Comparator;
public class BinarySearchDeluxe {
/**
* Returns the index of the first key in the sorted array a[]
* that is equal to the search key, or -1 if no such key.
* @param <Key> the type parameter
* @param a sorted array of Key objects
* @param key the search key
* @param comparator the comparator to determine equality
* @return index of the first matching key or -1 if not found
* @throws IllegalArgumentException if any argument is null
*/
public static <Key> int firstIndexOf(Key[] a, Key key, Comparator<Key> comparator) {
// Edge cases
if (a == null) {
throw new IllegalArgumentException("Array cannot be null.");
}
if (key == null) {
throw new IllegalArgumentException("Key cannot be null.");
}
if (comparator == null) {
throw new IllegalArgumentException("Comparator cannot be null.");
}
int low = 0;
int high = a.length - 1;
int result = -1;
// Standard binary search
while (low <= high) {
int mid = low + (high - low) / 2;
int cmp = comparator.compare(key, a[mid]);
if (cmp < 0) {
high = mid - 1; // Search left half
} else if (cmp > 0) {
low = mid + 1; // Search right half
} else {
result = mid;
high = mid - 1; // Continue searching left half
}
}
return result;
}
/**
* Returns the index of the last key in the sorted array a[]
* that is equal to the search key, or -1 if no such key.
* @param <Key> the type parameter
* @param a sorted array of Key objects
* @param key the search key
* @param comparator the comparator to determine equality
* @return index of the last matching key or -1 if not found
* @throws IllegalArgumentException if any argument is null
*/
public static <Key> int lastIndexOf(Key[] a, Key key, Comparator<Key> comparator) {
// Edge cases
if (a == null) {
throw new IllegalArgumentException("Array cannot be null.");
}
if (key == null) {
throw new IllegalArgumentException("Key cannot be null.");
}
if (comparator == null) {
throw new IllegalArgumentException("Comparator cannot be null.");
}
int low = 0;
int high = a.length - 1;
int result = -1;
// Standard binary search
while (low <= high) {
int mid = low + (high - low) / 2;
int cmp = comparator.compare(key, a[mid]);
if (cmp < 0) {
high = mid - 1; // Search left half
} else if (cmp > 0) {
low = mid + 1; // Search right half
} else {
result = mid;
low = mid + 1; // Continue searching right half
}
}
return result;
}
/**
* Unit testing for BinarySearchDeluxe.
*/
public static void main(String[] args) {
// Example with Strings
String[] a = { "A", "A", "A", "A", "A", "A", "Z", "Z", "Z", "Z" };
Comparator<String> comparator = String.CASE_INSENSITIVE_ORDER;
int indexFirst = BinarySearchDeluxe.firstIndexOf(a, "Z", comparator);
int indexLast = BinarySearchDeluxe.lastIndexOf(a, "A", comparator);
StdOut.println("First index of 'Z': " + indexFirst); // Expected: 6
StdOut.println("Last index of 'A': " + indexLast); // Expected: 5
// Example with Terms
Term term1 = new Term("AAA", 0);
Term term2 = new Term("AAA", 1);
Term term3 = new Term("AAAB", 2);
Term term4 = new Term("AAB", 3);
Term term5 = new Term("AAB", 4);
Term term6 = new Term("AAB", 5);
Term term7 = new Term("AAC", 6);
Term term8 = new Term("AAD", 7);
Term term9 = new Term("AAE", 8);
Term term10 = new Term("AAF", 9);
Term[] termList = {term1, term2, term3, term4, term5, term6, term7, term8, term9, term10};
Comparator<Term> comparatorP2 = Term.byPrefixOrder(2);
Term searchKey = new Term("AA", 0);
int indexTermFirst = BinarySearchDeluxe.firstIndexOf(termList, searchKey, comparatorP2);
int indexTermLast = BinarySearchDeluxe.lastIndexOf(termList, searchKey, comparatorP2);
StdOut.println("First index of prefix 'AA': " + indexTermFirst); // Expected: 0
StdOut.println("Last index of prefix 'AA': " + indexTermLast); // Expected: 9
}
}
Autocomplete.java
(As provided above.)
Conclusion
The Autocomplete class efficiently provides autocomplete functionality by leveraging sorted data and binary search techniques. By carefully managing the internal state and adhering to immutability principles, it ensures both robustness and performance. The provided unit tests demonstrate its correctness across various scenarios, including edge cases.
Feel free to integrate this class into your application and extend it further as needed. If you have any questions or need further assistance, don't hesitate to ask!