Question

Please change the first algorithm (the one with linked lists) so it runs faster using the...

Please change the first algorithm (the one with linked lists) so it runs faster using the List.Iterator() function. The program uses 2 algorithms one is linked lists and the other is arrays. Just need to change the linked list algorithm so that it runs faster, to do that it needs to use list.iterator function instead of get(i). I have highlighted the area that needs to be changed, rest should be fine. The function of the program is to read a text file and see which word is the most frequent and return the time it took to do it using both arrays and linked list algorithms.

import java.io.File;
import java.util.Scanner;
import java.util.Map.Entry;
import java.util.AbstractMap;
import java.util.LinkedList;

public class WordCountLinkedList254 {
  
   public static Entry count_ARRAY(String[] tokens) {
       int CAPACITY = 10000;
       String[] words = new String[CAPACITY];
       int[] counts = new int[CAPACITY];
       for (int j = 0; j < tokens.length; j++) {
           String token = tokens[j];
           for (int i = 0; i < CAPACITY; i++) {
               if (words[i] == null) {
                   words[i] = token;
                   counts[i] = 1;
                   break;
               } else if (words[i].equals(token))
                   counts[i] = counts[i] + 1;
           }
       }

       int maxCount = 0;
       String maxWord = "";
       for (int i = 0; i < CAPACITY & words[i] != null; i++) {
           if (counts[i] > maxCount) {
               maxWord = words[i];
               maxCount = counts[i];
           }
       }
       return new AbstractMap.SimpleEntry(maxWord, maxCount);
   }

   public static Entry count_LINKED_LIST(String[] tokens) {
       LinkedList> list = new LinkedList>();
       for (int j = 0; j < tokens.length; j++) {
           String word = tokens[j];
           boolean found = false;
          
           for (int i = 0; i < list.size(); i++) {
               Entry e = list.get(i);

               if (word.equals(e.getKey())) {
                   e.setValue(e.getValue() + 1);
                   list.set(i, e);
                   found = true;
                   break;
               }
           }

          
           if (!found)
               list.add(new AbstractMap.SimpleEntry(word, 1));
       }

       int maxCount = 0;
       String maxWord = "";
       for (int i = 0; i < list.size(); i++) {
           int count = list.get(i).getValue();
           if (count > maxCount) {
               maxWord = list.get(i).getKey();
               maxCount = count;
           }
       }
       return new AbstractMap.SimpleEntry(maxWord, maxCount);
   }

   static String[] readText(String PATH) throws Exception {
       Scanner doc = new Scanner(new File(PATH)).useDelimiter("[^a-zA-Z]+");
       int length = 0;
       while (doc.hasNext()) {
           doc.next();
           length++;
       }

       String[] tokens = new String[length];
       Scanner s = new Scanner(new File(PATH)).useDelimiter("[^a-zA-Z]+");
       length = 0;
       while (s.hasNext()) {
           tokens[length] = s.next().toLowerCase();
           length++;
       }
       doc.close();

       return tokens;
   }
  
   public static void main(String[] args) throws Exception {
      
       String PATH = "dblp200.txt";
       String[] tokens = readText(PATH);
       long startTime = System.currentTimeMillis();
       Entry entry = count_LINKED_LIST(tokens);
       long endTime = System.currentTimeMillis();
       String time = String.format("%12d", endTime - startTime);
       System.out.println("time\t" + time + "\t" + entry.getKey() + ":" + entry.getValue());
      
       tokens = readText(PATH);
       startTime = System.currentTimeMillis();
       entry = count_ARRAY(tokens);
       endTime = System.currentTimeMillis();
       time = String.format("%12d", endTime - startTime);
       System.out.println("time\t" + time + "\t" + entry.getKey() + ":" + entry.getValue());
   }
}

Homework Answers

Answer #1

Here is the completed code for this problem, updated as you requested. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

// WordCountLinkedList254.java

import java.io.File;

import java.util.Iterator;

import java.util.Scanner;

import java.util.Map.Entry;

import java.util.AbstractMap;

import java.util.LinkedList;

public class WordCountLinkedList254 {

