Question

In: Computer Science

Hey guys so ive been working on these Radix for quite sometime but I keep hitting...

Hey guys so ive been working on these Radix for quite sometime but I keep hitting roadblocks on my todos. Ive implement the first TODO but I cant get the stringRadixSort to work properly as well nor the ChainOfNodes mergeTwoChainsIntoThird() function. Please feel free to rewrite anything you see wrong with it. Ive also provided the Lab Description down below as well for what the output should be and what to do. Thanks again for your guys help! 

1) Implement a radix sort of String objects in a chain of linked nodes, where strings consist only of upper-case characters. This sort will need 27 buckets: 26 for letters A to Z and one bucket for a space.  Each bucket holds a ChainOfNodes object, which will hold appropriate Strings during the sorting. 

2) The ChainOfNodes is a private class inside the SortChain class, its add method adds new elements to the end on the chain.

3) SortChain constructor is already defined and it calls a private method generateList that randomly generates the given number of String objects with number of characters no longer than the given maxStringLength and adds them to the given list. Utilize StringBuffer to build each String.

4) You will create two lists: this.linkedDataOne and this.linkedDataTwo. Each list will be sorted with the stringRadixSort method which you need to implement following the radix sort algorithm.

5) Finally, you will create a third list with mergeTwoChainsIntoThird method. The new list will contain the same data the this.linkedDataOne and this.linkedDataTwo contain. The new list will also be sorted in the ascending order and the original list will remain unchanged. 

See sample runs (with seed 101):
RUN #1
How many nodes in the first chain?
 It should be an integer value greater than or equal to 0.
5
How many characters in the longest string in the first chain?
 It should be an integer value greater than or equal to 1.
6

How many nodes in the second chain?
 It should be an integer value greater than or equal to 0.
7
How many characters in the longest string in the second chain?
 It should be an integer value greater than or equal to 1.
3

The original listOne is: 
CLYUD RWUMOX OVW A CEZ 
The are 5 elements in the list
  The longest string has 6 characters, so the number of needed passes is 6
The original listOne sorted with RadixSort: 
A CEZ CLYUD OVW RWUMOX 
The are 5 elements in the list


The original listTwo is: 
AY NCQ UBT D TF A UAR 
The are 7 elements in the list
  The longest string has 3 characters, so the number of needed passes is 3
The original listTwo sorted with RadixSort: 
A AY D NCQ TF UAR UBT 
The are 7 elements in the list

The mergeChain is:
A A AY CEZ CLYUD D NCQ OVW RWUMOX TF UAR UBT 
The are 12 elements in the list
The listOne sorted should be unchanged: 
A CEZ CLYUD OVW RWUMOX 
The are 5 elements in the list
The listTwo sorted should be unchanged: 
A AY D NCQ TF UAR UBT 
The are 7 elements in the list

Process finished with exit code 0


RUN #2
How many nodes in the first chain?
 It should be an integer value greater than or equal to 0.
0
How many characters in the longest string in the first chain?
 It should be an integer value greater than or equal to 1.
5

How many nodes in the second chain?
 It should be an integer value greater than or equal to 0.
5
How many characters in the longest string in the second chain?
 It should be an integer value greater than or equal to 1.
3

The original listOne is: 
The list is empty
The original listOne sorted with RadixSort: 
The list is empty


The original listTwo is: 
CL UD RWU O S 
The are 5 elements in the list
  The longest string has 3 characters, so the number of needed passes is 3
The original listTwo sorted with RadixSort: 
CL O RWU S UD 
The are 5 elements in the list

The mergeChain is:
CL O RWU S UD 
The are 5 elements in the list
The listOne sorted should be unchanged: 
The list is empty
The listTwo sorted should be unchanged: 
CL O RWU S UD 
The are 5 elements in the list

Process finished with exit code 0

RUN #3
How many nodes in the first chain?
 It should be an integer value greater than or equal to 0.
25
How many characters in the longest string in the first chain?
 It should be an integer value greater than or equal to 1.
4

How many nodes in the second chain?
 It should be an integer value greater than or equal to 0.
4
How many characters in the longest string in the second chain?
 It should be an integer value greater than or equal to 1.
25

The original listOne is: 
CLY D RWU OX OVWM MCE O Y NCQD BTQ WT GA UAR BNOZ KK H U JBAO DF DIN RYBA BMZG GFLU SJX X 
The are 25 elements in the list
  The longest string has 4 characters, so the number of needed passes is 4
The original listOne sorted with RadixSort: 
BMZG BNOZ BTQ CLY D DF DIN GA GFLU H JBAO KK MCE NCQD O OVWM OX RWU RYBA SJX U UAR WT X Y 
The are 25 elements in the list


The original listTwo is: 
OAQTRHPCWYKQJLDVISONZN ORLBRYUSSXFNFQ YSLFLIASALCGMYBNXISCIJQ OPEMSYQVZUMCCVDS 
The are 4 elements in the list
  The longest string has 23 characters, so the number of needed passes is 23
The original listTwo sorted with RadixSort: 
OAQTRHPCWYKQJLDVISONZN OPEMSYQVZUMCCVDS ORLBRYUSSXFNFQ YSLFLIASALCGMYBNXISCIJQ 
The are 4 elements in the list

The mergeChain is:
BMZG BNOZ BTQ CLY D DF DIN GA GFLU H JBAO KK MCE NCQD O OAQTRHPCWYKQJLDVISONZN OPEMSYQVZUMCCVDS ORLBRYUSSXFNFQ OVWM OX RWU RYBA SJX U UAR WT X Y YSLFLIASALCGMYBNXISCIJQ 
The are 29 elements in the list
The listOne sorted should be unchanged: 
BMZG BNOZ BTQ CLY D DF DIN GA GFLU H JBAO KK MCE NCQD O OVWM OX RWU RYBA SJX U UAR WT X Y 
The are 25 elements in the list
The listTwo sorted should be unchanged: 
OAQTRHPCWYKQJLDVISONZN OPEMSYQVZUMCCVDS ORLBRYUSSXFNFQ YSLFLIASALCGMYBNXISCIJQ 
The are 4 elements in the list

Process finished with exit code 0


   

import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;

/**
 * A class Radix Sort tester
 *
 * @author YOUR NAME
 * @version 10/6/2020
 */
public class SortChain>
{
    private ChainOfNodes linkedDataOne;
    private ChainOfNodes linkedDataTwo;
    private Random generator;

    public SortChain(int listSizeOne, int maxStringLengthOne, int listSizeTwo, int maxStringLengthTwo)
    {
        this.generator = new Random(101);
        this.linkedDataOne = generateList(listSizeOne, maxStringLengthOne);
        this.linkedDataTwo = generateList(listSizeTwo, maxStringLengthTwo);
    }

    /**
     * Creates a ChainOfNodes object called list, randomly generates String objects and adds them to the list
     *
     * @param listSize        - number of STring objects to generate
     * @param maxStringLength - the maximum number of characters in the generated String object
     * @return created list
     */
    private ChainOfNodes generateList(int listSize, int maxStringLength)
    {
        final int ASCII_Z = 90;
        final int ASCII_A = 65;
        ChainOfNodes list = new ChainOfNodes<>();
        //TODO Project 4 #1

        for (int i = 0; i < listSize; i++)
        {
            StringBuilder builder = new StringBuilder();
            int length = generator.nextInt (maxStringLength) + 1;

            for (int j = 0; j < length; j++)
            {
                char c = (char) (generator.nextInt ((ASCII_Z - ASCII_A) + 1) + ASCII_A) ;
                builder.append (c);
            }
            String word = builder.toString();
            list.add (word);
        }

        return list;
    }

    public void sortLinkedDataAndDisplayResults()
    {
        System.out.println("\nThe original listOne is: ");
        displayChain(this.linkedDataOne.firstNode);
        stringRadixSort(this.linkedDataOne);
        System.out.println("The original listOne sorted with RadixSort: ");
        displayChain(this.linkedDataOne.firstNode);

        System.out.println("\n\nThe original listTwo is: ");
        displayChain(this.linkedDataTwo.firstNode);
        stringRadixSort(this.linkedDataTwo);
        System.out.println("The original listTwo sorted with RadixSort: ");
        displayChain(this.linkedDataTwo.firstNode);
    }

    /**
     * RADIX SORT
     * sorts String objects in linkedData chain of nodes
     */
    private void stringRadixSort(ChainOfNodes linkedData)
    {
        // TODO Project 4 #2
        Node currentNode = linkedData.firstNode;
        final int NUMBER_OF_UPPER_CASE_LETTERS = 26;

        // do nothing if no more than one node

        // otherwise
        // create buckets

        // traverse the chain to find the longest string

        if (currentNode.next == null)
        {
            return;
        }

        Node[] buckets = new Node[NUMBER_OF_UPPER_CASE_LETTERS];


        String longestString = currentNode.data;
        while (currentNode != null)
        {
            if (currentNode.data.length () > longestString.length ())
            {
                longestString = currentNode.data;
            }
            currentNode = currentNode.next;
        }




        int max = longestString.length (); // THIS IS A STUB
        System.out.println("\u001B[35m\u001B[1m  The longest string has " + max + " characters so the number of needed passes is " + max + "\u001B[0m\n");


        // start soring

        // for each pass:
        // distribute nodes to appropriate buckets
        // clear the original chain and add the nodes back in "buckets" order
        // clear buckets


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

            currentNode = linkedData.firstNode;
            int length = 1;

            while (currentNode.data != null)
            {
                if (currentNode.data.length () > i)
                {
                    int charValue = (int) (currentNode.data.charAt (i)) - 'A';

                }
                currentNode = currentNode.next;
                length++;
            }
            linkedData.clear ();
        }

    }

    public void createSortedChainFromTwoAndDisplayResults()
    {
        ChainOfNodes mergeChain = mergeTwoChainsIntoThird();
        System.out.println("\n\u001B[35m\u001B[1mThe mergeChain is:\u001B[0m");
        displayChain(mergeChain.firstNode);

        System.out.println("The listOne sorted should be unchanged: ");
        displayChain(this.linkedDataOne.firstNode);

        System.out.println("The listTwo sorted should be unchanged: ");
        displayChain(this.linkedDataTwo.firstNode);
    }

    /**
     * Merges two sorted chains: this.linkedDataOne and this.linkedDataTwo into a new one
     * and returns a reference to the new chain.
     * Each chain is in ascending order.
     * The resulting chain should be in ascending order
     * The original chains remain unchanged
     */
    private ChainOfNodes mergeTwoChainsIntoThird()
    {
        ChainOfNodes newChain = new ChainOfNodes<>();
        Node firstCurrent = this.linkedDataOne.firstNode;
        Node secondCurrent = this.linkedDataTwo.firstNode;

        while ((firstCurrent != null) && (secondCurrent != null))
        {
            // TODO Project 4 #3
            // Create new node for merged chain and decide what data belongs in it


        } // end while


        // Exhausted one or both chains; add any remaining data


        return newChain;
    }


    /**
     * Displays all entries in the given chain of nodes.
     */
    private void displayChain(Node currentNode)
    {
        if (currentNode == null)
            System.out.println("The list is empty");
        else
        {
            int count = 0;
            while (currentNode != null)
            {
                System.out.print(currentNode.data + " ");
                count++;
                currentNode = currentNode.next;
            }
            System.out.println("\nThe are " + count + " elements in the list");
        }
    }

    /**
     * Chain of nodes class with add method that adds elements to the end of the list
     */
    private class ChainOfNodes>
    {
        private Node firstNode;       // reference to first node
        private Node tailNode;        // reference to the last node in the chain

        public ChainOfNodes()
        {
            this.firstNode = null;
            this.tailNode = null;
        } // end default constructor

        /**
         * Adds a new entry to the end of the chain.
         *
         * @param newEntry the object to be added as a new entry
         * @return true
         */
        public boolean add(T newEntry) // OutOfMemoryError possible
        {
            // add to the end of the chain:
            Node newNode = new Node<>(newEntry);
            if (this.firstNode == null)
            {
                this.firstNode = newNode;
                this.tailNode = newNode;
            }
            else
            {
                this.tailNode.next = newNode;
                this.tailNode = newNode;
            }
            return true;
        } // end add

        /**
         * Removes all entries from this bag.
         */
        public void clear()
        {
            this.firstNode = null;
            this.tailNode = null;
        } // end clear
    } // end ChainOfNodes

    private class Node
    {
        private S data; // entry in bag
        private Node next; // link to next node

        private Node(S dataPortion)
        {
            this(dataPortion, null);
        } // end constructor

        private Node(S dataPortion, Node nextNode)
        {
            this.data = dataPortion;
            this.next = nextNode;
        }
    } // end Node

    public static void main(String args[])
    {
        int listOneSize = 0;
        int maxStringLengthListOne = 0;
        int listTwoSize = 0;
        int maxStringLengthListTwo = 0;
        boolean invalidInput;

        // get input
        do
        {
            try
            {
                invalidInput = false;
                Scanner keyboard = new Scanner(System.in);
                System.out.println("How many nodes in the first chain?" + "\n It should be an integer value greater than or equal to 0.");
                listOneSize = keyboard.nextInt();

                System.out.println("How many characters in the longest string in the first chain?" + "\n It should be an integer value greater than or equal to 1.");
                maxStringLengthListOne = keyboard.nextInt();

                System.out.println("\nHow many nodes in the second chain?" + "\n It should be an integer value greater than or equal to 0.");
                listTwoSize = keyboard.nextInt();

                System.out.println("How many characters in the longest string in the second chain?" + "\n It should be an integer value greater than or equal to 1.");
                maxStringLengthListTwo = keyboard.nextInt();
            } catch (InputMismatchException ime)
            {
                System.out.println("Could not convert input to an integer");
                invalidInput = true;
            } catch (Exception e)
            {
                System.out.println("There was an error with System.in");
                System.out.println(e.getMessage());
                invalidInput = true;
            }
        } while (invalidInput);

        SortChain tester = new SortChain(listOneSize, maxStringLengthListOne, listTwoSize, maxStringLengthListTwo);
        tester.sortLinkedDataAndDisplayResults();
        tester.createSortedChainFromTwoAndDisplayResults();
    }
} // end RadixSort

Solutions

Expert Solution

SortChain.java

import java.lang.reflect.Array;
import java.util.LinkedList;
import java.util.List;

public class SortChain{
   List<String> list;
  
   public SortChain() {
       list=new LinkedList<>();
   }
   public void stringRadixSort() {
       if (list.size() <= 1) {
   return;
   }
       int n=list.size();
   List<String>[] buckets = new List[27];
   for (int i = 0; i < buckets.length; i++) {
   buckets[i] = new LinkedList<>();
   }
   int largestLength = -1;
   int secondLargestLength = 0;
   for (String s : list) {
   int length = s.length();
   if (length >= largestLength) {
   secondLargestLength = largestLength;
   largestLength = length;
   } else if (secondLargestLength < length) {
   secondLargestLength = length;
   }
   }
  
   System.out.println("\nThe longest string has "+largestLength+" characters, so the number of needed passes is "+largestLength);
   for (int i = secondLargestLength == largestLength ? secondLargestLength-1 : secondLargestLength; i >= 0; i--) {
   for (String word : list) {
   int index = (word.length() <= i) ? 0 : word.charAt(i) - ('A' - 1);
   buckets[index].add(word);
   }

   list.clear();

   for (List<String> lst : buckets) {
   if (lst != null) {
   list.addAll(lst);
   lst.clear();
   }
   }
     
  
   }
   System.out.println("The original list sorted with RadixSort:");
   for(String s:list) {
   System.out.print(s+" ");
}
   }
   public static void main(String args[]) {
       SortChain d=new SortChain();
       d.list.add("HI");
       d.list.add("ERFG");
       d.list.add("ASD");
       d.list.add("BVD");
       d.list.add("SDFGNV");
       System.out.println("Original list is:");
       for(int i=0;i<d.list.size();i++) {
           System.out.print(d.list.get(i)+" ");
       }
       d.stringRadixSort();
   }
}

Output:


Related Solutions

Hey guys, So I am doing a presentation on the element Gold, Au. Now I could...
Hey guys, So I am doing a presentation on the element Gold, Au. Now I could go look up the information online but I am really running out of time here, could someone provide me with as much information as you can on the elemnt gold(NOTE NOT PLAGIARIZED). Please cite everything and just hook me up with as many paragraphs and information on gold as you can. I will downrate you if you just do a lazy copy paste from...
Hey, I have a code that I am working on to make a garden plot calculator,...
Hey, I have a code that I am working on to make a garden plot calculator, however I am reaching an error that I cannot seem to get past. Please help. import math # GarednPlot contains all the utility functions class GardenPlot: # constructor function: Welcomes the user and sets default values def __init__(self): print("Welcome!") self.length = 0 self.radius = 0 self.depth = 0 # Sets the length of the GardenPlot and returns that length def setLength(self): self.length = float(input("Enter...
Hey yall, Im working on a quiz I completed. I really need to get a 100...
Hey yall, Im working on a quiz I completed. I really need to get a 100 I worked all the problems out and i was wondering if one of yall would mind checking it for me. If i missed one if yall could tell me how to get the correct answer? 1.The intermolecular forces present in CH3NH2 include which of the following? I. dipole-dipole II. ion-dipole III. dispersion IV. hydrogen bonding ANS: I, III, and IV 2. A liquid boils...
I working on this program in C++ and I keep getting 20 errors of the same...
I working on this program in C++ and I keep getting 20 errors of the same type again.cpp:36:11: error: use of undeclared identifier 'Polynomial' int main() { // create a list of polinomials vector<Polynomial> polynomials; // welcome message cout << "Welcome to Polynomial Calculator" << endl; int option = 0; while (option != 6) { // display menu displayMenu(); // get user input; cin >> option; if (option == 1) { cout << "Enter a polynomial :" << endl; string...
I am not quite sure how to get this program working or how to start it...
I am not quite sure how to get this program working or how to start it in the first place. Write a full Java program and do the following: 1- Create a generic class and declare a one dim array as a private member. 2- Add a constructor to initialize the array. 3- A set method to set the array. 4- Sort method to sort the array. 5- Print method to print the array. 6- Reverse method to reverse the...
Hello, i have this assignment i have tried solving it but been hitting road blocks how...
Hello, i have this assignment i have tried solving it but been hitting road blocks how do i solve this also, i have the texas BA II PLUS Calculator can you tell me how to solve for this using the fomular approach Thank you Questions Based on the following cash flows, which of the following mutually exclusive project would you choose? You require a 15% return on your investment. Year 0 (Initial Investment) 1 2 3 4 Project #1 ($300,000)...
hey. so I need to understand what each of the following Cytokines do: TNF? , TNF?,...
hey. so I need to understand what each of the following Cytokines do: TNF? , TNF?, TNF ?, IL-3 (G-CSF and GM-CSF), IL-7 (so I undesrtand there is also something similiar like in 3 with CSF?, does he decide to what lymphocyte will be produced? if not who does that and whats his function), IL-4, IL-5, IL-6, IL-17, IL-2, IL-12, IL-1, IL-8 (didn't get what they mean by does chemotaxis), IL-10 and IL-13. ok so this is the first course...
Hey i am a Electrical Engineering student So as we all know due to this pandemic...
Hey i am a Electrical Engineering student So as we all know due to this pandemic situation universities are closed. So we were not able to work on our lab Hardware part so we are trying to cover its software part. Now lets come to the point i am working on my DIGITAL LOGIC DESIGN lab we are using two softwares in that lab one is XILINX and the other one is PROTEUS.now as the end of the semester is...
I hope you have been well and enjoying your new positions- ive heard great things are...
I hope you have been well and enjoying your new positions- ive heard great things are in motion with the train the trainer project. please send me the draft ot your narrative on the KSAs and competency model by the end of the week.
YOU GUYS PROVIDE ME THE WRONG ANSWER SO I NEED THE CORRECT ANS Check my work...
YOU GUYS PROVIDE ME THE WRONG ANSWER SO I NEED THE CORRECT ANS Check my work Check My Work button is now enabledItem 4 Item 4 30 points A private not-for-profit entity is working to create a cure for a deadly disease. The charity starts the year with cash of $775,000. Of this amount, unrestricted net assets total $425,000, temporarily restricted net assets total $225,000, and permanently restricted net assets total $125,000. Within the temporarily restricted net assets, the entity...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT