Download presentation
Presentation is loading. Please wait.
Published byKory Goodman Modified over 7 years ago
1
CS1020 – Data Structures And Algorithms 1 AY2015-16 Semester 2
Take-Home Lab #04 CS1020 – Data Structures And Algorithms 1 AY Semester 2
2
FIFO = First-In First-Out
Queues are “one-way”. Only insert from the back, can only take the head. (FIFO) FIFO = First-In First-Out Big “Queue of Stacks” 1 4 5 3 22 3 8 9 5 17 100 1 4 5 3 7 Dequeue Enqueue Elaborate on how Queue is an interface and using LinkedList is one way of using that interface since LinkedList in java implements the Queue Interface. Head Tail Queue<E> = new LinkedList<E>(); Stack and Queue
3
<<interface>> Queue<E>
//see Java API + add(E) : boolean + peek() : E + poll() : E … Stack and Queue
4
<<interface>> Queue<E>
//see Java API add(E) + add(E) : boolean + peek() : E + poll() : E … Queue Stack and Queue
5
<<interface>> Queue<E>
//see Java API poll() + add(E) : boolean + peek() : E + poll() : E … Queue Stack and Queue
6
Stack and Queue Class Stack<E> Stack<E>
elements: LinkedList<E> + push(E) : void + pop() : E + peek() : E + getSize() : int + isEmpty() : boolean Implement your own stack… Stack and Queue
7
1 Stack and Queue Class Stack<E> 1 3 5 4 Stack<E>
elements: LinkedList<E> + push(E) : void + pop() : E + peek() : E + getSize() : int + isEmpty() : boolean 1 3 5 Implement your own stack… 4 1 Stack and Queue
8
push(10) 1 Stack and Queue Class Stack<E> 10 1 3 5 4
elements: LinkedList<E> 10 + push(E) : void + pop() : E + peek() : E + getSize() : int + isEmpty() : boolean 1 3 5 4 1 Stack and Queue
9
peek() Returns 10 1 Stack and Queue Class Stack<E> 10 1 3 5 4
elements: LinkedList<E> 10 + push(E) : void + pop() : E + peek() : E + getSize() : int + isEmpty() : boolean 1 3 5 Elaborate on how peek returns 10 but the top of the stack stays inside the stack. 4 1 Stack and Queue
10
pop() Returns 10 1 Stack and Queue Class Stack<E> 10 1 3 5 4
elements: LinkedList<E> 10 + push(E) : void + pop() : E + peek() : E + getSize() : int + isEmpty() : boolean 1 3 5 Elaborate on how pop returns 10 and remove the top element 4 1 Stack and Queue
11
Stack and Queue Class Stack<E> Stack<E>
elements: LinkedList<E> public int getSize() { return elements.size(); } public boolean isEmpty() { return this.getSize() == 0; + push(E) : void + pop() : E + peek() : E + getSize() : int + getIndex() : int + isEmpty() : boolean Stack and Queue
12
Problem 1 Swinging Monkeys
13
Count the number of possible swings:
Monkeys can swing from one tree to another directly as long as there is no tree in between that is taller than or have the same height as either one of the two trees. Given the sequence of tree heights, determine the number of pair of trees that the monkeys can swing from and to. Swinging Monkeys
14
5 Trees: 19m – 17m – 20m – 20m – 20m Output: 5 Swinging Monkeys
15
Naïve solution: Swinging Monkeys
For all trees, count how many trees that the monkey can swing to from that tree. Maintain two for loops, one for the source and one for the destination: for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (canSwing(i,j)) { count++; } Swinging Monkeys
16
Swinging Monkeys private boolean canSwing(int from, int to) {
for (int i = from + 1; i < to; i++) { if (trees[i] >= Math.min(from, to)) { return false; } return true; Swinging Monkeys
17
Swinging Monkeys 5 Trees: 19m – 17m – 20m – 20m – 17m Observe:
from the tree before the Blue tree, the Monkey cannot jump to the tree after the Blue tree Swinging Monkeys
18
After we process tree i, we can forget all the trees before i that are shorter than i.
What will be the property of the sequence of trees that are not forgotten? Decreasing order from the tree with smallest index. Why? Suppose it is not decreasing in sequence: After we process Blue, we can forget Yellow. Yellow would have been removed from the sequence. Swinging Monkeys
19
Swinging Monkeys Property of the Sequence: Discussions:
Decreasing Order of Height At the start of the processing of the next tree, the Monkey can jump from all tree in the sequence to the next tree If the next tree is higher than some elements, these elements in the sequence cannot jump beyond the next tree Discussions: What Data Structure do we need to implement? Stack: why? Because we need to remember the previous elements in order Swinging Monkeys
20
Problem 2 Chemistry
21
Given a set of mappings and chemical formula:
Calculate the molecule mass of the formula C 12 H 1 N 14 O 16 (NH4)2CO3 Problem Description Chemistry 21
22
Let’s work on a few examples based on the given mapping
(NH4)2CO3 C 12 H 1 N 14 O 16 CH4OH ((CH3)CH4C3H8)4 Problem Description Chemistry 22
23
Let’s work on a few examples based on the given mapping
(NH4)2CO3 x 1 C 12 H 1 N 14 O 16 CH4OH ((CH3)CH4C3H8)4 Problem Description Chemistry 23
24
Let’s work on a few examples based on the given mapping
(NH4)2CO3 18 * 2 C 12 H 1 N 14 O 16 CH4OH ((CH3)CH4C3H8)4 Problem Description Chemistry 24
25
Let’s work on a few examples based on the given mapping
36 + CO3 x 16 C 12 H 1 N 14 O 16 CH4OH ((CH3)CH4C3H8)4 Problem Description Chemistry 25
26
Let’s work on a few examples based on the given mapping
36 + CO3 60 C 12 H 1 N 14 O 16 CH4OH ((CH3)CH4C3H8)4 Problem Description Chemistry 26
27
Let’s work on a few examples based on the given mapping
C 12 H 1 N 14 O 16 CH4OH ((CH3)CH4C3H8)4 Problem Description Chemistry 27
28
Let’s work on a few examples based on the given mapping
(NH4)2CO3 Mr = 96 C 12 H 1 N 14 O 16 CH4OH ((CH3)CH4C3H8)4 Problem Description Chemistry 28
29
Let’s work on a few examples based on the given mapping
(NH4)2CO3 Mr = 96 C 12 H 1 N 14 O 16 CH4OH x ((CH3)CH4C3H8)4 Problem Description Chemistry 29
30
Let’s work on a few examples based on the given mapping
(NH4)2CO3 Mr = 96 C 12 H 1 N 14 O 16 CH4OH 33 ((CH3)CH4C3H8)4 Problem Description Chemistry 30
31
Let’s work on a few examples based on the given mapping
(NH4)2CO3 Mr = 96 C 12 H 1 N 14 O 16 CH4OH Mr = 33 ((CH3)CH4C3H8)4 Problem Description Chemistry 31
32
Let’s work on a few examples based on the given mapping
(NH4)2CO3 Mr = 96 C 12 H 1 N 14 O 16 CH4OH Mr = 33 ((CH3)CH4C3H8)4 x 1 Chemistry 32
33
Let’s work on a few examples based on the given mapping
(NH4)2CO3 Mr = 96 C 12 H 1 N 14 O 16 CH4OH Mr = 33 ((CH3)CH4C3H8)4 15 Chemistry 33
34
Let’s work on a few examples based on the given mapping
(NH4)2CO3 Mr = 96 C 12 H 1 N 14 O 16 CH4OH Mr = 33 (15 + CH4C3H8)4 x x x 1 Chemistry 34
35
Let’s work on a few examples based on the given mapping
(NH4)2CO3 Mr = 96 C 12 H 1 N 14 O 16 CH4OH Mr = 33 (15 + CH4C3H8)4 60 Chemistry 35
36
Let’s work on a few examples based on the given mapping
(NH4)2CO3 Mr = 96 C 12 H 1 N 14 O 16 CH4OH Mr = 33 ( )4 Chemistry 36
37
Let’s work on a few examples based on the given mapping
(NH4)2CO3 Mr = 96 C 12 H 1 N 14 O 16 CH4OH Mr = 33 ((CH3)CH4C3H8)4 Mr = 300 Problem Description Chemistry 37
38
? Chemistry What data structure should I use for: Mass Mapping Formula
Processing HashMap Stack Chemistry
39
Setting Keys and Values
HashMap<K, V> hashMapName = new HashMap<K, V>(); HashMap HashMap<Character, Integer> massMapping = new HashMap<Character, Integer>(); Setting Keys and Values Retrieving Values massMapping.put(‘C’, 12); massMapping.get(‘C’); Returns 12 massMapping.put(‘H’, 1); massMapping.get(‘H’); Returns 1 massMapping.put(‘N’, 14); massMapping.get(‘N’); Returns 14
40
What should my stack contain?
Mass of each Atom The Elements OR Stack
41
CH4 Stack What should my stack contain?
Mass of each Atom The Elements Stack We will use a stack of integers CH4 Stack
42
CH4 Stack What should my stack contain?
Mass of each Atom The Elements Stack We will use a stack of integers CH4 12 Stack
43
CH4 Stack What should my stack contain?
Mass of each Atom The Elements Stack We will use a stack of integers 1 CH4 12 Stack
44
CH4 Stack What should my stack contain?
Mass of each Atom The Elements Stack We will use a stack of integers 1 4 CH4 12 Stack
45
CH4 Total = 12 + 4 = 16 Stack What should my stack contain?
Mass of each Atom The Elements Stack We will use a stack of integers Total = = 16 1 4 CH4 12 Stack
46
? Chemistry How do I store the formula? As a character array
String nextLine = sc.nextLine(); char[] formula = nextLine.toCharArray(); ? How do I process the formula? Loop through all characters processInput(formula); Chemistry
47
Chemistry public void run() { Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); sc.nextLine(); initializeMassMapping(sc, n); //implement it String nextLine = sc.nextLine(); char[] formula = nextLine.toCharArray(); processInput(formula); int total = accumulate(); //will be defined later System.out.println(total); sc.close(); } Chemistry
48
Chemistry private void processInput(char[] formula) {
for (char c : formula) { //what should I do??? } Next character can be one of these: What you should do if you encounter it: ( Open Bracket Start New “Session” ) Close Bracket Acummulate Current “Session” X Atom Name Push Its Mass n Number of atoms (or molecules) Multiply Top of The Stack by n Chemistry
49
Chemistry private void processInput(char[] formula) {
for (char c : formula) { if (c == '(') { //open bracket results.push(-1); //start a new “session” } else if (c == ')') { //close bracket int sum = accumulate(); //acummulate is a “helper” //then push the sum into the stack } else if (Character.isDigit(c)) {//it’s a number //multiply the top of the stack. How? } else { //then c must be a ??? //push the corresponding atom’s mass } Chemistry
50
Chemistry private int accumulate() { int result = 0;
int top = results.pop(); while (/* top is not -1 and stack is not empty */) { //add current top to result //update top to be next element in stack } return result; Chemistry
51
Visualization CH4 -1 Stack Chemistry
52
CH4 Visualization Chemistry Stack Push The Mass of ‘C’ Into The Stack
12 -1 Stack Chemistry
53
CH4 Visualization Chemistry Stack Push The Mass of ‘H’ Into The Stack
1 12 -1 Stack Chemistry
54
Visualization CH4 Multiply top of stack by 4 1 12 -1 Stack Chemistry
55
Visualization CH4 Multiply top of stack by 4 4 12 -1 Stack Chemistry
56
CH4 Visualization 4 + 12 = 16 Chemistry Stack Accumulate all values 4
-1 Stack Chemistry
57
Visualization N(CH2(CH3)2)3 -1 Stack Chemistry
58
N(CH2(CH3)2)3 Visualization Chemistry Stack Push The Mass of ‘N’
Into The Stack 14 -1 Stack Chemistry
59
Visualization N(CH2(CH3)2)3 Start New Session -1 14 -1 Stack Chemistry
60
N(CH2(CH3)2)3 Visualization Chemistry Stack Push The Mass of ‘C’
12 Push The Mass of ‘C’ Into The Stack -1 14 -1 Stack Chemistry
61
N(CH2(CH3)2)3 Visualization Chemistry Stack Push The Mass of ‘H’
1 12 Push The Mass of ‘H’ Into The Stack -1 14 -1 Stack Chemistry
62
N(CH2(CH3)2)3 Visualization Chemistry Stack Multiply top of stack by 2
1 12 Multiply top of stack by 2 -1 14 -1 Stack Chemistry
63
N(CH2(CH3)2)3 Visualization Chemistry Stack Multiply top of stack by 2
12 Multiply top of stack by 2 -1 14 -1 Stack Chemistry
64
N(CH2(CH3)2)3 Visualization Chemistry Stack Start New Session -1 2 12
14 -1 Stack Chemistry
65
N(CH2(CH3)2)3 Visualization Chemistry Stack Push The Mass of ‘C’
12 -1 2 12 Push The Mass of ‘C’ Into The Stack -1 14 -1 Stack Chemistry
66
N(CH2(CH3)2)3 Visualization Chemistry Stack Push The Mass of ‘H’
1 N(CH2(CH3)2)3 12 -1 2 12 Push The Mass of ‘H’ Into The Stack -1 14 -1 Stack Chemistry
67
Multiply Top Of Stack by 3
Visualization 1 N(CH2(CH3)2)3 12 -1 2 12 Multiply Top Of Stack by 3 -1 14 -1 Stack Chemistry
68
Multiply Top Of Stack by 3
Visualization 3 N(CH2(CH3)2)3 12 -1 2 12 Multiply Top Of Stack by 3 -1 14 -1 Stack Chemistry
69
N(CH2(CH3)2)3 Visualization Chemistry 3 + 12 = 15 Stack Accumulate 3
-1 2 12 Accumulate -1 = 15 14 -1 Stack Chemistry
70
N(CH2(CH3)2)3 Visualization Chemistry 3 + 12 = 15 Stack Push Result 15
-1 = 15 14 -1 Stack Chemistry
71
Multiply Top of Stack by 2
Visualization N(CH2(CH3)2)3 15 2 12 Multiply Top of Stack by 2 -1 14 -1 Stack Chemistry
72
N(CH2(CH3)2)3 Visualization Chemistry 30 + 2 + 12 = 44 Stack
Accumulate -1 = 44 14 -1 Stack Chemistry
73
N(CH2(CH3)2)3 Visualization Chemistry 30 + 2 + 12 = 44 Stack
Push Result 44 = 44 14 -1 Stack Chemistry
74
Multiply Top of Stack by 3
Visualization N(CH2(CH3)2)3 Multiply Top of Stack by 3 44 14 -1 Stack Chemistry
75
Multiply Top of Stack by 3
Visualization N(CH2(CH3)2)3 Multiply Top of Stack by 3 132 14 -1 Stack Chemistry
76
N(CH2(CH3)2)3 Visualization Chemistry 132 + 14 = 146 Stack
Accumulate all values 132 = 146 14 -1 Stack Chemistry
77
Summary Start a new session by pushing “-1” (or any other invalid mass values that you desire). Push the mass of each atom when you encounter them. Multiply top of stack each time you encounter a number. Accumulate all values (until stack is empty or you pop a “session start” value). When done iterating, sum all values in the stack (without counting the invalid value, of course). Chemistry
78
Problem 3 Cake
79
Cake Cake Your friend baked a long cake and cut it into pieces
Some pieces have raisins, which you hate You can only take home a contiguous slice of pieces You want to maximise the chocolate on your slice But you are limited to a certain number of raisin pieces Input: N – number of pieces of cake C – number of raisins pieces allowed Followed by N lines of: T – state of the piece (raisin or not) X – amount of chocolate on that piece Output the maximum amount of chocolate you can gain Cake
80
Ask yourself… Cake Store the original cake in what data structure?
Take one piece of cake at a time and check it If there is no raisin, then no problem If there is a raisin, are we allowed to simply take it? How to compare between different slices of cake? How to keep track of previous amounts of chocolate? Cake
81
Visualisation Cake 1 2 10 2 3 4 5 Current Chocs 0 Max Chocs 0
Legend Green == No Raisin Orange == Has Raisin Number inside == num of Choc Original Cake 1 2 10 2 3 4 5 Current Chocs 0 Max Chocs 0 Raisin Pieces Taken 0 Max Raisin Pieces 2 Cake
82
Visualisation Cake 2 10 2 3 4 5 1 Only chocolate, so just take it
Legend Green == No Raisin Orange == Has Raisin White == Taken Number inside == num of Choc Original Cake 2 10 2 3 4 5 Only chocolate, so just take it Current Chocs 1 Max Chocs 0 Raisin Pieces Taken 0 Max Raisin Pieces 2 1 Potential Take Home Slice Cake
83
Visualisation Cake 10 2 3 4 5 1 2 Only chocolate, so just take it
Legend Green == No Raisin Orange == Has Raisin White == Taken Number inside == num of Choc Original Cake 10 2 3 4 5 Only chocolate, so just take it Current Chocs 3 Max Chocs 0 Raisin Pieces Taken 0 Max Raisin Pieces 2 1 2 Potential Take Home Slice Cake
84
Visualisation Legend Green == No Raisin Orange == Has Raisin White == Taken Number inside == num of Choc Original Cake 2 3 4 5 Raisin piece. We still have leeway to take it Current Chocs 13 Max Chocs 0 Raisin Pieces Taken 1 Max Raisin Pieces 2 1 2 10 Potential Take Home Slice Cake
85
Visualisation Cake 3 4 5 1 2 10 2 Only chocolate, so just take it
Legend Green == No Raisin Orange == Has Raisin White == Taken Number inside == num of Choc Original Cake 3 4 5 Only chocolate, so just take it Current Chocs 15 Max Chocs 0 Raisin Pieces Taken 1 Max Raisin Pieces 2 1 2 10 2 Potential Take Home Slice Cake
86
Visualisation Legend Green == No Raisin Orange == Has Raisin White == Taken Number inside == num of Choc Original Cake 4 5 Raisin piece. We still have leeway to take it. But it’s the last one we can have in this slice Current Chocs 18 Max Chocs 0 Raisin Pieces Taken 2 Max Raisin Pieces 2 1 2 10 2 3 Potential Take Home Slice Cake
87
Visualisation Cake 5 1 2 10 2 3 4 Only chocolate, so just take it
Legend Green == No Raisin Orange == Has Raisin White == Taken Number inside == num of Choc Original Cake 5 Only chocolate, so just take it Current Chocs 22 Max Chocs 0 Raisin Pieces Taken 2 Max Raisin Pieces 2 1 2 10 2 3 4 Potential Take Home Slice Cake
88
Visualisation Legend Green == No Raisin Orange == Has Raisin White == Taken Number inside == num of Choc Original Cake 5 Raisin piece. We don’t have leeway to take it. What we have here is a potential take-home slice with a certain amount of chocolate Current Chocs 22 Max Chocs 0 Raisin Pieces Taken 2 Max Raisin Pieces 2 1 2 10 2 3 4 Potential Take Home Slice Cake
89
Visualisation Legend Green == No Raisin Orange == Has Raisin White == Taken Number inside == num of Choc Original Cake 5 Compare this slice against our max chocolates so far and record the higher value Current Chocs 22 Max Chocs 22 Raisin Pieces Taken 2 Max Raisin Pieces 2 1 2 10 2 3 4 Potential Take Home Slice Cake
90
Visualisation Legend Green == No Raisin Orange == Has Raisin White == Taken Number inside == num of Choc Original Cake 5 Now we need to remove the first raisin piece so that we can consider the new piece. Current Chocs 22 Max Chocs 22 Raisin Pieces Taken 2 Max Raisin Pieces 2 1 2 10 2 3 4 Potential Take Home Slice Cake
91
Visualisation Legend Green == No Raisin Orange == Has Raisin White == Taken Number inside == num of Choc Original Cake 5 To exclude the first raisin piece, we need to also exclude all pieces that come before it. Current Chocs 22 Max Chocs 22 Raisin Pieces Taken 2 Max Raisin Pieces 2 1 2 10 2 3 4 Potential Take Home Slice Cake
92
Visualisation Legend Green == No Raisin Orange == Has Raisin White == Taken Number inside == num of Choc Original Cake 5 To exclude the first raisin piece, we need to also exclude all pieces that come before it. Current Chocs 21 Max Chocs 22 Raisin Pieces Taken 2 Max Raisin Pieces 2 2 10 2 3 4 Potential Take Home Slice Cake
93
Visualisation Legend Green == No Raisin Orange == Has Raisin White == Taken Number inside == num of Choc Original Cake 5 To exclude the first raisin piece, we need to also exclude all pieces that come before it. Current Chocs 19 Max Chocs 22 Raisin Pieces Taken 2 Max Raisin Pieces 2 10 2 3 4 Potential Take Home Slice Cake
94
Visualisation Legend Green == No Raisin Orange == Has Raisin White == Taken Number inside == num of Choc Original Cake 5 Now that we have excluded the first raisin piece, we have space for the new raisin piece. Current Chocs 9 Max Chocs 22 Raisin Pieces Taken 1 Max Raisin Pieces 2 2 3 4 Potential Take Home Slice Cake
95
Visualisation Legend Green == No Raisin Orange == Has Raisin White == Taken Number inside == num of Choc Original Cake Take the raisin piece and add its chocolate amount Current Chocs 14 Max Chocs 22 Raisin Pieces Taken 2 Max Raisin Pieces 2 2 3 4 5 Potential Take Home Slice Cake
96
Visualisation Legend Green == No Raisin Orange == Has Raisin White == Taken Number inside == num of Choc Original Cake We have checked all the slices in the original cake. Now we have another potential take-home slice. Current Chocs 14 Max Chocs 22 Raisin Pieces Taken 2 Max Raisin Pieces 2 2 3 4 5 Potential Take Home Slice Cake
97
Visualisation Legend Green == No Raisin Orange == Has Raisin White == Taken Number inside == num of Choc Original Cake Compare the amount of chocolate in this slice with the max chocolate so far. There is no change in the max. Current Chocs 14 Max Chocs 22 Raisin Pieces Taken 2 Max Raisin Pieces 2 2 3 4 5 Potential Take Home Slice Cake
98
Visualisation Cake Max Chocs 22 2 3 4 5
Legend Green == No Raisin Orange == Has Raisin White == Taken Number inside == num of Choc Original Cake Since the cake has been fully checked, we just return the max chocolate amount, 22. Current Chocs 14 Max Chocs 22 Raisin Pieces Taken 2 Max Raisin Pieces 2 2 3 4 5 Potential Take Home Slice Cake
99
Cake class Cake Main method: Why queue?
Read in the inputs N and C For each of the N subsequent lines: Read in T and X Construct a Piece object that encapsulates these information Store the Piece objects in a queue Solve the question and print the output Why queue? FIFO We want to consider the Pieces in the same order that they were read in Can we use Stack instead? Why or why not? Cake
100
Piece class Cake The encapsulation of the information on each piece
Attributes: raisin – boolean amountChocolate – int Getters: hasRaisin() getChocolate() Cake
101
Algorithm Sketch (1) Cake
Refer to the diagrams when tracing this algorithm Keep track of the following variables: The allowed number of raisins Given in the question. This does not change Another Queue to hold the take-home slice Why queue? Because we need the FIFO property! Max chocolate amount so far Updated before we consider a new take-home slice Current chocolate amount in the take-home slice Kept updated with every piece taken or removed from the slice Raisin count in the take-home slice Cake
102
Algorithm Sketch (2) Cake Repeat until the cake queue is empty:
Dequeue the next cake piece If it has raisins: Increment the raisin count If we exceeded the allowed number of raisins: Compare the current chocolate against the max chocolate and take the higher value as the new max: use Math.max(a, b) Remove all pieces up to and including the first raisin piece from the take home slice. Decrement the current chocolate while removing. Reduce the raisin count by 1 after removing. Regardless of whether it has raisins: Increment the current chocolate amount with the piece’s amount Enqueue the piece into the take-home slice Finally return the higher value between the max chocolate and the current chocolate Cake
103
End Of File Any Questions?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.