Question

Trying to make an autocomplete java program that given a prefix, find all strings in set...

Trying to make an autocomplete java program that given a prefix, find all strings in set that start with said prefix, in descending weight order. I created the classes Term.java, BinarySearchDeluxe.java, and Autocomplete.java posted below. I believe Term.java is correct, but where you see "//?" needs added code. I will also list before the code, the descriptions of said methods with "//?" to explain their purpose. DO NOT add more import packages or change the main methods as that is all that is needed and serve as guidance to what the class does.

BinarySearchDeluxe.java methods:

Comments regarding firstIndexOf():

Method: static int firstIndexOf(Key[] a, Key key, Comparator comparator)

Description: the index of the first key in a[] that equals search key, or -1 if no key exists

Comments regarding lastIndexOf():

Method: static int lastIndexOf(Key[] a, Key key, Comparator comparator)

Description: the index of the last key in a[] that equals search key, or -1 if no key exists

Autocomplete.java

Method: Autocomplete(Term[] terms) … Description: Initialize data structure from given array of terms

Method: Term[] allMatches(String prefix) … Description: All terms that start with given prefix, by descending order of weight

Method: int numberOfMatches(String prefix) … Description: number of terms that start with given prefix

Below is what I have so far:

---Term.java--- For reference to BinarySearchDeluxe and Autocomplete methods

//remember do not change import packages for any files, not necessary

import java.util.Arrays;
import java.util.Comparator;
public class Term implements Comparable<Term> {
  
private final String query;
private final long weight;
  
// constructor
public Term(String query)
{
if(query == null) // check if query is null
throw new NullPointerException();
this.query = query;
weight = 0; // assign weight to 0
}
  
// constructor
public Term(String query, long weight) {
if(query == null) // check if query is null
throw new NullPointerException();
else if(weight < 0) // check if weight is negative
throw new IllegalArgumentException();
this.query = query;
this.weight = weight;
}
// return comparator that compares the terms by weight in descending order
public static Comparator<Term> byReverseWeightOrder() {
return new ReverseWeightOrder();
}
  
// class that compares 2 terms by weight in descending order
private static class ReverseWeightOrder implements Comparator<Term> {
  
public int compare(Term v, Term w) {
if(v.weight > w.weight)
return -1;
else if(v.weight < w.weight)
return 1;
else
return 0;
}
}
  
// return comparator that compares the query string in lexicographic order using only the first r characters
public static Comparator<Term> byPrefixOrder(int r) {
if(r < 0) // check that r >= 0
throw new IllegalArgumentException();
return new PrefixOrder(r);
}
  
// class that compares 2 terms by query using the first r characters in lexicographic order
private static class PrefixOrder implements Comparator<Term> {
  
private int r;
  
PrefixOrder(int r) {
this.r = r;
}
  
public int compare(Term v, Term w) {
return(v.query.substring(0,r).compareTo(w.query.substring(0,r)));
}
}
// return comparator that compares the query string in lexicographic order
public int compareTo(Term that) {
return(query.compareTo(that.query));
}
  
// return string representation of Term
public String toString() {
return weight + "\t" + query;
}
  
public static void main(String[] args) {
  
String filename = args[0];
int k = Integer.parseInt(args[1]);
In in = new In(filename);
int N = in.readInt();
Term[] terms = new Term[N];
for (int i = 0; i < N; i++) {
long weight = in.readLong();
in.readChar();
String query = in.readLine();
terms[i] = new Term(query.trim(), weight);
}
System.out.printf("Top %d by lexicographic order:\n", k);
Arrays.sort(terms);
for (int i = 0; i < k; i++) {
System.out.println(terms[i]);
}
System.out.printf("Top %d by reverse-weight order:\n", k);
Arrays.sort(terms, Term.byReverseWeightOrder());
for (int i = 0; i < k; i++) {
System.out.println(terms[i]);
}
}
}

---BinarySearchDeluxe.java---

import java.util.Arrays;
import java.util.Comparator;

// Implements binary search for clients that may want to know the index of
// either the first or last key in a (sorted) collection of keys.
public class BinarySearchDeluxe {
// The index of the first key in a[] that equals the search key,
// or -1 if no such key.
public static <Key> int firstIndexOf(Key[] a, Key key,
Comparator<Key> comparator) {
//? <-- Symbol for needs code
}

// The index of the last key in a[] that equals the search key,
// or -1 if no such key.
public static <Key> int lastIndexOf(Key[] a, Key key,
Comparator<Key> comparator) {
//?
}

// Test client. no changes needed
public static void main(String[] args) {
String filename = args[0];
String prefix = args[1];
In in = new In(filename);
int N = in.readInt();
Term[] terms = new Term[N];
for (int i = 0; i < N; i++) {
long weight = in.readLong();
in.readChar();
String query = in.readLine();
terms[i] = new Term(query.trim(), weight);
}
Arrays.sort(terms);
Term term = new Term(prefix);
Comparator<Term> prefixOrder = Term.byPrefixOrder(prefix.length());
int i = BinarySearchDeluxe.firstIndexOf(terms, term, prefixOrder);
int j = BinarySearchDeluxe.lastIndexOf(terms, term, prefixOrder);
int count = i == -1 && j == -1 ? 0 : j - i + 1;
System.out.println(count);
}
}

---Autocomplete.java---

import java.util.Arrays;
import java.util.Comparator;

// A data type that provides autocomplete functionality for a given set of
// string and weights, using Term and BinarySearchDeluxe.
public class Autocomplete {
private Term[] terms;

// Initialize the data structure from the given array of terms.
public Autocomplete(Term[] terms) {
//?
}

// All terms that start with the given prefix, in descending order of
// weight.
public Term[] allMatches(String prefix) {
//?
}

// The number of terms that start with the given prefix.
public int numberOfMatches(String prefix) {
//?
}

// no changes needed
public static void main(String[] args) throws IOException{
String filename = args[0];
In in = new In(filename);
int N = in.readInt();
Term[] terms = new Term[N];
for (int i = 0; i < N; i++) {
long weight = in.readLong();
in.readChar();
String query = in.readLine();
terms[i] = new Term(query.trim(), weight);
}
int k = Integer.parseInt(args[1]);
Autocomplete autocomplete = new Autocomplete(terms);
while (StdIn.hasNextLine()) {
String prefix = StdIn.readLine();
Term[] results = autocomplete.allMatches(prefix);
for (int i = 0; i < Math.min(k, results.length); i++) {
System.out.println(results[i]);
}
}
}
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

// Term.java

import java.util.Arrays;
import java.util.Comparator;

public class Term implements Comparable<Term> {
  
   private final String query;
   private final long weight;
  
   // constructor
   public Term(String query)
   {
       if(query == null) // check if query is null
           throw new NullPointerException();
      
       this.query = query;
       weight = 0;   // assign weight to 0
   }
  
   // constructor
   public Term(String query, long weight) {
       if(query == null) // check if query is null
           throw new NullPointerException();
       else if(weight < 0) // check if weight is negative
           throw new IllegalArgumentException();
       this.query = query;
       this.weight = weight;  
   }

   // return comparator that compares the terms by weight in descending order
   public static Comparator<Term> byReverseWeightOrder() {
       return new ReverseWeightOrder();
   }
  
   // class that compares 2 terms by weight in descending order
   private static class ReverseWeightOrder implements Comparator<Term> {
  
       public int compare(Term v, Term w) {
           if(v.weight > w.weight)
               return -1;
           else if(v.weight < w.weight)
               return 1;
           else
               return 0;
       }  
   }
  
   // return comparator that compares the query string in lexicographic order using only the first r characters
   public static Comparator<Term> byPrefixOrder(int r) {
       if(r < 0) // check that r >= 0
           throw new IllegalArgumentException();
       return new PrefixOrder(r);
   }
  
   // class that compares 2 terms by query using the first r characters in lexicographic order
   private static class PrefixOrder implements Comparator<Term> {
      
       private int r;
      
       PrefixOrder(int r) {
           this.r = r;
       }
      
       public int compare(Term v, Term w) {
           return(v.query.substring(0,r).compareTo(w.query.substring(0,r)));
       }
   }

   // return comparator that compares the query string in lexicographic order
   public int compareTo(Term that) {
       return(query.compareTo(that.query));
   }
  
   // return string representation of Term
   public String toString() {
       return weight + "\t" + query;
   }
  
   public static void main(String[] args) {
      
      
       String fname = args[0];
       int c = Integer.parseInt(args[1]);
       In in = new In(fname);
       int N = in.readInt();
       Term[] terms = new Term[N];
       for (int i = 0; i < N; i++) {
       long weight = in.readLong();
       in.readChar();
       String query = in.readLine();
       terms[i] = new Term(query.trim(), weight);
       }
       System.out.printf("Top %d by lexicographic order:\n", c);
       Arrays.sort(terms);
       for (int i = 0; i < c; i++) {
       System.out.println(terms[i]);
       }
       System.out.printf("Top %d by reverse-weight order:\n", c);
       Arrays.sort(terms, Term.byReverseWeightOrder());
       for (int i = 0; i < c; i++) {
       System.out.println(terms[i]);
       }
   }
}

//end of Term.java

// BinarySearchDeluxe.java

import java.util.Arrays;
import java.util.Comparator;

// Implements binary search for clients that may want to know the index of
// either the first or last key in a (sorted) collection of keys.

public class BinarySearchDeluxe {
  
   // The index of the first key in a[] that equals the search key,
   // or -1 if no such key.
   public static <Key> int firstIndexOf(Key[] a, Key key,
   Comparator<Key> comparator) {
      
       // loop over the array a
       for(int i=0;i<a.length;i++)
       {
           // if ith element of a = key using comparator, return i
           if(comparator.compare(a[i], key) == 0)
               return i;
       }
      
       return -1; // key not found
   }
  
   // The index of the last key in a[] that equals the search key,
   // or -1 if no such key.
   public static <Key> int lastIndexOf(Key[] a, Key key,
   Comparator<Key> comparator) {
       int index = -1;
       // loop over the array a
       for(int i=0;i<a.length;i++)
       {
           // if ith element of a = key using comparator, set index to i
           if(comparator.compare(a[i],key) == 0)
               index = i;
       }
      
       return index; // return index
   }

   // Test client. no changes needed
   public static void main(String[] args) {
      
      
       String filename = args[0];
       String prefix = args[1];
       In in = new In(filename);
       int N = in.readInt();
       Term[] terms = new Term[N];
       for (int i = 0; i < N; i++) {
           long weight = in.readLong();
           in.readChar();
           String query = in.readLine();
           terms[i] = new Term(query.trim(), weight);
       }
       Arrays.sort(terms);
       Term term = new Term(prefix);
       Comparator<Term> prefixOrder = Term.byPrefixOrder(prefix.length());
       int i = BinarySearchDeluxe.firstIndexOf(terms, term, prefixOrder);
       int j = BinarySearchDeluxe.lastIndexOf(terms, term, prefixOrder);
       int count = i == -1 && j == -1 ? 0 : j - i + 1;
       System.out.println(count);
      
   }

}

//end of BinarySearchDeluxe.java

// Autocomplete.java

import java.util.Arrays;
import java.util.Comparator;

// A data type that provides autocomplete functionality for a given set of
// string and weights, using Term and BinarySearchDeluxe.

public class Autocomplete {

   private Term[] terms;

   // Initialize the data structure from the given array of terms.
   public Autocomplete(Term[] terms) {
       this.terms = terms;
   }

   // All terms that start with the given prefix, in descending order of
   // weight.
   public Term[] allMatches(String prefix) {
      
       Arrays.sort(terms); // sort the terms in lexicographic order
       Term term = new Term(prefix);
       // create a prefix order comparator using prefix length as argument
       Comparator<Term> prefixOrder = Term.byPrefixOrder(prefix.length());
       int firstIndex = BinarySearchDeluxe.firstIndexOf(terms, term, prefixOrder); // get the index of first occurrence of prefix in terms
       if(firstIndex == -1) // if term is not found
           return null; // return null
       else
       {
           // if at least one occurrence of term is found
           // get the index of last occurrence of prefix in terms
           int lastIndex = BinarySearchDeluxe.lastIndexOf(terms, term, prefixOrder);
           int length = lastIndex - firstIndex + 1; // get the number of terms
          
           // create output array of length
           Term[] matching = new Term[length];
          
           // loop to populate matching from terms
           for(int i=firstIndex;i<=lastIndex;i++)
           {
               matching[i] = terms[i];
           }
           Arrays.sort(matching,Term.byReverseWeightOrder()); // sort the matching array in descending order of weight
           return matching; // return the array
       }
   }

   // The number of terms that start with the given prefix.
   public int numberOfMatches(String prefix) {
       Arrays.sort(terms); // sort the terms in lexicographic order
       Term term = new Term(prefix);
       // create a prefix order comparator using prefix length as argument
       Comparator<Term> prefixOrder = Term.byPrefixOrder(prefix.length());
       int firstIndex = BinarySearchDeluxe.firstIndexOf(terms, term, prefixOrder); // get the index of first occurrence of prefix in terms
      
       if(firstIndex == -1) // if term is not found
           return 0;
       else
       {
           // get the index of last occurrence of prefix in terms
           int lastIndex = BinarySearchDeluxe.lastIndexOf(terms, term, prefixOrder);
           int length = lastIndex - firstIndex + 1; // get the number of terms
          
           return length; // return the length
       }
   }
  
   // no changes needed
   public static void main(String[] args) throws IOException{
      
       String filename = args[0];
       In in = new In(filename);
       int N = in.readInt();
       Term[] terms = new Term[N];
       for (int i = 0; i < N; i++) {
           long weight = in.readLong();
           in.readChar();
           String query = in.readLine();
           terms[i] = new Term(query.trim(), weight);
       }
       int k = Integer.parseInt(args[1]);
       Autocomplete autocomplete = new Autocomplete(terms);
       while (StdIn.hasNextLine()) {
           String prefix = StdIn.readLine();
           Term[] results = autocomplete.allMatches(prefix);
           for (int i = 0; i < Math.min(k, results.length); i++) {
               System.out.println(results[i]);
           }
       }
   }
}

//end of Autocomplete.java

Add a comment
Know the answer?
Add Answer to:
Trying to make an autocomplete java program that given a prefix, find all strings in set...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • For Autocomplete.java, I am trying to implement a data type that provides autocomplete functionality for a...

    For Autocomplete.java, I am trying to implement a data type that provides autocomplete functionality for a given set of string and weights, using Term and BinarySearchDeluxe.. Should sort the terms in lexicographic order, use binary search to find the set of terms that start with given prefix, and sort matching terms in descending order by weight. Corner cases: Constructor and each method throws a java.lang.NullPointerException if argument is null. Constructor should make proportional N log N compares worst case scenario,...

  • Computer Science - Java Explain the code step by step (in detailed order). Also explain what...

    Computer Science - Java Explain the code step by step (in detailed order). Also explain what the program required. Thanks 7 import java.io.File; 8 import java.util.Scanner; 9 import java.util.Arrays; 10 import java.io.FileNotFoundException; 12 public class insertionSort 13 14 public static void insertionSort (double array]) 15 int n -array.length; for (int j-1; j < n; j++) 17 18 19 20 21 double key - array[j]; int i-_1 while ( (i > -1) && ( array [i] > key array [i+1] -...

  • Below I have my 3 files. I am trying to make a dog array that aggerates...

    Below I have my 3 files. I am trying to make a dog array that aggerates with the human array. I want the users to be able to name the dogs and display the dog array but it isn't working. //Main File import java.util.*; import java.util.Scanner; public class Main {    public static void main(String[] args)    {    System.out.print("There are 5 humans.\n");    array();       }    public static String[] array()    {       //Let the user...

  • Java: Return an array of booleans in a directed graph. Please complete the TODO section in...

    Java: Return an array of booleans in a directed graph. Please complete the TODO section in the mark(int s) function import algs13.Bag; import java.util.HashSet; // See instructions below public class MyDigraph { static class Node { private String key; private Bag<Node> adj; public Node (String key) { this.key = key; this.adj = new Bag<> (); } public String toString () { return key; } public void addEdgeTo (Node n) { adj.add (n); } public Bag<Node> adj () { return adj;...

  • FOR JAVA: Summary: Create a program that adds students to the class list (see below). The...

    FOR JAVA: Summary: Create a program that adds students to the class list (see below). The solution should be named Roster402_v2.java. Allow the user to control the number of students added to the roster. Ask if the user would like to see their new roster to confirm additions. If yes, then display contents of the file, if no, end the program. ------------------------------------------------------------------------------------- List of student names and IDs for class (this will be your separate text file): Jones, Jim,45 Hicks,...

  • Help! Not sure how to create this java program to run efficiently. Current code and assignment...

    Help! Not sure how to create this java program to run efficiently. Current code and assignment attached. Assignment :Write a class Movies.java that reads in a movie list file (movies.txt). The file must contain the following fields: name, genre, and time. Provide the user with the options to sort on each field. Allow the user to continue to sort the list until they enter the exit option. ---------------------------------------------------------- import java.util.*; import java.io.*; public class Movies { String movieTitle; String movieGenre;...

  • I've previously completed a Java assignment where I wrote a program that reads a given text...

    I've previously completed a Java assignment where I wrote a program that reads a given text file and creates an index that stores the line numbers for where individual words occur. I've been given a new assignment where I need to modify some of my old code. I need to replace the indexer in my Index class with a NavigableMap<String, Word> and update my Word class with NavigableSet<Integer> lines. The instantiated objects should be TreeMap() and TreeSet(). I have below...

  • Hello, How can I make the program print out "Invalid data!!" and nothing else if the...

    Hello, How can I make the program print out "Invalid data!!" and nothing else if the file has a grade that is not an A, B, C, D, E, or F or a percentage below zero? I need this done by tomorrow if possible please. The program should sort a file containing data about students like this for five columns: one for last name, one for first name, one for student ID, one for student grade percentage, one for student...

  • Java Programming Answer 60a, 60b, 60c, 60d. Show code & output. public class Employee { private...

    Java Programming Answer 60a, 60b, 60c, 60d. Show code & output. public class Employee { private int id; private String name; private int sal; public Employee(int id, String name, int sal) { super(); this.id = id; this.name = name; this.sal = sal; } public int getid) { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; public void setName(String name) { this.name = name; } public int get Sall) { return...

  • I need help running this code. import java.util.*; import java.io.*; public class wordcount2 {     public...

    I need help running this code. import java.util.*; import java.io.*; public class wordcount2 {     public static void main(String[] args) {         if (args.length !=1) {             System.out.println(                                "Usage: java wordcount2 fullfilename");             System.exit(1);         }                 String filename = args[0];               // Create a tree map to hold words as key and count as value         Map<String, Integer> treeMap = new TreeMap<String, Integer>();                 try {             @SuppressWarnings("resource")             Scanner input = new Scanner(new File(filename));...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT