Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Program Description:Spelling Checker We will create a spell checker program. Thi

ID: 3874884 • Letter: P

Question

Program Description:Spelling Checker We will create a spell checker program. This program will use this file as a dictionary to look up properly spelled words. When the program starts, you will open the dictionary file (name it "Dictionary.txt"). You will utilize a hash function you have created to hash the words into an externally-chained hash table you have created. The hash table will be of a size that you will determine. You will then open an input file named "testTextFile.txt." When the checking proceeds, you will extract a word from the file to be checked, hash it into the table, and determine if it exists. You will continue this process until you have checked all the words in the file. Each time you find a word that you cannot match in the dictionary, you will let the user know and you will attempt to generate a list of suggested words. You will generate the list by assembling similar words via three methods: 1.One letter missing. You assume that one letter has been left out of the word. You can assemble new words to check by adding letters a..z in each of the positions in the word from the start to the end of the word. 2.One letter added. You assume the word has an extra letter. You scan through the word deleting each of the letters in turn, and looking up the word formed by the remaining letters. 3.Two letters reversed. You swap letters in positions 0..1, 1..2, 2..3, ... , n-2..n-1, to form new words which you look up. Each time you find a legal word from any of the three methods, you add it to a list of suggestions, which you present to the user when you have finished this part of the process. If you cannot identify any suggestions, let the user know. question must be in programmed in C. must include all files not just one

Explanation / Answer

SpellingController.java


/**
* Handles the execution of the SpellingChecker thread.
*/
public class SpellingController {

    public static void main(String[] args){
        SpellingChecker sc = new SpellingChecker();
        sc.run();
    }
}

SpellingChecker.java


import java.io.File;
import java.io.FileNotFoundException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.List;
import java.util.Scanner;

public class SpellingChecker implements Runnable{

    /*Sets dynamic paths for spellchecker by retrieving users working directories*/
    String workingDir = System.getProperty("user.dir");//stores uses working director
    String DICT_FILENAME = "\src\dictionary.txt";
    String TEST_FILENAME = "\src\testTextFile.txt";
    String D_PATH = workingDir + DICT_FILENAME;
    String F_PATH = workingDir + TEST_FILENAME;

    public DictionaryTable DICT_MAP; //builds instance of Dictionary class as a HashTable
    char[] letters = "abcdefghijklmnopqrstuvwxyz".toCharArray();

    SpellingChecker(){
    /*Constructs SpellingChecker*/
        //System.out.println(D_PATH);
        DICT_MAP = new DictionaryTable();
        DICT_MAP.build(D_PATH);
    }

    @Override
    public void run() {
    /*Takes user input and prints suggestions*/
        Scanner kb = null;

        try {
            kb = new Scanner(new File(F_PATH));

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        String line;

        while(kb.hasNext()) {

            line = kb.next();
            if (line.equals("")) {
                break;
            }
            if (DICT_MAP.contains(line)) {
                System.out.println(" Spelling is correct for: " + line);
            } else {
                System.out.print(" Spelling for " + line + " is incorrect");
                System.out.println(suggestWords(line));
            }
        }
        //stats
        DICT_MAP.printStats();

    }

    private String suggestWords(String line) {
    /*Suggest words by integrating the swapCharacter */
        StringBuilder suggestWord = new StringBuilder();
        ArrayList<String> swapped = swapLetters(line);
        ArrayList<String> letterMissing = letterMissing(line);
        ArrayList<String> letterAdded = letterAdded(line);

        if(swapped.size() == 0) {
            return " no suggestions can be made. ";
        }
        suggestWord.append(" here are some suggestions: ");
        for(String l : swapped){
            suggestWord.append(" -" + l);
        }
        for(String l : letterMissing){
            suggestWord.append(" -" + l);
        }
        for(String l : letterAdded){
            suggestWord.append(" -" + l);
        }
        return suggestWord.toString();
    }
    public ArrayList<String> swapLetters(String line) {
    /*Uses foreach loop to swap first and last letters of lined passed in*/
        ArrayList<String> swappedWord = new ArrayList();
        for(char character : letters){ //iterates over character array to swap letters
            String firstLetter = character + line;
            String lastLetter = line + character;
            if(DICT_MAP.contains(firstLetter)){
                swappedWord.add(firstLetter);
            }
            if(DICT_MAP.contains(lastLetter)){
                swappedWord.add(lastLetter);
            }
        }
        return swappedWord;
    }
    public ArrayList<String> letterMissing(String line) {
        ArrayList<String> charToReturn = new ArrayList();
        int len = line.length() - 1;
        //try removing char from the front
        if (DICT_MAP.contains(line.substring(1))) {
            charToReturn.add(line.substring(1));
        }
        for (int i = 1; i < len; i++) {
            //try removing each char between (not including) the first and last
            String working = line.substring(0, i);
            working = working.concat(line.substring((i + 1), line.length()));
            if (DICT_MAP.contains(working)) {
                charToReturn.add(working);
            }
        }
        if (DICT_MAP.contains(line.substring(0, len))) {
            charToReturn.add(line.substring(0, len));
        }
        return charToReturn;
    }
    public ArrayList<String> letterAdded(String line) {
        ArrayList<String> charToReturn = new ArrayList();

        for (int i = 0; i < line.length() - 1; i++) {
            String working = line.substring(0, i);
            working = working + line.charAt(i + 1);
            working = working + line.charAt(i);
            working = working.concat(line.substring((i + 2)));
            if (DICT_MAP.contains(working)) {
                charToReturn.add(working);
            }
        }
        return charToReturn;
    }
}

DictionaryTable.java

import java.io.*;

public class DictionaryTable {

    public String workingDir = System.getProperty("user.dir");//stores uses working director

    public String DICT_FILENAME = "\src\Dictionary.txt";
    public String D_PATH = workingDir + DICT_FILENAME;
    public String REPORT_FILE = "\src\Report.txt";
    public String R_PATH = workingDir + REPORT_FILE;

    //loads buckets and LoadFactor
    private int initLoadFactor;
    final private Bucket[] array;

    public DictionaryTable() {
        try {
            initLoadFactor = (countLines(D_PATH) % 31); //sets load factor to the count of the dictionary % 31
        } catch (IOException e) {
            e.printStackTrace();
        }

        array = new Bucket[initLoadFactor];
        for (int i = 0; i < initLoadFactor; i++) {
            array[i] = new Bucket();
        }
    }
    protected int getTableLoad(){
    /*Returns initial table load*/
        return initLoadFactor;
    }
    private int hash(String key) {
    /*Hash function hashes key and forces the return of a positive integer*/
        return (key.hashCode() & 0x7fffffff) % initLoadFactor;
    }
    public static int countLines(String filename) throws IOException {
        InputStream is = new BufferedInputStream(new FileInputStream(filename));
        try {
            byte[] c = new byte[1024];
            int count = 0;
            int readChars = 0;
            boolean empty = true;
            while ((readChars = is.read(c)) != -1) {
                empty = false;
                for (int i = 0; i < readChars; ++i) {
                    if (c[i] == ' ') {
                        ++count;
                    }
                }
            }
            return (count == 0 && !empty) ? 1 : count;
        } finally {
            is.close();
        }
    }
    public void add(String key) {
    /*hashes key and puts into hash table*/
        array[hash(key)].put(key);
    }
    public boolean contains(String input) {
    /*Checks to see if input matches */
        input = input.toLowerCase();
        return array[hash(input)].get(input);
    }
    public void build(String file) {
    /*Builds filepath for DICTIONARY TABLE */
        try {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            String line;
            while ((line = reader.readLine()) != null) {
                add(line);
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

    }

    /*Statistics*/
    public void printStats(){
    /*Reads over hashtable to determine % of bucket usage*/

        double bucketFreq = avgChainLength();
        /*Print to table*/
        FileWriter fw = null;
        try {
            fw = new FileWriter(R_PATH);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
                fw.write(" --------------Load Factor-----------------------");
                fw.write(" LF: " + getTableLoad());
                fw.write(" --------------Bucket Usage----------------------");
                fw.write(" Total Number of Buckets: " + bucketSize());
                fw.write(" Usage % :" + bucketUsage() + "%");
                fw.write(" -----------------------------------------------");
                fw.write(" -------------Avg Chain Length------------------");
                fw.write(" " + bucketFreq);
            } catch (IOException e) {
                e.printStackTrace();
            }
        try {
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public double avgChainLength(){
    //returns the average length of the hashtable chains
       int buckSize = bucketSize();
       int[] bucketFreq = new int[bucketSize()];
       for(Bucket b : array){
           bucketFreq[b.hashCode() % buckSize]++;
       }
        int count = 0;
        for(int i : bucketFreq){
            if(i > 0) count++;
        }
        return (double) array.length / count;
    }
    public double bucketUsage(){
    //returns the percentage of the buckets used
        int buckSize = bucketSize();
        int[] bucketFreq = new int[buckSize];
        for(Bucket b : array){
            bucketFreq[b.hashCode() % buckSize]++;
        }
        int count = 0;
        for(int i : bucketFreq){
            if(i > 0) count++;
        }
        return (double) count / buckSize;
    }
    public int log2(int number){
    // returns log 2 of number
        if(number == 0)
            return 0;
        return 31 - Integer.numberOfLeadingZeros(number);
    }
    public int bucketSize(){
    //returns the size of the buckets by bitshifting
        int n = array.length;
        int bucketSize = 2 << log2(n);
        if(bucketSize * initLoadFactor <= n){
            bucketSize <<= 1;
        }
        return bucketSize;
    }

}

Bucket.java


class Bucket {

    public Node first;

    public boolean get(String key) {
    /*Iterates through bucket to find key*/
        Node current = first;
        while (current != null) {
            if (current.word.equals(key)) {
                return true;
            }
            current = current.next;
        }
        return false;
    }

    public void put(String key) {
    /*Puts a new node within the bucket containing a word*/
        for (Node curr = first; curr != null; curr = curr.next) {
            if (key.equals(curr.word)) {
                return;                     //search hit: return
            }
        }
        first = new Node(key, first); //search miss: add new node
    }
}

Node.java

class Node {

    String word;
    Node next;

    public Node(String key, Node next) {
    /*Node constructor*/
        this.word = key;
        this.next = next;
    }

}

testTextFile.txt

otc i ama at bein girlf oge your apple otc i ama at bein girlf oge your apple otc i ama at bein girlf oge your apple otc i ama at bein girlf oge your apple otc i ama at bein girlf oge your apple otc i ama at bein girlf oge your apple otc i ama at bein girlf oge your apple otc i ama at bein girlf oge your apple otc i ama at bein girlf oge your apple otc i ama at bein girlf oge your apple otc i ama at bein girlf oge your apple otc i ama at bein girlf oge your apple

dictionary.txt

A
a
Aachen
Aalborg
aardvark
Aarhus
Aaron
AB
Ab
abaci
aback
abacus
Abadan
abaft
abalone
abandon
abandoned
abandonedly
abandonment

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at drjack9650@gmail.com
Chat Now And Get Quote