Question

In: Computer Science

In this problem, we will use our knowledge of maps and lists to build a spell-checking...

In this problem, we will use our knowledge of maps and lists to build a spell-checking program. The class Main contains the starter code for this problem; your task is to complete this program. You are provided with a file titled words.txt, which contains a list of valid English words, one per line. Your program should take as input a line of space-separated words representing a sentence. (No punctuation or capitalization will be used; all characters will be either the space character or a lowercase English letter). You should then output a list of words in the input that are misspelled, each on their own line, followed by a newline.

For example, if our input is:

teh qwick braown foxx jumpps ovar teh laizy dog

then we should print:

teh

qwick

braown

foxx

jumpps

ovar

teh

laizy

Restrictions:

(a) You may not use any of Java’s built-in data structures except for arrays. (In particular, you should write your own implementation of HashSet. I suggest calling this MyHashSet. Additionally, if you want to use lists to handle collisions, you will need to write your own implementation of a LinkedList or ArrayList.)

(b) Your algorithm should run in approximately O(m+n) time, where m is the total number of words in the file words.txt and n is the number of words in the input sentence.

(c) Violations of these restrictions will result in your receiving a zero for

this question

Hints :

(a) As a first step, I would recommend implementing your own ver-

sion of hash sets, called “MyHashSet”. I would suggest using the

MyLinkedList class from the last assignment as an example.

i. Your hash set should support an “add” method, which takes in

a string and puts it in the set.

ii. Your hash set should support a “contains” method, which takes

in a string and returns true if it’s in the set, and false otherwise.

iii. Your hash set should contain an array for holding the underlying

data.

iv. Your hash set should include a hash function. I suggest research-

ing one on the Internet and using that.

v. Your hash set should handle collisions somehow. I suggest using

a linked list.

(b) As a second step, you should iterate through the lines in

words.txt, and put each one in an instance of your hash set. Code for reading from the file has been provided; your job is to put each word in your

hash set.

(c) As a third step, you should iterate through the input words, check if

each one is in the set, and print it if it is not (i.e. it is not in the set

of real English words).

//Starter code

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
  
// Step 1: load our txt file of English words.
try {
BufferedReader rd = new BufferedReader(new FileReader("words.txt"));
  
String currentLine = null;
while ((currentLine = rd.readLine()) != null) {
// TODO do something with the words we're reading
}
} catch (IOException e) {
System.out.println("Exception loading words.txt.");
}
  
// Step 2: read the sentence given into an array of strings
String[] sentenceWords;
String input = sc.nextLine();
if (input.equals("")) {
sentenceWords = new String[0];
} else {
sentenceWords = input.split(" ");
}
  
// Step 3: print all misspelled words
// TODO implement this using your own version of a HashSet.
}
}

Solutions

Expert Solution

// MyHashSet Implementation:

public class MyHashSet {

    private static class Entry {
        Object key;
        Entry next;
    }

    private Entry[] buckets;

    // size of the MyHashSet
    private int size;

    public MyHashSet(int capacity) {

        // each value is null initially, ie bucket[index] is null for all 0 < index < capacity
        buckets = new Entry[capacity];
        size = 0;
    }

    /**
     * Determines the index of buckets array where this hashCode will be mapped
     */
    private int hashFunction(int hashCode) {

        int index = hashCode;
        if (index < 0) {
            index = -index;
        }
        return index % buckets.length;
    }

    // Adds the specified element to this set if it is not already present
    public boolean add(String element) {

        int index = hashFunction(element.hashCode());
        Entry current = buckets[index];

        // Iterate to list to find if an entry already exists for this value of hashCode
        while (current != null) {
            // element is already in set
            if (current.key.equals(element)) {
                return false;
            }
            // otherwise visit next entry in the bucket
            current = current.next;
        }

        // no element found with that hashCode so add new entry
        Entry entry = new Entry();
        entry.key = element;
        // current Entry is null if bucket is empty
        // if it is not null it becomes next Entry
        entry.next = buckets[index];
        buckets[index] = entry;

        // increment size of MyHashSet
        size++;
        return true;
    }

    // Returns true if this set contains the specified element
    public boolean contains(String element) {

        int index = hashFunction(element.hashCode());
        Entry current = buckets[index];

        while (current != null) {
            // check if node contains element
            if (current.key.equals(element)) {
                return true;
            }
            // otherwise visit next node in the bucket
            current = current.next;
        }

        // no element found
        return false;
    }

    // Returns the number of elements in this set
    int size() {
        return size;
    }
}

// Main program:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        MyHashSet myHashSet = new MyHashSet(1000);
        Scanner sc = new Scanner(System.in);

        // Step 1: load our txt file of English words.
        try {
            BufferedReader rd = new BufferedReader(new FileReader("words.txt"));
            String currentLine = null;
            while ((currentLine = rd.readLine()) != null) {
            myHashSet.add(currentLine);
            }
        } catch (IOException e) {
            System.out.println("Exception loading words.txt. " + e);
        }

        // Step 2: read the sentence given into an array of strings
        String[] sentenceWords;
        String input = sc.nextLine();
        if (input.equals("")) {
            sentenceWords = new String[0];
        } else {
            sentenceWords = input.split(" ");
        }

        // Step 3: print all misspelled words
        for (String word : sentenceWords) {
            if (!myHashSet.contains(word)) {
                System.out.println(word);
            }
        }
    }
}

Related Solutions

We can use our knowledge of air resistance to calculate its effect on a baseball in...
We can use our knowledge of air resistance to calculate its effect on a baseball in 2-dimensional projectile motion. The effect of air resistance can be modeled with an extra acceleration term, so that the acceleration is no longer simply ⃗a = ⃗g but rather ⃗a = ⃗g − bv⃗v We will use b = 0.002 m^(−1), a reasonable value for a baseball flying through the air. Let the initial velocity of the ball be 35 m/s at an angle...
In this exercise, we will use our knowledge of the relationships between revenue, variable costs, fixed...
In this exercise, we will use our knowledge of the relationships between revenue, variable costs, fixed costs, contribution margin, operating margin, and unit charge or sales price. We will calculate the number of UOS we need to perform to break even, what the revenue needed to achieve a target operating income, and compute the contribution income statement to prove our results. Please use the Contribution Margin Method to arrive at your answers and show all your calculations for the answer...
use logism: For each of the following functions, simplify using Karnaugh Maps, then build, and hand...
use logism: For each of the following functions, simplify using Karnaugh Maps, then build, and hand in a properlydocumented circuit. You need to submit both a K-Map as well as the circuit for each part. a) F1 (a,b,c,d) = Σ(1, 2, 3, 4, 5, 9,10,11) b) F2 (a,b,c,d) = Σ(2, 3, 4, 6, 8, 11, 15) δ(a,b,c,d) = Σ(0, 5, 7, 9, 10)
How do we use our knowledge of edge effects to plan the reserves? What information do...
How do we use our knowledge of edge effects to plan the reserves? What information do you need?
# = 8 Suppose next that we have even less knowledge of our patient, and we...
# = 8 Suppose next that we have even less knowledge of our patient, and we are only given the accuracy of the blood test and prevalence of the disease in our population. We are told that the blood test is 9# percent reliable, this means that the test will yield an accurate positive result in 9#% of the cases where the disease is actually present. Gestational diabetes affects #+1 percent of the population in our patient’s age group, and...
2. Suppose next that we have even less knowledge of our patient, and we are only...
2. Suppose next that we have even less knowledge of our patient, and we are only given the accuracy of the blood test and prevalence of the disease in our population. We are told that the blood test is 96% percent reliable, this means that the test will yield an accurate positive result in 96% of the cases where the disease is actually present. Gestational diabetes affects 7 percent of the population in our patient’s age group, and that our...
2. Suppose next that we have even less knowledge of our patient, and we are only...
2. Suppose next that we have even less knowledge of our patient, and we are only given the accuracy of the blood test and prevalence of the disease in our population. We are told that the blood test is 93 percent reliable, this means that the test will yield an accurate positive result in 93% of the cases where the disease is actually present. Gestational diabetes affects 4 percent of the population in our patient’s age group, and that our...
Respond to the following in a minimum of 175 words: This second week we build our...
Respond to the following in a minimum of 175 words: This second week we build our understanding of ethical accounting by examining specific cases and effects that demonstrate the importance of fostering an ethical “culture” in a company and its various functions. strategic decision-making. In light of the accounting and budgeting systems we studied last week, consider how the costs involved in business performance and decision-making (Chapters 2 through 5 in our text) are tabulated, Discuss the importance of an...
This week we continue to build our understanding of ethical accounting practices by examining the intersection...
This week we continue to build our understanding of ethical accounting practices by examining the intersection of business and accounting practices by examining the ethical responsibilities of accountants when encountering company procedures affecting the accounting function, and its related responsibilities. Considering differing bases for accounting (cash, accrual) available, Discuss the legal rights, responsibilities, and liabilities involved when the accounting function is asked to take action(s) that may be inconsistent with the accounting basis that the company has traditionally used. Does...
We can remodel our existing building at a cost of $6.9 million, or build a new...
We can remodel our existing building at a cost of $6.9 million, or build a new building at a cost of $11 million. The old building, after it is refurbished, would not be as efficient as the new one, and energy costs would, therefore, be $750,000 a year higher. The maintenance cost for the old building would be $450,000 per year and $420,000 for the new building. The salvage value for the new building would be $3.25 million after its...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT