Question

In: Computer Science

the assignment folder for this assignment contains a file called values.txt. The first line in the...

the assignment folder for this assignment contains a file called values.txt. The first line in the file contains the total number of integers which comes after it. The length of this file will be the first line plus one lines long.

Implement a MinHeap. Your program should read in input from a file, add each value to the MinHeap, then after all items are added, those values are removed from the MinHeap. Create a java class called MinHeap with the package name csci3250.heap. Some parts of this classes is written for you. You need to complete it. Create a java main class (contains the main method) called HeapTest.java to test the min heap. This class also is in the package csci3250.heap

Your program must contain adequate comments including your name in both java classes.


package csci3250.heap;

import java.util.Vector;

public class MinHeap {

    private Vector mVector;

    /**

     * heapifies one subtree (It ensures that a parent is smaller than its

     * children and will be recursively called on the smallest child if

     * necessary.)

     *

     * @param index

     */

    private int heapifyNode(int nodeIndex) {       

    }

    // swaps two positions in mVector

    private void swap(int firstNodeIndex, int secondNodeIndex) {              

    }

    // Empty default constructor

    public MinHeap() {       

    }

    // Inserts, always maintaining a heap

    public void insert(int value) {    

    }

    // Removes the top element

    public int remove() {

    }

    // Returns true if heap is empty

    public boolean isEmpty() {

    }

    // Returns the top element at 0

    public int peek() {

    }

}

The vector is used to store the heap. In the main method of HeapTest.java you may need to use the following code to read the file. Complete the code (Keep in mind this piece of code must be in the method main)

File file = new File("src/main/java/csci3250/heap/nums.txt");

            try {

                Scanner inputStream = new Scanner(file);

             //complete the code

            } catch (FileNotFoundException ex) {

                System.out.println("File not found");

                System.exit(0);

            }

Your program should take the following steps.

  1. Prompt for read from file or read numbers from input.
  2. If the user chooses to read from the file read from the file nums.txt and go to step 4
  3. If the user chooses to enter numbers, prompt for a number of elements and go to step 4
  4. Read all of the elements into the heap using the insert call.
  5. Print the heap elements by removing each element one at a time.

Output

A sample output of the program is shown here.

How do you wish to insert into the heap? [R]ead from the nums.txt file or [I]nsert numbers? I

How many values do you wish to insert? 5

1: 3

2: 2

3: 6

4: 1

5: 9

Printing Heap

1

2

3

6

9

100000
49269
7139
6037
58922
32000
5234
2969
80843
24300
68862
75009
94960
90811
93247
77301
17633
89072
54112
98223
50535
62235
49773
64606
11393
40067
14873

This is the code that I have but I dont know how to translate it java and to the fix the mistakes please

#pragma once

#include
#include

using namespace std;

struct PriorityQueue

{

private:

vector A;

int PARENT(int i)

{

return (i - 1) / 2;

}

int LEFT(int i)
{
return (2 * i + 1);
}

int RIGHT(int i)
{
return (2 * i + 2);
}


void heapify_down(int i)
{

int left = LEFT(i);
int right = RIGHT(i);

int smallest = i;

if (left < size() && A[left] < A[i])
smallest = left;

if (right < size() && A[right] < A[smallest])
smallest = right;

if (smallest != i)
{
swap(A[i], A[smallest]);
heapify_down(smallest);
}
}


void heapify_up(int i)
{
// check if node at index i and its parent violates
// the heap property
if (i && A[PARENT(i)] > A[i])
{
// swap the two if heap property is violated
swap(A[i], A[PARENT(i)]);

// call Heapify-up on the parent
heapify_up(PARENT(i));
}
}

public:

unsigned int size()
{
return A.size();
}


bool empty()
{
return size() == 0;
}


void push(int key)
{
// insert the new element to the end of the vector
A.push_back(key);

// get element index and call heapify-up procedure
int index = size() - 1;
heapify_up(index);
}

// function to remove element with lowest priority (present at root)
void pop()
{
try
{

if (size() == 0)
throw out_of_range("Vector::at() : "
"index is out of range(Heap underflow)");

// replace the root of the heap with the last element
// of the vector
A[0] = A.back();
A.pop_back();

// call heapify-down on root node
heapify_down(0);
}
// catch and print the exception
catch (const out_of_range & oor)
{
cout << "\n" << oor.what();
}
}


int top()
{
try {

if (size() == 0)
throw out_of_range("Vector::at() : "
"index is out of range(Heap underflow)");


return A.at(0); // or return A[0];
}

catch (const out_of_range & oor) {
cout << "\n" << oor.what();
}
}
};

#include
#include

#include "Minheap.h"


int main()
{
PriorityQueue pq;
int arr[10] = { 10,20,30,40,50,60,70,80,90};
  
for (int i = 0; i < 15; i++)//.#i is from the text file values.txt
pq.push(90);


cout << "Size is " << pq.size() << endl;

cout << pq.top() << " "< pq.pop();

cout << pq.top() << " " << endl;
pq.pop();

cout << endl << "Size is " << pq.size() << endl;

cout << pq.top() << " " << endl;
pq.pop();

cout << pq.top() << " " << endl;
pq.pop();

cout << pq.top() << " "< pq.pop();

cout << pq.top() << " "< pq.pop();

cout << endl << std::boolalpha << pq.empty();

pq.top(); // top op empty heap
pq.pop(); // pop op empty heap

return 0;
}

Solutions

Expert Solution

The code is written as it was mentioned in the problem statement, please note that I have written both the classes in a single file and made the main function public, you can make both class public and save it in different files with the same package. For running this snippet of code you need to save a file named "HeapTest.java". I was confused a little regarding the format of file input so for reading from a file, it is assumed that the file consists of only two-line, the first line of the file contains a single number n denoting the size of the min-heap and the second line contains n separated integers. If you need it in any other format you can just mention it in the comment box. A sample of the output of the same has been added.

CODE:

//package csci3250.heap;

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

class MinHeap {    

    private Vector<Integer> mVector;

    /**

     * heapifies one subtree (It ensures that a parent is smaller than its

     * children and will be recursively called on the smallest child if

     * necessary.)

     *

     * @param index

     */


    // swaps two positions in mVector

    private void swap(int firstNodeIndex, int secondNodeIndex) {          
        
        
        Integer temp = mVector.get(firstNodeIndex);            // store the first value in a temp variable
        mVector.setElementAt(mVector.get(secondNodeIndex), firstNodeIndex);   // store the second value at firstNodeIndex and temp value at secondNodeIndex
        mVector.setElementAt(temp, secondNodeIndex);         
 
    }

    // Empty default constructor

    public MinHeap() {  
        mVector = new Vector();

    }
    
    // Empty parametrized constructor
    public MinHeap(int capacity) {  
        mVector = new Vector(capacity);

    }
    
    
    private int PARENT(int i)               // function which returns parent node of given node i
    {
        if (i == 0)                           // if  i is root then there is no parent
            return 0;
 
        return (i - 1) / 2;                   // else return (i-1)/2
    }
 
    private int LEFT(int i)                // function which returns left node of given node i
    {
        return (2 * i + 1);
    }
 
    private int RIGHT(int i)                            // function which returns right  node of given node i
    {
        return (2 * i + 2);
    }
    
    private void heapify_down(int i)           // function for heapify down for min heap
    {
        // get left and right child of node at index i
        int left = LEFT(i);        
        int right = RIGHT(i);
 
        int smallest = i;                  // set the smallest to current node
 
        if (left < size() && mVector.get(left) < mVector.get(i)) {       // get the smallest of left and right node of current node
            smallest = left;
        }
 
        if (right < size() && mVector.get(right) < mVector.get(smallest)) {
            smallest = right;
        }
 
        if (smallest != i)                                      // and if the smallest node changes from before
        {
            
            swap(i, smallest);                                    // then swap the smallest one with the current and recursively call the same function until smallest keep changes
 
            heapify_down(smallest);
        }
    }
 
    private void heapify_up(int i)           // function for heapify up for minheap
    {
     
        if (i > 0 && mVector.get(PARENT(i)) > mVector.get(i))          // if the parent node is greater that current node then swap and recursively call for the same
        {
            
            swap(i, PARENT(i));
 
            heapify_up(PARENT(i));
        }
    }
    
    public int size()           // returns size
    {
        return mVector.size();
    }
 

    // Inserts, always maintaining a heap

    public void insert(int value) {    // function for inserting into min heap
        
        mVector.addElement(value);     // add the element and heapify from the leaf node
         
        int index = size() - 1;
        heapify_up(index);

    }

    // Removes the top element

    public int remove() {      
        
        try {
            // if heap is empty, throw an exception
            if (size() == 0) {
                throw new Exception("Index is out of range (Heap underflow)");
            }
 
            int root = mVector.firstElement();     // get the root element
 
            
            mVector.setElementAt(mVector.lastElement(), 0);   // set the root element by the leaf node 
            mVector.remove(size()-1);                     // decrease the size 
 
            
            heapify_down(0);                // heapify down from the root node

            return root;
        }
        catch (Exception ex) {
            System.out.println(ex);
            return -1;
            
        }

    }

    // Returns true if heap is empty

    public boolean isEmpty() {          
        
        return size()==0;

    }

    // Returns the top element at 0

    public int peek() {
        
        try {

            if (size() == 0) {
                throw new Exception("Index out of range (Heap underflow)");
            }

            return mVector.firstElement();    
        }
        // catch the exception and print it, and return null
        catch (Exception ex) {
            System.out.println(ex);
            return -1;
           
        }

    }

}


public class HeapTest{
        
        public static void main(String[] args) {               // in main function read the values and insert it one by one.
                
                Scanner sc = new Scanner(System.in);
                
                System.out.println("How do you wish to insert into the heap? [R]ead from the nums.txt file or [I]nsert numbers?");
                String choice = sc.nextLine();
                
                if (choice.contentEquals("R")||choice.contentEquals("I")) {
                        
                        
                        if (choice.contentEquals("R")) {
                                File file = new File("src/main/java/csci3250/heap/nums.txt");
                                
                    try {

                        Scanner inputStream = new Scanner(file);

                        int n = Integer.parseInt(inputStream.nextLine());           // for reading from file it is assumed that the file consists only two line, first line of file contains a single number n denoting size of min heap and second line contains n separated integers 
                        int[] arr = new int[n];
                        String[] strArr = inputStream.nextLine().split(" ");
                        for (int i = 0; i < strArr.length; i++) {
                            String num = strArr[i];
                            arr[i] = Integer.parseInt(num);
                         }
                        
                        MinHeap pq = new MinHeap(n);
                                        for(int i =0;i<n;i++) {
                                                pq.insert(arr[i]);
                                        }
                                        
                                        System.out.println("Printing Heap:");
                                        while (pq.size()!=0) {
                                                System.out.println(pq.remove());
                                        }
                        
                        
                        

                    } catch (FileNotFoundException ex) {

                        System.out.println("File not found");

                        System.exit(0);

                    }
                    
                    
                        }
                        
                        
                        else{
                                
                                System.out.println("How many values do you wish to insert? ");
                                int n = sc.nextInt();
                                int[] arr = new int[n];
                                for(int i=0;i<n;i++) {
                                        System.out.print((i+1)+":");
                                        arr[i] = sc.nextInt();
                                        
                                }
                                        
                        
                                
                                MinHeap pq = new MinHeap(n);
                                for(int i =0;i<n;i++) {
                                        pq.insert(arr[i]);
                                }
                                
                                System.out.println("Printing Heap:");
                                while (pq.size()!=0) {
                                        System.out.println(pq.remove());
                                }
                        
                        }
                        
                        
                        
                }
                
                else {
                        System.out.println("Invalid choice");
                }
                
                
                
                
        }
        /*
        */
}

OUTPUT:

How do you wish to insert into the heap? [R]ead from the nums.txt file or [I]nsert numbers?I
How many values do you wish to insert? 5
1:3
2:2
3:6
4:1
5:9
Printing Heap:
1
2
3
6
9

NOTE: In case of any query you can mention it in the comment box. HAPPY LEARNING!!


Related Solutions

Assume there is a file called "mydata". each line of the file contains two data items
how do you read in a file in JAVA Assume there is a file called "mydata". each line of the file contains two data items: hours and rate. hours is the represented by the number of hours the worker worked and rate is represented as hourly rate of pay. The first item of data is count indicating how many lines of data are to follow.Methodspay- accepts the number of hours worked and the rate of pay. returns the dollor and cents...
On Python Preview the provided sample file called studentdata.txt. It contains one line for each student...
On Python Preview the provided sample file called studentdata.txt. It contains one line for each student in an imaginary class. The student’s name is the first thing on each line, followed by some exam scores. The number of scores might be different for each student. Using the text file studentdata.txt write a program that calculates the average grade for each student, and print out the student’s name along with their average grade with two decimal places.
In the root of the project create a folder called res. In that folder create a...
In the root of the project create a folder called res. In that folder create a file called DemoFile.txt Create a class with a static main that tests the ability to resolve and print a Path: Create an instance of a FileSystem class. Create an instance of the Path interface for the DemoFile.txt file. Print the constructed Path with System.out.println() method. Create a class that does the following: Using a pre-Java 7 solution, create a class that tests streams in...
Exercise 2 — Matrix file The file format for the matrix will have the first line...
Exercise 2 — Matrix file The file format for the matrix will have the first line contain 2 integers, which are the number of rows and columns. After this line, repeatedly count from 0 to 9, filling in the matrix size conditions as specified above. For example: 3 4 0 1 2 3 4 5 6 7 8 9 0 1 Randomly create different sized arrays with random numbers. There should be a space between each number. You will be...
Part 1 Ask for a file name. The file should exist in the same folder as...
Part 1 Ask for a file name. The file should exist in the same folder as the program. If using input() to receive the file name do not give it a path, just give it a name like “number1.txt” or something similar (without the quotes when you enter the name). Then ask for test scores (0-100) until the user enters a specific value, in this case, -1. Write each value to the file as it has been entered. Make sure...
assignment in C I have a file that contains a lot of lines with words separated...
assignment in C I have a file that contains a lot of lines with words separated by spaces ( also contains empty lines as well). I need to read this file line by line and put each word into 2d array. NOTE: i need to skip spaces as well as empty lines. also I need to count each word.
C++ There is a file, called EmployeeInfo.txt, that contains information about company employees work for a...
C++ There is a file, called EmployeeInfo.txt, that contains information about company employees work for a week. You will write a program that reads the info from the file, and produces an output file called EmployeePay.txt with information about the employees pay amount for that week. Details: The input file is called EmployeeInfo.txt There are 4 lines of input Each line has the same form Last Name, first Name, hours worked, pay rate, tax percentage, extra deductions Example: John Doe...
On Moodle, you will find a file labelled “Data for Question 4 Assignment 1”. It contains...
On Moodle, you will find a file labelled “Data for Question 4 Assignment 1”. It contains data on past students in this course. Under Midterm is information on whether past studentsgot an A grade (A−, A, A+) an F or D grade (D is a passing grade but most students need aC− for it to count towards their program) or Other (any grade in between). Under FinalExam is information on whether students got a D or F grade or anything...
What is the name of the folder in the Windows system folder that contains files used in the boot process and regularly opened by other programs?
What is the name of the folder in the Windows system folder that contains files used in the boot process and regularly opened by other programs? 1. User 2. Journal 3. svchost 4. Prefetch
A hotel salesperson enters sales in a text file. Each line contains the following, separated by...
A hotel salesperson enters sales in a text file. Each line contains the following, separated by semicolons: The name of the client, the service sold (such as Dinner, Conference, Lodging, and so on), the amount of the sale, and the date of that event. Write a program that reads such a file and displays the total amount for each service category. Use the following data for your text file:5 pts Bob;Dinner;10.00;January 1, 2013 Tom;Dinner;14.00;January 2, 2013 Anne;Lodging;125.00;January 3, 2013 Jerry;Lodging;125.00;January...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT