CS1020 – Data Structures And Algorithms 1 AY2015-16 Semester 2 Take-Home Lab #04 CS1020 – Data Structures And Algorithms 1 AY2015-16 Semester 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>(); http://docs.oracle.com/javase/8/docs/api/java/util/Queue.html Stack and Queue
<<interface>> Queue<E> //see Java API + add(E) : boolean + peek() : E + poll() : E … Stack and Queue
<<interface>> Queue<E> //see Java API add(E) + add(E) : boolean + peek() : E + poll() : E … Queue Stack and Queue
<<interface>> Queue<E> //see Java API poll() + add(E) : boolean + peek() : E + poll() : E … Queue Stack and Queue
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
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
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
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
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
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
Problem 1 Swinging Monkeys
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
5 Trees: 19m – 17m – 20m – 20m – 20m Output: 5 Swinging Monkeys
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
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
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
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
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
Problem 2 Chemistry
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
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
Let’s work on a few examples based on the given mapping (NH4)2CO3 14 + 4 x 1 C 12 H 1 N 14 O 16 CH4OH ((CH3)CH4C3H8)4 Problem Description Chemistry 23
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
Let’s work on a few examples based on the given mapping 36 + CO3 12 + 3 x 16 C 12 H 1 N 14 O 16 CH4OH ((CH3)CH4C3H8)4 Problem Description Chemistry 25
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
Let’s work on a few examples based on the given mapping 36 + 60 C 12 H 1 N 14 O 16 CH4OH ((CH3)CH4C3H8)4 Problem Description Chemistry 27
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
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 12 + 4 x 1 + 16 + 1 ((CH3)CH4C3H8)4 Problem Description Chemistry 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 33 ((CH3)CH4C3H8)4 Problem Description Chemistry 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 Mr = 33 ((CH3)CH4C3H8)4 Problem Description Chemistry 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 12 + 3 x 1 Chemistry 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 15 Chemistry 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 (15 + CH4C3H8)4 12 + 4 x 1 + 3 x 12 + 8 x 1 Chemistry 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 60 Chemistry 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 + 60)4 Chemistry 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 ((CH3)CH4C3H8)4 Mr = 300 Problem Description Chemistry 37
? Chemistry What data structure should I use for: Mass Mapping Formula Processing HashMap Stack Chemistry
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 https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html
What should my stack contain? Mass of each Atom The Elements OR Stack https://docs.oracle.com/javase/8/docs/api/java/util/Stack.html
CH4 Stack What should my stack contain? Mass of each Atom The Elements Stack We will use a stack of integers CH4 Stack https://docs.oracle.com/javase/8/docs/api/java/util/Stack.html
CH4 Stack What should my stack contain? Mass of each Atom The Elements Stack We will use a stack of integers CH4 12 Stack https://docs.oracle.com/javase/8/docs/api/java/util/Stack.html
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 https://docs.oracle.com/javase/8/docs/api/java/util/Stack.html
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 https://docs.oracle.com/javase/8/docs/api/java/util/Stack.html
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 = 12 + 4 = 16 1 4 CH4 12 Stack https://docs.oracle.com/javase/8/docs/api/java/util/Stack.html
? 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
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
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
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
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
Visualization CH4 -1 Stack Chemistry
CH4 Visualization Chemistry Stack Push The Mass of ‘C’ Into The Stack 12 -1 Stack Chemistry
CH4 Visualization Chemistry Stack Push The Mass of ‘H’ Into The Stack 1 12 -1 Stack Chemistry
Visualization CH4 Multiply top of stack by 4 1 12 -1 Stack Chemistry
Visualization CH4 Multiply top of stack by 4 4 12 -1 Stack Chemistry
CH4 Visualization 4 + 12 = 16 Chemistry Stack Accumulate all values 4 -1 Stack Chemistry
Visualization N(CH2(CH3)2)3 -1 Stack Chemistry
N(CH2(CH3)2)3 Visualization Chemistry Stack Push The Mass of ‘N’ Into The Stack 14 -1 Stack Chemistry
Visualization N(CH2(CH3)2)3 Start New Session -1 14 -1 Stack Chemistry
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
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
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
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
N(CH2(CH3)2)3 Visualization Chemistry Stack Start New Session -1 2 12 14 -1 Stack Chemistry
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
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
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
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
N(CH2(CH3)2)3 Visualization Chemistry 3 + 12 = 15 Stack Accumulate 3 -1 2 12 Accumulate -1 3 + 12 = 15 14 -1 Stack Chemistry
N(CH2(CH3)2)3 Visualization Chemistry 3 + 12 = 15 Stack Push Result 15 -1 3 + 12 = 15 14 -1 Stack Chemistry
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
N(CH2(CH3)2)3 Visualization Chemistry 30 + 2 + 12 = 44 Stack Accumulate -1 30 + 2 + 12 = 44 14 -1 Stack Chemistry
N(CH2(CH3)2)3 Visualization Chemistry 30 + 2 + 12 = 44 Stack Push Result 44 30 + 2 + 12 = 44 14 -1 Stack Chemistry
Multiply Top of Stack by 3 Visualization N(CH2(CH3)2)3 Multiply Top of Stack by 3 44 14 -1 Stack Chemistry
Multiply Top of Stack by 3 Visualization N(CH2(CH3)2)3 Multiply Top of Stack by 3 132 14 -1 Stack Chemistry
N(CH2(CH3)2)3 Visualization Chemistry 132 + 14 = 146 Stack Accumulate all values 132 132 + 14 = 146 14 -1 Stack Chemistry
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
Problem 3 Cake
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
Piece class Cake The encapsulation of the information on each piece Attributes: raisin – boolean amountChocolate – int Getters: hasRaisin() getChocolate() Cake
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
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
End Of File Any Questions?