0% found this document useful (0 votes)
34 views6 pages

COMP1020 2023 Lab13

y to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et

Uploaded by

Dũng Minh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views6 pages

COMP1020 2023 Lab13

y to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et

Uploaded by

Dũng Minh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Lab Practice № 13:

Trees and Search Trees, Heaps, Hashing

COMP1020: OOP and Data Structures Spring 2023 - Week 15, June 5, 2023

Lab Practice Submission Instructions:


• This is an individual lab practice and will typically be assigned in the computer laboratory.
• Your program should work correctly on all inputs. If there are any specifications about how the
program should be written (or how the output should appear), those specifications should be fol-
lowed.
• Your code and functions/modules should be appropriately commented. However, try to avoid mak-
ing your code overly busy (e.g., include a comment on every line).
• Variables and functions should have meaningful names, and code should be organized into func-
tions/methods where appropriate.
• Academic honesty is required in all work you submit to be graded. You should NOT copy or share
your code with other students to avoid plagiarism issues.
• Use the template provided to prepare your solutions (modified to provide your student ID, your
name, etc).
• You should upload your .java file(s) to both the Canvas and CMS Autograder before the end of
the laboratory session unless the instructor gave a specified deadline. No Canvas or No CMS
Autograder submission will get 0 point.
• Submit separate .java file for each lab problem with the exact file name specified in each lab
question. For example: HelloWorld.java.
• Late submission of lab practice without an approved extension will incur the following penalties:

1. No submission by the deadline will incur 0.25 point deduction for each problem (most of the
problems are due at the end of the lab session).
2. The instructor will deduct an additional 0.25 point per problem for each day past the deadline.
3. The penalty will be deducted until the maximum possible score for the lab practice reaches
zero (0%) unless otherwise specified by the instructor.

Lab Practice № 13 Page 1


Problem 1: Word Frequency Counter (30pts)
You are given a list of words in a form of a string. Your task is to count the frequency of each word
and store it in a data structure. You need to implement a class WordFrequency.java which has a
countWordFrequency method that takes a list of words as input and returns a data structure containing
each word as a key and its frequency as the corresponding value. In the countWordFrequency method:

• Create the chosen data structure to store the word frequencies.

• Iterate over the list of words and for each word, update its frequency in the data structure. If the
word is already present in the data structure, increment its frequency by 1. If the word is not
present, add it to the data structure with a frequency of 1.

After iterating over all the words, return the data structure containing the word frequencies in increasing
order based on the word. In case-sensitive sorting, capital letters are considered smaller than non-capital
letters.

Input: A string containing a number of words separated by spaces.

Output: The word frequencies are printed in separate lines, with each line showing the word followed by
its frequency in the form of <word: frequency>.

Test cases:

Table 1: Sample input and output for Word Frequency Counter.

Input Output
programming is fun and challenging programming is creative and: 1
challenging: 1
creative: 1
fun: 1
is: 2
programming: 2

Lab Practice № 13 Page 2


Problem 2: Expression Tree (30pts)
1. Create a program ExpressionEvaluator.java that contains the following methods:

• constructBinaryTree(expression: String): This method takes a string expression rep-


resenting a mathematical expression in postfix notation and constructs a binary tree from it.
• getInfixExpression(): String: This method returns the infix expression obtained by per-
forming an inorder traversal of the constructed binary tree.

2. You can implement the constructBinaryTree method as follows:

• Split the expression string into individual tokens using space as the delimiter.
• Initialize an empty stack to store the tree nodes.
• Iterate through each token in the expression:
– If the token is an operator (+, -, *, /), pop two nodes from the stack to be the left and
right children of a new operator node. Push the operator node back onto the stack.
– If the token is an operand, create a new operand node and push it onto the stack.
• The final node remaining on the stack will be the root of the constructed binary tree.

3. In the main method, you should read the postfix expression from the input and then output the infix
expression and the result of the expression.

Please note that the implementation assumes valid postfix expressions and does not handle error cases
such as invalid expressions or division by zero.
Input: The postfix expression as a string, each character separated by space.

Output: The output should include two lines: the first line is the infix expression and the second line is
the result of the expression.

Test Cases:

Table 2: Sample input and output for the Expression Tree program.

Input Output
23*45*+6- (((2*3)+(4*5))-6)
20

Listing 1: Problem 2 Skeleton


import java . util . Scanner ;
import java . util . Stack ;

class Node {
String data ;
Node left ;
Node right ;
Node ( String data ) {
this . data = data ;
this . left = null ;

Lab Practice № 13 Page 3


this . right = null ;
}
}

public class ExpressionEvaluator {


private Node constructBinaryTree ( String postfix ) {
Stack < Node > stack = new Stack < >() ;

for ( String token : postfix . split ( " " ) ) {


if ( isOperator ( token ) ) {
// TODO : pop two nodes from the stack to be the left and
// right children of a new operator node .
// TODO : Push the operator node back onto the stack
} else {
// TODO : create a new operand node and push it onto the stack .
}
}
// TODO : return sth
}

private boolean isOperator ( String token ) {


// TODO : check whether the token is operator + - * /
}

private String infixExpression ( Node root ) {


// TODO : returns the infix expression obtained by performing
// an inorder traversal of the constructed binary tree
}

private int evaluateExpression ( Node root ) {


// TODO : Recursive calls to evaluate left and right subtrees

// TODO : Evaluate the current operator and return the result

public static void main ( String [] args ) {


Scanner scanner = new Scanner ( System . in ) ;
String postfix = scanner . nextLine () ;

E xpressionEvaluator evaluator = new ExpressionEvaluator () ;


Node root = evaluator . constructBinaryTree ( postfix ) ;
String infix = evaluator . infixExpression ( root ) ;
int result = evaluator . evaluateExpression ( root ) ;

System . out . println ( infix ) ;


System . out . println ( result ) ;

scanner . close () ;
}
}

Lab Practice № 13 Page 4


Problem 3: Finding the Kth Wealthiest Person (30 pts)
Problem Description: You are given a list of individuals belonging to a wealthy family, Family A, along
with their names and the total value of properties they own. Your goal is create a program (FindKthWealthiest.java)
to find the k-th wealthiest person from Family A and display their name and property value.
Instructions:

1. Define the FamilyMember class with the following attributes:


– name: String representing the name of the family member.
– propertyValue: Integer representing the total value of properties the family member owns.

2. Implement the HeapSort class with the following methods:


– heapify: Performs the heapify operation on the given array of FamilyMember objects to maintain
the max heap property.
– swap: Swaps two elements in the array.
– heapSort: Sorts the array of FamilyMember objects using the Heap Sort algorithm.

3. Create the FindKthWealthiest class with the main function as follows:


– Create an array of FamilyMember objects based on the input values.
– Sort the array of family members using the heapSort method from the HeapSort class. Then,
retrieve the name and property value of the k-th wealthiest person from the sorted array.

Input:
– The first line contains two integers, N and k, representing the number of family members and the po-
sition of the kth wealthiest person, respectively.
– The next N lines contain the name and property value of each family member separated by a semicolon.

Output: The name and property value of the k-th wealthiest person, separated by space. If k is not valid,
print "Invalid". In case of a tie in property value, the person with the lexicographically smallest name
should be selected.

Test Cases:

Table 3: Sample input and output for the FindKthWealthiest program.

Input Output
66
Adam;100000
Eve;200000
Sam;300000 Adam 100000
Julia;400000
Max;500000
Sophia;600000
64
Alice;800000
Charlie;600000
Bob;600000 Bob 600000
David;700000
Eve;800000
Frank;500000

Lab Practice № 13 Page 5


Listing 2: Problem 3 skeleton
import java . util .*;

class FamilyMember {
String name ;
int propertyValue ;

public FamilyMember ( String name , int propertyValue ) {


this . name = name ;
this . propertyValue = propertyValue ;
}
}

class HeapSort {
// Implement the heapify method
public static void heapify ( FamilyMember [] arr , int n , int i ) {
// TODO : Implement heapify logic
}

// Implement the swap method


public static void swap ( FamilyMember [] arr , int i , int j ) {
// TODO : Implement swap logic
}

// Implement the heapSort method


public static void heapSort ( FamilyMember [] arr ) {
// TODO : Implement heapSort logic
}
}

public class FindKthWealthiest {


public static void main ( String [] args ) {
Scanner scanner = new Scanner ( System . in ) ;

int N = scanner . nextInt () ;


int k = scanner . nextInt () ;
scanner . nextLine () ; // Consume the newline

FamilyMember [] familyMembers = new FamilyMember [ N ];

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


// TODO : read each member ’s information .
}

// TODO : Print the name and property value of the kth wealthiest ←-
person .

scanner . close () ;
}
}

Lab Practice № 13 Page 6

You might also like