      public static Entry count_ARRAY(String[] tokens) {

            int CAPACITY = 10000;

            String[] words = new String[CAPACITY];

            int[] counts = new int[CAPACITY];

            for (int j = 0; j < tokens.length; j++) {

                  String token = tokens[j];

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

                        if (words[i] == null) {

                              words[i] = token;

                              counts[i] = 1;

                              break;

                        } else if (words[i].equals(token))

                              counts[i] = counts[i] + 1;

                  }

            }

            int maxCount = 0;

            String maxWord = "";

            for (int i = 0; i < CAPACITY & words[i] != null; i++) {

                  if (counts[i] > maxCount) {

                        maxWord = words[i];

                        maxCount = counts[i];

                  }

            }

            return new AbstractMap.SimpleEntry(maxWord, maxCount);

      }

      public static Entry count_LINKED_LIST(String[] tokens) {

            LinkedList<Entry<String, Integer>> list = new LinkedList();

            for (int j = 0; j < tokens.length; j++) {

                  String word = tokens[j];

                  boolean found = false;

                  //creating an iterator from the list

                  Iterator<Entry<String, Integer>> iterator = list.iterator();

                  //looping as long as there is an element to iterate

                  while (iterator.hasNext()) {

                        //getting next entry

                        Entry<String, Integer> e = iterator.next();

                        //checking if word is same as key of e

                        if (word.equals(e.getKey())) {

                              //updating count by 1

                              e.setValue(e.getValue() + 1);

                              found = true;

                              break;

                        }

                  }

                  //old code

                  /*for (int i = 0; i < list.size(); i++) {

                     Entry<String, Integer> e = list.get(i);

                     if (word.equals(e.getKey())) {

                         e.setValue(e.getValue() + 1);

                         list.set(i, e);

                         found = true;

                         break;

                     }

                 }*/

                  if (!found)

                        list.add(new AbstractMap.SimpleEntry(word, 1));

            }

            int maxCount = 0;

            String maxWord = "";

            for (int i = 0; i < list.size(); i++) {

                  int count = list.get(i).getValue();

                  if (count > maxCount) {

                        maxWord = list.get(i).getKey();

                        maxCount = count;

                  }

            }

            return new AbstractMap.SimpleEntry(maxWord, maxCount);

      }

      static String[] readText(String PATH) throws Exception {

            Scanner doc = new Scanner(new File(PATH)).useDelimiter("[^a-zA-Z]+");

            int length = 0;

            while (doc.hasNext()) {

                  doc.next();

                  length++;

            }

            String[] tokens = new String[length];

            Scanner s = new Scanner(new File(PATH)).useDelimiter("[^a-zA-Z]+");

            length = 0;

            while (s.hasNext()) {

                  tokens[length] = s.next().toLowerCase();

                  length++;

            }

            doc.close();

            return tokens;

      }

      public static void main(String[] args) throws Exception {

            String PATH = "dblp200.txt";

            String[] tokens = readText(PATH);

            long startTime = System.currentTimeMillis();

            Entry entry = count_LINKED_LIST(tokens);

            long endTime = System.currentTimeMillis();

            String time = String.format("%12d", endTime - startTime);

            System.out.println("time\t" + time + "\t" + entry.getKey() + ":"

                        + entry.getValue());

            tokens = readText(PATH);

            startTime = System.currentTimeMillis();

            entry = count_ARRAY(tokens);

            endTime = System.currentTimeMillis();

            time = String.format("%12d", endTime - startTime);

            System.out.println("time\t" + time + "\t" + entry.getKey() + ":"

                        + entry.getValue());

      }

}

Know the answer?
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
Similar Questions
Do a theta analysis and count the number of computations it performed in each function/method of...
Do a theta analysis and count the number of computations it performed in each function/method of the following code: import java.io.*; import java.util.Scanner; class sort { int a[]; int n; long endTime ; long totalTime; long startTime; static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public sort(int nn) // Constructor { a = new int[nn]; n = nn; endTime= 0; totalTime =0; startTime =0; } public static void main(String args[]) throws IOException { System.out.print("\nEnter number of students: "); int nn =...
Use the TestTime.java/TestTime.cpp le to compare the two queue implementations. Note that enqueue function when implemented...
Use the TestTime.java/TestTime.cpp le to compare the two queue implementations. Note that enqueue function when implemented using an array has O(1) complexity, and when using two arrays has O(n) complexity, where n is the current size of the queue. So, the two stack implementation should take more time, which is substantiated by the experiment (time output). public class TestTime {    public static void main(String[] args) throws Exception {        for (int maxSize = 10000; maxSize <= 50000; maxSize...
using java LO: (Analyze) Students will fix a loop that runs forever. This program runs the...
using java LO: (Analyze) Students will fix a loop that runs forever. This program runs the countdown sequence for a rocket launch. However, it seems to loop infinitely. Fix the program so it counts down and terminates properly. starter code : import java.util.Scanner; /* * Counts down to a blastoff, starting from a given number. */ public class Countdown {    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        int countdown = 0;...
[Java] I'm not sure how to implement the code. Please check my code at the bottom....
[Java] I'm not sure how to implement the code. Please check my code at the bottom. In this problem you will write several static methods to work with arrays and ArrayLists. Remember that a static method does not work on the instance variables of the class. All the data needed is provided in the parameters. Call the class Util. Notice how the methods are invoked in UtilTester. public static int min(int[] array) gets the minimum value in the array public...
If you cant answer this please dont waste my question. thank you. This cryptographic program run...
If you cant answer this please dont waste my question. thank you. This cryptographic program run and produce text screen output. You are to create a GUI that uses the program. Your program (GUI) must allow a user to input of a message to be coded. It must also have an area to show the plaintext, the ciphertext, and the decrypted text. If required by your choice of cryptographic method, the user should have an area to input a key....
Solve Project 2 using a TreeMap. You can display the words in key sequence without performing...
Solve Project 2 using a TreeMap. You can display the words in key sequence without performing a sort. Java Project 2: Use a HashMap to store the frequency counts for all the words in a large text document. When you are done, display the contents of this HashMap. Next, create a set view of the Map and store its contents in an array. Then sort the array based on key value and display it. Finally, sort the array in decreasing...
Java Programming Language Currently my code is recording all the nodes it took to find the...
Java Programming Language Currently my code is recording all the nodes it took to find the Longest Path. But i only want it to record the nodes that takes it to the longest path. import java.util.*; import java.awt.Point; class Main {     // M x N matrix     private static final int M = 10;     private static final int N = 10;     static ArrayList<Point> Path = new ArrayList<Point>();     // check if it is possible to go to position (x, y) from     //...
Question: I am using three different ways to execute this program. I am a bit confused...
Question: I am using three different ways to execute this program. I am a bit confused on the time complexity for each one. Can someone explain the time complexity for each function in relation to the nanoseconds. import java.util.HashMap; import java.util.Map; public class twosums {       public static void main(String args[]) {               int[] numbers = new int[] {2,3,9,4,8};;        int target = 10;               long nano_begin1 = System.nanoTime();        int[]...
Java : Modify the selection sort algorithm to sort an array of integers in descending order....
Java : Modify the selection sort algorithm to sort an array of integers in descending order. describe how the skills you have gained could be applied in the field. Please don't use an already answered solution from chegg. I've unfortunately had that happen at many occasion ....... ........ sec01/SelectionSortDemo.java import java.util.Arrays; /** This program demonstrates the selection sort algorithm by sorting an array that is filled with random numbers. */ public class SelectionSortDemo { public static void main(String[] args) {...
please fix code to delete by studentname import java.util.Scanner; public class COurseCom666 {     private String...
please fix code to delete by studentname import java.util.Scanner; public class COurseCom666 {     private String courseName;     private String[] students = new String[1];     private int numberOfStudents;     public COurseCom666(String courseName) {         this.courseName = courseName;     }     public String[] getStudents() {         return students;     }     public int getNumberOfStudents() {         return numberOfStudents;     }     public void addStudent(String student) {         if (numberOfStudents == students.length) {             String[] a = new String[students.length + 1];            ...