Question

In: Computer Science

Test Memory Usage on the Text File Reversing Problem (1 mark) Test the performance of your...

Test Memory Usage on the Text File Reversing Problem (1 mark)
Test the performance of your Stack implementation on file reversing task. The code below is to reverse a text file using the stack. It has three lines missing, and you need to complete it. Then you submit it on our marking site here. You need to change the stack capacity according to input data size. On average each line has about 11 words. Our site prints out the total computer memory usage by your program when it runs on 5 data sets of different sizes.
The total memory usage from the submission site is

static String[] reverse(String filename) throws Exception{
       Scanner scanner = new Scanner(new File(filename)).useDelimiter("[^a-zA-Z]+");
       Stack2540Array stack = new Stack2540Array();
       while (scanner.hasNext())
           stack.push(scanner.next().toLowerCase());
       String[] rev = new String[stack.size()];


/* for (int i = 0; i < stack.size(); i++) {
           rev[i] = stack.pop();
       } */


       return rev;
   }

The code for Stack2540Array cannot be modified:

import java.io.*;
import java.util.*;

public class Stack2540Array {
   int CAPACITY = 128;
   int top;
   String[] stack;
  
   public Stack2540Array() {
       stack = new String[CAPACITY];
       top = -1;
   }

   public int size() {       return top + 1;   }
   public boolean isEmpty() {       return (top == -1); }

   public String top() {
       if (top == -1)
           return null;
       return stack[top];
   }
      
   public void push(String element) {
       top++;
       stack[top] = element;
   }

   public String pop() {
   if (top == -1) {
return null;
}
   else {
return stack[top--];
}
   }
}

The lines are added as comments, but the output shows: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 128 out of bounds for length 128. Your Stack and reverse() can run, but the result is not correct. Can you please fix the error in the code?

* The complete program is not available as we are supposed to work with code fragments.

Solutions

Expert Solution

Here to fix this error I am adding a new variable called "count" which keeps tracking when every new element is pushed into the stack.

I implemented the driver code to test it.

CODE:

import java.io.*;
import java.util.*;

class Stack2540Array {
   int CAPACITY = 128;
   int top;
   String[] stack;
  
   public Stack2540Array() {
       stack = new String[CAPACITY];
       top = -1;
   }

   public int size() {       return top + 1;   }
   public boolean isEmpty() {       return (top == -1); }

   public String top() {
       if (top == -1)
           return null;
       return stack[top];
   }
      
   public void push(String element) {
       top++;
       stack[top] = element;
   }

   public String pop() {
   if (top == -1) {
return null;
}
   else {
return stack[top--];
}
   }
}
public class Main{
    static String[] reverse(String filename) throws Exception{
       Scanner scanner = new Scanner(new File(filename)).useDelimiter("[^a-zA-Z]+");
       Stack2540Array stack = new Stack2540Array();
       int count=0;//Introducing a new variable
       while (scanner.hasNext()){
           stack.push(scanner.next().toLowerCase());
           count+=1;//Keeping a track when every new element is pushed
       }
       String[] rev = new String[stack.size()];
        for (int i = 0; i < count; i++) {//using the count as the size 
           rev[i] = stack.pop();;
        } 

       return rev;
   }
   //Driver code to test for output
        public static void main(String[] args) throws Exception{
            String a[]=reverse("test.txt");
            for(String i:a){
           System.out.println(i);}
        }
}

Screenshots of the Code for your reference:

The text file and the output of the code:

Thank you! if you have any queries post it below in the comment section I will try my best to resolve your queries and I will add it to my answer if required. Please give upvote if you like my work.


Related Solutions

Problem 2(a). Letter Frequencies. ? Write Python code that reads a text file into memory and...
Problem 2(a). Letter Frequencies. ? Write Python code that reads a text file into memory and creates a dict object with a frequency count for each letter. For example, for encryptedA.txt, your output should contain the key:value pairs 'a': 78 and 'b': 31. Notes Do not distinguish between uppercase and lowercase letters. Ignore punctuation. Punctuation counts must not appear in your dict If a given letter does not appear in the text, there must be a key:value pair with value...
Write all your answers for this problem in a text file named aa.txt – for each...
Write all your answers for this problem in a text file named aa.txt – for each problem write the problem number and your answer. 1.1 What type of object can be contained in a list (write the letter for the best answer)? a. String b. Integer c. List d. String and Integer only e. String, Integer, and List can all be contained in a list 1.2 Which statement about the debugger is not correct? a. It is a powerful tool...
Write a C++ program to create a text file. Your file should contain the following text:...
Write a C++ program to create a text file. Your file should contain the following text: Batch files are text files created by programmer. The file is written in notepad. Creating a text file and writing to it by using fstream: to write to a file, you need to open thew file as write mode. To do so, include a header filr to your program. Create an object of type fsrteam. Open the file as write mode. Reading from a...
Your task is to count the frequency of words in a text file, and return the...
Your task is to count the frequency of words in a text file, and return the most frequent word with its count. For example, given the following text: there are two ways of constructing a software design one way is to make it so simple that there are obviously no deficiencies and the other way is to make it so complicated that there are no obvious deficiencies. Based on the example your program should printout the following along with the...
Your task is to count the frequency of words in a text file, and return the...
Your task is to count the frequency of words in a text file, and return the most frequent word with its count. (Must use the code below without changing algorithms) For example, given the following text: there are two ways of constructing a software design one way is to make it so simple that there are obviously no deficiencies and the other way is to make it so complicated that there are no obvious deficiencies. Based on the example your...
Problem Statement You are required to read in a list of stocks from a text file...
Problem Statement You are required to read in a list of stocks from a text file “stocks.txt” and write the sum and average of the stocks’ prices, the name of the stock that has the highest price, and the name of the stock that has the lowest price to an output file. The minimal number of stocks is 30 and maximal number of stocks in the input file is 50. You can download a input file “stocks.txt” from Canvas. When...
The C++ problem: Student marks are kept in a text file as a single column. Each...
The C++ problem: Student marks are kept in a text file as a single column. Each student may have a different number of assessments and therefore scores. The data recorded in the file for each student start with the number of scores for the student. This is followed by the student id and then several marks student scored in various assessments, one score per line. A small segment of the file might look like the following: (file name is marks.txt)...
Problem: Write a Python module (a text file containing valid Python code) named p5.py. This file...
Problem: Write a Python module (a text file containing valid Python code) named p5.py. This file must satisfy the following. Define a function named rinsert. This function will accept two arguments, the first a list of items to be sorted and the second an integer value in the range 0 to the length of the list, minus 1. This function shall insert the element corresponding to the second parameter into the presumably sorted list from position 0 to one less...
You are given a text file containing a short text. Write a program that 1. Reads...
You are given a text file containing a short text. Write a program that 1. Reads a given text file : shortText.txt 2. Display the text as it is 3. Prints the number of lines 4. Prints the occurences of each letter that appears in the text. [uppercase and lowercase letter is treated the same]. 5. Prints the total number of special characters appear in the text. 6. Thedisplayofstep3,4and5aboveshouldbesaveinanoutputfile:occurencesText.txt write it in C++ programing Language
Create this C++ program using classes 1. Create a file text file with a string on...
Create this C++ program using classes 1. Create a file text file with a string on it 2. Check the frecuency of every letter, number and symbol (including caps) 3. Use heapsort to sort the frecuencys found 4. Use huffman code on the letters, symbols or numbers that have frecuencys I created the file, and the frecuency part but i'm having trouble with the huffman and heapsort implementation.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT