Question

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, N is number of terms. allMatches() should make proportional to logN + MlogM compares worst case scenario, M is # of matching terms. numberOfMatches() should be proportional to log N compares worst case. Comments are given above methods that need more work, look for "//?" which denotes areas that need to be filled.

Additional comments regarding methods that need work:

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 for Autocomplete.java:

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


public class Autocomplete {
private Term[] terms;

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

//terms start with given prefix, descending weight
public Term[] allMatches(String prefix) {
   //?
}

//Total number of terms with given prefix
public int numberOfMatches(String prefix) {
   //?
}

public static void main(String[] args) throws IOException{
String fname = args[0];
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);
}
int c = 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(c, results.length); i++) {
System.out.println(results[i]);
}
}
}
}

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

import java.util.*;

import java.lang.*;

import java.util.Comparator;

public class Term implements Comparable<Term> {

  

public double weight;

public String query;

  

/*Initializes a term with the given query string and weight*/

public Term(String query, double w) {

//exception will be thrown if query word is null

if (query == null) {

throw new java.lang.NullPointerException();

}

//exception will be thrown if weight of the word is less than 0

if (w < 0) {

throw new java.lang.IllegalArgumentException();

}

this.weight = w; //Initialize weight

this.query = query; //Initialize query

}

  

/*Compares the two terms in descending order by weight*/

public static Comparator<Term> byReverseWeightOrder() {

return new Comparator<Term>() {

public int compare(Term x, Term y) {

if (x.weight > y.weight) {

return -1;

} else if (x.weight < y.weight) {

return 1;

} else {

return 0;

}

}

};

}

  

/*Compares the two terms in descending order but using only the first r characters

of each query.*/

public static Comparator<Term> byPrefixOrder(final int textLength) {

final int x = textLength;

return new Comparator<Term>() {

public int compare(Term term1, Term term2) {

String string1 = term1.query;

String string2 = term2.query;

  

  

//Find min length of either text input or the term

int minlength;

if (string1.length() < string2.length()) {

minlength = string1.length();

} else {

minlength = string2.length();

}

//Compare the substring of the larger string with the smaller string

//Returns -1 if the two strings lengths are equal, returns 1 else wise

if (minlength >= textLength) {

return string1.substring(0, x).compareToIgnoreCase(string2.substring(0, x));

} else if (string1.substring(0, minlength).compareToIgnoreCase(string2.substring(0, minlength)) == 0) {

if (string1.length() == minlength) {

return -1;

} else {

return 1;

}

} else {

return string1.substring(0, minlength).compareToIgnoreCase(string2.substring(0, minlength));

}

}

};

}

/*Compares the two terms in lexicographic order by query. */

public int compareTo(Term that) {

String x = this.query;

String y = that.query;

return x.compareToIgnoreCase(y); //Compares the two strings, ignoring the case

}

/*Returns a string representation of this term in the following format: the

weight, followed by a tab, followed by the query*/

public String toString() {

return Double.toString(this.weight) + "\t" + this.query;

}

public static void main(String[] args)

{

Term[] termArray = new Term[20];

for(int i = 0; i < 20; i++)

{

termArray[i] = new Term("Chegg"+i,i+(20*Math.random()));

}

  

for(int i = 0; i < 20; i++)

{

System.out.println(termArray[i]);

}

  

System.out.println();

  

Arrays.sort(termArray);

  

for(int i = 0; i < 20; i++)

{

System.out.println(termArray[i]);

}

  

System.out.println();

  

Arrays.sort(termArray, Term.byReverseWeightOrder());

  

for(int i = 0; i < 20; i++)

{

System.out.println(termArray[i]);

}

  

System.out.println();

  

Arrays.sort(termArray, Term.byPrefixOrder(2));

  

for(int i = 0; i < 20; i++)

{

System.out.println(termArray[i]);

}

}

}

Compile java prigram get output

Add a comment
Know the answer?
Add Answer to:
For Autocomplete.java, I am trying to implement a data type that provides autocomplete functionality for a...
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
  • 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...

  • 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...

  • I need help with the last method listed in the problem: Implement a class Grid that...

    I need help with the last method listed in the problem: Implement a class Grid that stores measurements in a rectangular grid. The grid has a given number of rows and columns, and a description string can be added for any grid location. Supply the following constructor and methods: public Grid(int numRows, int numColumns) public void add(int row, int column, String description) public String getDescription(int row, int column) public ArrayList getDescribedLocations() Here, Location is an inner class that encapsulates the...

  • This is my current output for my program. I am trying to get the output to...

    This is my current output for my program. I am trying to get the output to look like This is my program Student.java import java.awt.GridLayout; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import javax.swing.JFileChooser; public class Student extends javax.swing.JFrame {     BufferedWriter outWriter;     StudentA s[];     public Student() {         StudentGUI();            }     private void StudentGUI() {         jScrollPane3 = new javax.swing.JScrollPane();         inputFileChooser = new javax.swing.JButton();         outputFileChooser = new javax.swing.JButton();         sortFirtsName = new...

  • I must implement a class to calculate n-th row of Pascal's Triangle (in Java). I need...

    I must implement a class to calculate n-th row of Pascal's Triangle (in Java). I need to create a static method that takes an argument "n" and returns the n'th line of pascal's triangle. the main method, which will call the class, is already done and the class is set up. Please build this without modifying the main method and without modifying exactly what the static method returns. public class Main { public static void main(String[] args) { int n...

  • Trying to practice this assignment Argument list: the *yahoonews.txt Data file: yahoonews.txt Wr...

    Trying to practice this assignment Argument list: the *yahoonews.txt Data file: yahoonews.txt Write a program named WordCount.java, in this program, implement two static methods as specified below: public static int countWord(Sting word, String str) this method counts the number of occurrence of the word in the String (str) public static int countWord(String word, File file) This method counts the number of occurrence of the word in the file. Ignore case in the word. Possible punctuation and symbals in the file...

  • Please help me ONLY for the second method : public static int[] runningGroups(String[] inputFileNames) throws IOException....

    Please help me ONLY for the second method : public static int[] runningGroups(String[] inputFileNames) throws IOException. The second method has an "array of files as a parameter". and return int [ ]. Each element of the return array is the number of group that can get from the first method.    I got an error Exception in thread "main" java.lang.NullPointerException Here my code: import java.io.*; import java.util.ArrayList; import java.util.Scanner; public class RunningGroups { public static void main(String[] args) throws IOException...

  • I am trying to make a linked list queue and I am trying to use the...

    I am trying to make a linked list queue and I am trying to use the display method I made just to see if its working but when I run it nothing is displayed please help. Also the newPlane boolean was made just so I can randomly decide if the plane is going to join the queue or not. public class PlaneSimulation { public static void main(String[] args) { int landTime = 2; int takeoffTime = 3; int avgArrivalInterval =...

  • Exercise 1 Adjacency Matrix In this part, you will implement the data model to represent a graph. Implement the followi...

    Exercise 1 Adjacency Matrix In this part, you will implement the data model to represent a graph. Implement the following classes Node.java: This class represents a vertex in the graph. It has only a single instance variable of type int which is set in the constructor. Implement hashCode() and equals(..) methods which are both based on the number instance variable Node - int number +Node(int number); +int getNumberO; +int hashCode() +boolean equals(Object o) +String toString0) Edge.java: This class represents a...

  • I have almost done with this code to Implement Huffman Coding. However I have an error...

    I have almost done with this code to Implement Huffman Coding. However I have an error at the "Heap<Tree>". Could anyone help with solving this issue, really appreciated. Thank you!! import java.util.Scanner; public class HuffmanEncoding { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a text: "); String text = input.nextLine();    int[] counts = getCharacterFrequency(text); // Count frequency System.out.printf("%-15s%-15s%-15s%-15s\n", "ASCII Code", "Character", "Frequency", "Code");    Tree tree = getHuffmanTree(counts); // Create a Huffman tree String[]...

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