0% found this document useful (0 votes)
3 views

Lab06

Lab Practice № 6 focuses on recursion and Java Collections Framework, specifically LinkedList and HashMap. Students are required to implement three programming problems: calculating power using recursion, finding indices of two numbers that sum to a target using HashMap, and managing web history with LinkedList. Submission guidelines include individual work, proper file naming, and penalties for late submissions.

Uploaded by

kienduong160
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)
3 views

Lab06

Lab Practice № 6 focuses on recursion and Java Collections Framework, specifically LinkedList and HashMap. Students are required to implement three programming problems: calculating power using recursion, finding indices of two numbers that sum to a target using HashMap, and managing web history with LinkedList. Submission guidelines include individual work, proper file naming, and penalties for late submissions.

Uploaded by

kienduong160
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/ 8

Lab Practice № 6:

Recursion, Java Collections Framework: LinkedList, HashMap

COMP1020: OOP, Algorithms, and Data Structures Week 06

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 followed.
• Your classes and methods should be appropriately commented. However, try to avoid making your code overly
busy (e.g., include a comment on every line).
• Variables, methods and classes should have meaningful names, and should be followed Java programming con-
vention.
• Academic honesty is required in all work you submit to be graded. Although you can discuss among yourself at
high level how to solve the lab problem, you should NOT copy or share your code with other students to avoid
plagiarism issues.
• Use the template provided to prepare your solutions.
• 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.

(a) No Canvas submission will get 0 point (of course).

(b) No CMS Autograder submission will get 20% deduction.


• Submit separate *.java file for each Lab problem with the exact file name specified in each lab question (do not
add your student ID or your name). For example: HelloWorld.java.
• Late submission of lab practice without an approved extension will incur the following penalties:

(a) 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).

(b) The instructor will deduct an additional 0.25 point per problem for each day past the deadline.

(c) 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 № 6 Page 1


Learning Outcome
Topics: Recursion, Java Collections Framework
Outcome: Acquire the skill of implementing recursive thinking in Java. Be able to define and use Java collections
framework such as LinkedList and HashMap

CMS Autograder
Direct access to this CMS lab is followed: https://www.cmsvinuni.online
Note: Due to the current limitation of the Autograder, you must comment out all the package declaration before submis-
sion.

Lab Practice № 6 Page 2


Figure 1: Example testcases of Problem 01

Problem 01: Recursion (35 pts)


[CMS Autograder is required] Write a program and name it Power.java: Implement a function to compute the power of a
number, xn , where x is the base and n is the exponent. The implementation must use recursion to calculate the result.
Input: Two values will be provided as input:

• A floating-point number x (−100.0 ≤ x ≤ 100.0), representing the base.

• An integer n (−104 ≤ n ≤ 104 ), representing the exponent.

Output: A single floating-point number representing the result of xn . The output should be precise up to 5 decimal
places.
Testcase See Figure 1

Problem 02: HashMap (35 pts)


[CMS Autograder is required]
FYI: HashMap: You learned that Arrays store items as an ordered collection, and you have to access them with an
index number (int type). A HashMap however, store items in "key/value" pairs, and you can access them by an index of
another type (e.g. a String).
One object is used as a key (index) to another object (value). It can store different types: String keys and Integer
values, or the same type, like: String keys and String values
Common methods in HashMap: See figure 02
Example of using HashMap: See figure 03
Your task: Write a program and name it Sum.java: Given an array of integers nums and an integer sum, return
indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
The implementation must use HashMap for efficient lookups as we iterate through the array, we store each number
and its index in the HashMap. For each new number, we check if its complement (i.e., target - currentNumber) already
exists in the HashMap. If found, we return the indices immediately; otherwise, we continue storing elements for future
lookups.
Input: Two values will be provided as input:

• A list of integers representing the array nums

• A single integer target, which represents the sum we need to find.

Output: A list containing two indices whose corresponding values in nums add up to target.
Testcase See Figure 3

Lab Practice № 6 Page 3


Figure 2: Common methods in HashMap

Lab Practice № 6 Page 4


Figure 3: Example of using HashMap

Problem 03 - LinkedList (30 pts)


[CMS Autograder is required] Write a program and name it WebHistory.java: You are given a simple web browser with
a single tab that starts on a homepage. The browser allows you to navigate to new URLs, move backward through
previously visited pages, and move forward if possible.
Implement the WebHistory class with the following functionalities:

• WebHistory(String homepage): Initializes the browser with the given homepage.

• void visit(String url): Navigates to the specified URL from the current page. This action removes all forward
history.

• String back(int steps): Moves back by the given number of steps in history. If there are fewer available pages
than the requested steps, go as far back as possible. Returns the current page after moving.

• String forward(int steps): Moves forward by the given number of steps in history. If there are fewer available
pages than the requested steps, go as far forward as possible. Returns the current page after moving.

Complete the problem by filling in the "TODO" sections.

1 import java . util .*;


2
3 class WebHistory {
4 private LinkedList < String > history ;
5 private int currIndex ;
6

Lab Practice № 6 Page 5


Figure 4: Example testcases of Problem 02

7 // currIndex keeps track of the current position in the browsing history .


8 public WebHistory ( String homepage ) {
9 history = new LinkedList < >() ;
10 history . add ( homepage ) ;
11 currIndex = 0;
12 }
13
14 public void visit ( String url ) {
15 // TODO : Implement the visit method
16 // This method should take a URL as input and navigate to it .
17 // When visiting a new URL , clear all forward history
18 // Example :
19 // Suppose the user visits pages in this order :
20 // A = > B = > C ( Current page : " C " )
21 // If the user clicks ’ Back ’ twice , they move to " A " ( Current page : " A " ) .
22 // Now , if the user visits " D " :
23 // - The forward history ( " B " and " C " ) is cleared .
24 // - The history now looks like : [ " A " , " D " ] ( Current page : " D " ) .
25 // - The user cannot move forward to " B " or " C " anymore .
26 // This ensures that when a new URL is visited , any previously stored ←-
forward pages are removed .
27 }
28
29 public String back ( int steps ) {
30 // TODO : Implement the back method
31 // This method should move ’ steps ’ back in history .
32 // If ’ steps ’ is greater than the available history , move as far back as ←-
possible .
33 // Return the current page after moving back .
34 return " " ;
35 }
36
37 public String forward ( int steps ) {
38 // TODO : Implement the forward method

Lab Practice № 6 Page 6


39 // This method should move ’ steps ’ forward in history .
40 // If ’ steps ’ is greater than the available forward history , move as far ←-
forward as possible .
41 // Return the current page after moving forward .
42 return " " ;
43 }
44
45 public static void main ( String [] args ) {
46 Scanner scanner = new Scanner ( System . in ) ;
47
48 // Read commands input
49 String commandInput = scanner . nextLine () ;
50 String [] commands = commandInput . replaceAll ( " [\\[\\]\"] " , " " ) . split ( " ," ) ;
51
52 // Read parameters input
53 String paramInput = scanner . nextLine () ;
54 paramInput = paramInput . substring (1 , paramInput . length () - 1) ; // Remove ←-
outer brackets
55
56 String [] paramGroups = paramInput . split ( " ] ,\\[ " ) ;
57 Object [][] parameters = new Object [ paramGroups . length ][];
58
59 for ( int i = 0; i < paramGroups . length ; i ++) {
60 String param = paramGroups [ i ]. replace ( " [ " , " " ) . replace ( " ] " , " " ) .←-
replace ( " \" " , " " ) ;
61 if ( param . matches ( " -?\\ d + " ) ) { // If it ’s an integer
62 parameters [ i ] = new Object []{ Integer . parseInt ( param ) };
63 } else {
64 parameters [ i ] = new Object []{ param }; // It ’s a URL
65 }
66 }
67
68 scanner . close () ;
69
70 // Process commands
71 List < Object > output = new ArrayList < >() ;
72 WebHistory browser = null ;
73
74 for ( int i = 0; i < commands . length ; i ++) {
75 switch ( commands [ i ]) {
76 case " BrowserHistory " :
77 browser = new WebHistory (( String ) parameters [ i ][0]) ;
78 output . add ( null ) ;
79 break ;
80 case " visit " :
81 browser . visit (( String ) parameters [ i ][0]) ;
82 output . add ( null ) ;

Lab Practice № 6 Page 7


83 break ;
84 case " back " :
85 output . add ( browser . back (( Integer ) parameters [ i ][0]) ) ;
86 break ;
87 case " forward " :
88 output . add ( browser . forward (( Integer ) parameters [ i ][0]) ) ;
89 break ;
90 }
91 }
92
93 System . out . println ( output ) ;
94 }
95 }

Input: The input consists of two lists:

• A list of commands that represent the sequence of operations to be performed on the BrowserHistory class.

• A list of parameters that correspond to each command.

Output: The output is a list of results corresponding to each command.

Figure 5: Example of Test case for Problem 03

Lab Practice № 6 Page 8

You might also like