Question

**********Using Java***************

Create 5 CLASSES: Driver(main), Word, AnagramFamily, and 2 Comparators classes

words.txt is a very large file containing thousands of words. I will post some words down below.

DETAILS To better prepare you for assignments in more advanced courses, specific step-by-step, method headings class names, and the like have been omitted. What remains is a general description (you may need to read this several times to fully understand the requirements): form. The canonical form stores a word with its letters in alphabetical order, e.g. bob would be bbo, cat would be act, program would be agmoprr, and so on. The class Word constructor has the responsibility of storing which is stored in the canonical form field (you should call a separate method for this conversion purpose) Once all the words from the input file have been properly stored in a LinkedList of Word, you should use Collections to sort this list ascending alphabetically based on the canonical words by making the Word class Using an Iterator on the LinkedList of Word, create a 2ng list (new LinkedList) consisting of objects of a new class named AnagramFamily. AnagramFamily should contain at least 2 fields; 1 to hold a list of Word words that are all anagrams of each other (these should all be grouped together in the original canonical sorted list) and the 2nd field to store an integer value of how many items are in the current list. (Keep in mind, because the original list contains both the normal and canonical forms, as the AnagramFamily List will also have, a family of anagrams will all have the same canonical form with different normal forms stored in the normalForm field of the Word class). Each AnagramFamily List of Word should be sorted Descending by normal form using a Comparator of Word (if you insert Word(s) into a family one at a time, this presents an issue on how to get this ist sorted as each Word insertion will require a new sort to be performed to guarantee the list is always sorted. For this reason it is best to form a list, sort it, and then create an AnagramFamily by passing the sorted list to it). Sort the AnagramFamily LinkedList in descending order based on family size by use of a Comparator to be passed to the Collections sort method. Next, output the top five largest families then, all families of length 8, and lastly, the very last family stored in the list to a file named out6.txt. Be sure to format the output to be very clear and meaningful

some of word.txt

aa
aah
aahed
aahing
aahs
aal
aalii
aaliis
aals
aardvark
aardvarks
aardwolf
aardwolves
aargh
aarrgh
aarrghh
aas
aasvogel
aasvogels
ab
aba
abaca
abacas
abaci
aback
abacterial
abacus
abacuses
abaft
abaka
abakas
abalone
abalones
abamp
abampere
abamperes
abamps
abandon
abandoned
abandoner
abandoners
abandoning
abandonment
abandonments
abandons
abapical
abas
abase
abased
abasedly
abasement
abasements
abaser
abasers
abases
abash
abashed
abashes
abashing
abashment
abashments
abasia
abasias
abasing
abatable
abate
abated
abatement
abatements
abater
abaters
abates
abating
abatis
abatises
abator
abators
abattis
abattises
abattoir
abattoirs
abaxial
abaxile
abba
abbacies
abbacy
abbas
abbatial
abbe
abbes
abbess
abbesses
abbey
abbeys
abbot
abbotcies
abbotcy
abbots
abbreviate
abbreviated
abbreviates

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

Hi,

Please find the classes that you have mentioned me to create.

AnagramFamily.java:

import java.util.Collections;

import java.util.LinkedList;

import java.util.List;

import java.util.ListIterator;

public class AnagramFamily {

private LinkedList<Word> myWords;

private int myCount;

/**

* this constructor accepts a list containing a sorted anagram family, adds the

* elements of that list to the myWords feild, sorts myWords, and calculates the

* number of words in the list

*

* @param theFamily

* (list of words)

*

**/

public AnagramFamily(List<Word> theFamily) {

myCount = 0;

myWords = new LinkedList<Word>();

// theFamily iterator

ListIterator<Word> iterator = theFamily.listIterator();

while (iterator.hasNext()) {

myWords.add(iterator.next());

myCount++;

}

// sort words by original form

// descending alphabetically

Collections.sort(myWords, new CompareByOriginal());

}

/**

* getMyCount() returns this objects # of words.

*

* @return myCount (# of words)

**/

public int getMyCount() {

return myCount;

}

/**

* toString returns the string representation of a list with all of myWords

* original word forms to identify its containing word objects.

*

* @return myWords.toString()

*

**/

public String toString() {

return myWords.toString();

}

}

CompareAnagramSize.java:

import java.util.Comparator;

public class CompareAnagramSize implements Comparator<AnagramFamily> {

/**

* this comparator compares two anagram families, families with more objects

* considered ahead.

*

* @param theThis

* (original family)

* @param theOther

* (family being considered)

* @return theOther.getMyCount() - theThis.getMyCount()

*

**/

public int compare(AnagramFamily theThis, AnagramFamily theOther) {

return theOther.getMyCount() - theThis.getMyCount();

}

}

CompareByOriginal.java:

import java.util.Comparator;

public class CompareByOriginal implements Comparator<Word> {

/**

* compare is a comparator which compares word objects alphabetically descending

*

* @param theFirst

* (word being compared to)

* @param theSecond

* (word being compared)

* @return theSecond.getMyWord().compareTo( theFirst.getMyWord())

*

*/

public int compare(Word theFirst, Word theSecond) {

return theSecond.getMyWord().compareTo(theFirst.getMyWord());

}

}

ProgramNineDriver.java:

import java.io.File;

import java.io.FileNotFoundException;

import java.io.PrintStream;

import java.util.Collections;

import java.util.LinkedList;

import java.util.ListIterator;

import java.util.Scanner;

public class ProgramNineDriver {

/**

* main is the driver program to test word and AnagramFamily objects from

* words.txt.

*

* @param theArgs[]

* (command line input)

*

**/

public static void main(String theArgs[]) {

Scanner input = null;

PrintStream output = null;

boolean fileOk = false;

try {

input = new Scanner(new File("C:\\Users\\baba\\HomeworkLib\\eclipse-workspace\\Chegg\\images\\words.txt"));

output = new PrintStream(new File("C:\\Users\\baba\\HomeworkLib\\eclipse-workspace\\Chegg\\images\\out9.txt"));

fileOk = true;

} catch (FileNotFoundException e) {

System.out.println("Cannot open file " + e);

}

// body of program if file is read

if (fileOk) {

LinkedList<Word> words = new LinkedList<Word>();

// iterator creates and adds word objects to words

while (input.hasNext()) {

words.add(new Word(input.next()));

}

// sorts words alphabetically canotically

Collections.sort(words);

// this LinkedList stores the content of

// unique AnagramFamilies for construction

LinkedList<Word> aFamily = new LinkedList<Word>();

// this LinkedList stores anagram families

LinkedList<AnagramFamily> families = new LinkedList<AnagramFamily>();

// iterator for traversing words

ListIterator<Word> iterator = words.listIterator();

// uses recursive calls to getFamily to get families

while (iterator.hasNext()) {

Word test = iterator.next();

aFamily.add(test);

// recursive end runs until end of family

if (iterator.hasNext()) {

getFamily(aFamily, iterator, test);

}

// sort this family on original word

// ascending alphabetically

Collections.sort(aFamily, new CompareByOriginal());

// adds current AnagramFamily to our list

families.add(new AnagramFamily(aFamily));

// primes aFamily for next family

aFamily.clear();

}

// sorts our AnagramFamilys

// based on family size descending

Collections.sort(families, new CompareAnagramSize());

// the rest of main handles program output

output.println("5 LARGEST FAMILIES");

for (int i = 0; i < 5; i++) {

output.println(families.get(i));

}

output.println();

output.println("FAMILIES OF LENGTH 8");

for (AnagramFamily f : families) {

if (f.getMyCount() == 8) {

output.println(f);

}

}

input.close();

output.close();

}

}

/**

* getFamily is a recursive method which continues down a list of Word objects

* untill the next word object is not the same as the current object based on

* its canotical form and adds all similar objects to a result LinkedList.

*

* @param theFamily

* (list of similar words)

* @param theIterator

* (word list iterator)

* @param thePrevious

* (last word in the list)

*

**/

public static void getFamily(LinkedList<Word> theFamily, ListIterator<Word> theIterator, Word thePrevious) {

// sets the test to the next word

Word test = theIterator.next();

// if test == previous, recall method with

// test passed to thePrevious

if (thePrevious.compareTo(test) == 0) {

theFamily.add(test);

if (theIterator.hasNext()) {

getFamily(theFamily, theIterator, test);

}

}

// BASE CASE: if the next item != previous

else {

// step back in iterator so next item

// is the first new canotical form

theIterator.previous();

}

}

}

Word.java:

import java.util.Arrays;

public class Word implements Comparable<Word> {

// Original word field

private String myWord;

// field for myWord's canonical form

private String myCat;

/**

* this constructor assigns myWord and calls makeCat to create myCat

*

* @param theWord

* (original word)

*

**/

public Word(String theWord) {

myWord = theWord;

// charlist of word for sorting

char[] wordChars = theWord.toCharArray();

makeCat(wordChars);

// assign myCat to new sorted char string

myCat = new String(wordChars);

}

/**

* this method will find the canotical form of the passed arraylist of char. It

* operates using the mergesort algorithm by recursively splitting the array in

* half then sorting those halfs into a resulting array.

*

* @param chars

* (char list of word characters)

*

**/

private final void makeCat(char[] chars) {

// BASE CASE: if length =< 1

if (chars.length > 1) {

char[] left = Arrays.copyOfRange(chars, 0, chars.length / 2);

char[] right = Arrays.copyOfRange(chars, chars.length / 2, chars.length);

// recursively call makeCat

makeCat(left);

makeCat(right);

// merge the two halves together

merge(chars, left, right);

}

}

/**

* this method handles merging the two halves of the char array from makeCat

* into sorted order.

*

* @param result

* (final char array)

* @param theLeft

* (first half of array)

* @param theRight

* (second half of array)

*

**/

private final void merge(char[] result, char[] theLeft, char[] theRight) {

int i1 = 0; // left array index

int i2 = 0; // right array index

for (int i = 0; i < result.length; i++) {

if (i2 >= theRight.length || (i1 < theLeft.length && theLeft[i1] <= theRight[i2])) {

result[i] = theLeft[i1]; // take from left

i1++;

} else {

result[i] = theRight[i2];

i2++;

}

}

}

/**

* this accessor method retrieves myWord.

*

* @return myWord (word objects word feild)

*

**/

public String getMyWord() {

return myWord;

}

/**

* getMyCat retrieves canatical form.

*

* @return myCat (canotical form feild)

*

**/

public String getMyCat() {

return myCat;

}

/**

* compareTo method compares this objects canotical form to the others canotical

* form ascending alphabetically

*

* @param theOther

* (word to compare to

* @return myCat.compareTo(theOther.getMyCat())

*

**/

public int compareTo(Word theOther) {

return myCat.compareTo(theOther.getMyCat());

}

/**

* toString simply returns the word objects original word feild.

*

* @return myWord (the word feild)

*

**/

public String toString() {

return myWord;

}

}

As per the words list provided by you the output for them is as follows:

Output:

5 LARGEST FAMILIES
[aa]
[abatable]
[abbatial]
[abaca]
[abacterial]

FAMILIES OF LENGTH 8

Add a comment
Know the answer?
Add Answer to:
**********Using Java*************** Create 5 CLASSES: Driver(main), Word, AnagramFamily, and 2 Comparators classes words.txt is a very...
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
  • Programming Assignment 9 The purpose of this programming project is to demonstrate a significant culmination of...

    Programming Assignment 9 The purpose of this programming project is to demonstrate a significant culmination of most constructs learned thus far in the course. This includes Lists, Classes, accessors, mutators, constructors, implementation of Comparable, Comparator, use of Collections sort, iterators, properly accessing fields of complex objects, and fundamental File I/O. BACKGROUND Look over Programming Project #4 at the end of the Searching & Sorting Chapter (13), page 869. Programming Assignment 9 is similar with some added features as described below....

  • java Create the following classes: DatabaseType: an interface that contains one method 1. Comparator getComparatorByTrait(String trait)...

    java Create the following classes: DatabaseType: an interface that contains one method 1. Comparator getComparatorByTrait(String trait) where Comparator is an interface in java.util. Database: a class that limits the types it can store to DatabaseTypes. The database will store the data in nodes, just like a linked list. The database will also let the user create an index for the database. An index is a sorted array (or in our case, a sorted ArrayList) of the data so that searches...

  • ONLY NEED THE DRIVER CLASS PLEASE!!! Domain & Comparator Classes: 0.) Design a hierarchy of classes,...

    ONLY NEED THE DRIVER CLASS PLEASE!!! Domain & Comparator Classes: 0.) Design a hierarchy of classes, where the Media superclass has the artistName and the mediaName as the common attributes. Create a subclass called CDMedia that has the additional arrayList of String objects containing the songs per album. Create another subclass called DVDMedia that has the additional year the movie came out, and an arrayList of co-stars for the movie. 1.) The superclass Media will implement Comparable, and will define...

  • PLEASE HELP IN JAVA: This is an exercise in using the java LinkedList class. Using input...

    PLEASE HELP IN JAVA: This is an exercise in using the java LinkedList class. Using input file words.txt , create a LinkedList BUT you must NOT add a word that is already in the list and you MUST add them in the order received to the end of the list. For example, if your input was cat, cat, dog, mouse, dog, horse your list would now contain cat, dog, mouse, horse. And the head of the list would be cat,...

  • FOR JAVA: Summary: Create a program that stores info on textbooks. The solution should be named...

    FOR JAVA: Summary: Create a program that stores info on textbooks. The solution should be named TextBookSort.java. Include these steps: Create a class titled TextBook that contains fields for the author, title, page count, ISBN, and price. This TextBook class will also provide setter and getter methods for all fields. Save this class in a file titled TextBook.java. Create a class titled TextBookSort with an array that holds 5 instances of the TextBook class, filled without prompting the user for...

  • Question 2: Finding the best Scrabble word with Recursion using java Scrabble is a game in...

    Question 2: Finding the best Scrabble word with Recursion using java Scrabble is a game in which players construct words from random letters, building on words already played. Each letter has an associated point value and the aim is to collect more points than your opponent. Please see https: //en.wikipedia.org/wiki/Scrabble for an overview if you are unfamiliar with the game. You will write a program that allows a user to enter 7 letters (representing the letter tiles they hold), plus...

  • Please try to write the code with Project 1,2 and 3 in mind. And use java language, thank you very much. Create an Edit Menu in your GUI Add a second menu to the GUI called Edit which will have one me...

    Please try to write the code with Project 1,2 and 3 in mind. And use java language, thank you very much. Create an Edit Menu in your GUI Add a second menu to the GUI called Edit which will have one menu item called Search. Clicking on search should prompt the user using a JOptionPane input dialog to enter a car make. The GUI should then display only cars of that make. You will need to write a second menu...

  • Using C++ Skills Required Create and use classes Exception Handling, Read and write files, work vectors....

    Using C++ Skills Required Create and use classes Exception Handling, Read and write files, work vectors. Create Functions, include headers and other files, Loops(while, for), conditional(if, switch), datatypes,  etc. Assignment You work at the computer science library, and your boss just bought a bunch of new books for the library! All of the new books need to be cataloged and sorted back on the shelf. You don’t need to keep track of which customer has the book or not, just whether...

  • CSC110 Lab 6 (ALL CODING IN JAVA) Problem: A text file contains a paragraph. You are to read the contents of the file, store the UNIQUEwords and count the occurrences of each unique word. When the fil...

    CSC110 Lab 6 (ALL CODING IN JAVA) Problem: A text file contains a paragraph. You are to read the contents of the file, store the UNIQUEwords and count the occurrences of each unique word. When the file is completely read, write the words and the number of occurrences to a text file. The output should be the words in ALPHABETICAL order along with the number of times they occur and the number of syllables. Then write the following statistics to...

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

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