Take-Home Lab #04 CS1020 – DATA STRUCTURES AND ALGORITHMS 1 1

advertisement
Take-Home Lab #04
CS1020 – DATA STRUCTURES AND ALGORITHMS 1
AY2015-16 SEMESTER 2
1

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
1
3
Dequeue
100
3
5
8
17
5
4
22
5
4
1
3
9
71
Head
Enqueue
Tail
Queue<E> = new LinkedList<E>();
http://docs.oracle.com/javase/8/docs/api/java/util/Queue.html
Stack and Queue
2

Interface Queue<E>
<<interface>> Queue<E>
- //see Java API
+ add(E) : boolean
+ peek() : E
+ poll() : E
…
Stack and Queue
3

Interface Queue<E>
<<interface>> Queue<E>
- //see Java API
add(E)
+ add(E) : boolean
+ peek() : E
+ poll() : E
…
Queue
Stack and Queue
4

Interface Queue<E>
<<interface>> Queue<E>
- //see Java API
poll()
+ add(E) : boolean
+ peek() : E
+ poll() : E
…
Queue
Stack and Queue
5

Class Stack<E>
Stack<E>
- elements: LinkedList<E>
+
+
+
+
+
push(E) : void
pop() : E
peek() : E
getSize() : int
isEmpty() : boolean
Stack and Queue
6

Class Stack<E>
Stack<E>
- elements: LinkedList<E>
+
+
+
+
+
1
push(E) : void
pop() : E
peek() : E
getSize() : int
isEmpty() : boolean
3
5
4
1
Stack and Queue
7
push(10)

Class Stack<E>
Stack<E>
- elements: LinkedList<E>
10
+
+
+
+
+
1
push(E) : void
pop() : E
peek() : E
getSize() : int
isEmpty() : boolean
3
5
4
1
Stack and Queue
8
peek()

Class Stack<E>
Returns 10
Stack<E>
- elements: LinkedList<E>
+
+
+
+
+
10
1
push(E) : void
pop() : E
peek() : E
getSize() : int
isEmpty() : boolean
3
5
4
1
Stack and Queue
9
pop()

Class Stack<E>
Returns 10
Stack<E>
- elements: LinkedList<E>
+
+
+
+
+
10
1
push(E) : void
pop() : E
peek() : E
getSize() : int
isEmpty() : boolean
3
5
4
1
Stack and Queue
10

Class Stack<E>
Stack<E>
- elements: LinkedList<E>
+
+
+
+
+
+
push(E) : void
pop() : E
peek() : E
getSize() : int
getIndex() : int
isEmpty() : boolean
public int getSize() {
return elements.size();
}
public boolean isEmpty() {
return this.getSize() == 0;
}
Stack and Queue
11
Problem 1
Swinging Monkeys
12

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
13

5 Trees: 19m – 17m – 20m – 20m – 20m
Output:
5
Swinging Monkeys
14

Naïve solution:
•
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
15
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
16

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
17

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
18
Property of the Sequence:
1.
2.
3.
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
19
Problem 2
Chemistry
20

Given a set of mappings and chemical formula:
•
Calculate the molecule mass of the formula
C
H
N
O
12
1
14
16
(NH4)2CO3
Problem Description
Chemistry
21

Let’s work on a few examples based on the given mapping
(NH4)2CO3
C
H
N
O
12
1
14
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
H
N
O
12
1
14
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
H
N
O
12
1
14
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
H
N
O
12
1
14
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
H
N
O
12
1
14
16
CH4OH
((CH3)CH4C3H8)4
Problem Description
Chemistry
26

Let’s work on a few examples based on the given mapping
36 + 60
C
H
N
O
12
1
14
16
CH4OH
((CH3)CH4C3H8)4
Problem Description
Chemistry
27

Let’s work on a few examples based on the given mapping
(NH4)2CO3
C
H
N
O
12
1
14
16
Mr = 96
CH4OH
((CH3)CH4C3H8)4
Problem Description
Chemistry
28

Let’s work on a few examples based on the given mapping
(NH4)2CO3
C
H
N
O
12
1
14
16
Mr = 96
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
C
H
N
O
12
1
14
16
Mr = 96
CH4OH
33
((CH3)CH4C3H8)4
Problem Description
Chemistry
30

C
H
N
O
Let’s work on a few examples based on the given mapping
12
1
14
16
(NH4)2CO3
Mr = 96
CH4OH
Mr = 33
((CH3)CH4C3H8)4
Problem Description
Chemistry
31

C
H
N
O
Let’s work on a few examples based on the given mapping
12
1
14
16
(NH4)2CO3
Mr = 96
CH4OH
Mr = 33
((CH3)CH4C3H8)4
12 + 3 x 1
Chemistry
32

C
H
N
O
Let’s work on a few examples based on the given mapping
12
1
14
16
(NH4)2CO3
Mr = 96
CH4OH
Mr = 33
((CH3)CH4C3H8)4
15
Chemistry
33

C
H
N
O
Let’s work on a few examples based on the given mapping
12
1
14
16
(NH4)2CO3
Mr = 96
CH4OH
Mr = 33
(15 + CH4C3H8)4
12 + 4 x 1 + 3 x 12 + 8 x 1
Chemistry
34

C
H
N
O
Let’s work on a few examples based on the given mapping
12
1
14
16
(NH4)2CO3
Mr = 96
CH4OH
Mr = 33
(15 + CH4C3H8)4
60
Chemistry
35

C
H
N
O
Let’s work on a few examples based on the given mapping
12
1
14
16
(NH4)2CO3
Mr = 96
CH4OH
Mr = 33
(15 + 60)4
Chemistry
36

C
H
N
O
Let’s work on a few examples based on the given mapping
12
1
14
16
(NH4)2CO3
Mr = 96
CH4OH
Mr = 33
((CH3)CH4C3H8)4
Mr = 300
Problem Description
Chemistry
37
?
What data structure should I use for:
HashMap
Mass
Mapping
Formula
Processing
Chemistry
Stack
38
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
39
What should my stack contain?
Mass of each Atom
OR
The Elements
Stack
https://docs.oracle.com/javase/8/docs/api/java/util/Stack.html
40
What should my stack contain?
Mass of each Atom
Stack
The Elements
We will use a stack of integers
CH4
Stack
https://docs.oracle.com/javase/8/docs/api/java/util/Stack.html
41
What should my stack contain?
Mass of each Atom
Stack
CH4
The Elements
We will use a stack of integers
12
Stack
https://docs.oracle.com/javase/8/docs/api/java/util/Stack.html
42
What should my stack contain?
Mass of each Atom
Stack
CH4
The Elements
We will use a stack of integers
1
12
Stack
https://docs.oracle.com/javase/8/docs/api/java/util/Stack.html
43
What should my stack contain?
Mass of each Atom
Stack
CH4
The Elements
We will use a stack of integers
4
1
12
Stack
https://docs.oracle.com/javase/8/docs/api/java/util/Stack.html
44
What should my stack contain?
Mass of each Atom
Stack
The Elements
We will use a stack of integers
Total = 12 + 4
= 16
CH4
4
1
12
Stack
https://docs.oracle.com/javase/8/docs/api/java/util/Stack.html
45
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
46
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
47
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
48
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
49
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
50
Visualization
CH4
-1
Stack
Chemistry
51
Visualization
CH4
Push The Mass of ‘C’
Into The Stack
12
-1
Stack
Chemistry
52
Visualization
CH4
Push The Mass of ‘H’
Into The Stack
1
12
-1
Stack
Chemistry
53
Visualization
CH4
Multiply top of stack by 4
1
12
-1
Stack
Chemistry
54
Visualization
CH4
Multiply top of stack by 4
4
12
-1
Stack
Chemistry
55
Visualization
CH4
Accumulate all values
4
12
4 + 12 = 16
-1
Stack
Chemistry
56
Visualization
N(CH2(CH3)2)3
-1
Stack
Chemistry
57
Visualization
N(CH2(CH3)2)3
Push The Mass of ‘N’
Into The Stack
14
-1
Stack
Chemistry
58
Visualization
N(CH2(CH3)2)3
Start New Session
-1
14
-1
Stack
Chemistry
59
Visualization
N(CH2(CH3)2)3
12
Push The Mass of ‘C’
Into The Stack
-1
14
-1
Stack
Chemistry
60
Visualization
N(CH2(CH3)2)3
1
12
Push The Mass of ‘H’
Into The Stack
-1
14
-1
Stack
Chemistry
61
Visualization
N(CH2(CH3)2)3
1
12
Multiply top of stack by 2
-1
14
-1
Stack
Chemistry
62
Visualization
N(CH2(CH3)2)3
2
12
Multiply top of stack by 2
-1
14
-1
Stack
Chemistry
63
Visualization
N(CH2(CH3)2)3
-1
2
12
Start New Session
-1
14
-1
Stack
Chemistry
64
Visualization
N(CH2(CH3)2)3
12
-1
2
12
Push The Mass of ‘C’
Into The Stack
-1
14
-1
Stack
Chemistry
65
Visualization
1
N(CH2(CH3)2)3
12
-1
2
12
Push The Mass of ‘H’
Into The Stack
-1
14
-1
Stack
Chemistry
66
Visualization
1
N(CH2(CH3)2)3
12
-1
2
12
Multiply Top Of Stack by 3
-1
14
-1
Stack
Chemistry
67
Visualization
3
N(CH2(CH3)2)3
12
-1
2
12
Multiply Top Of Stack by 3
-1
14
-1
Stack
Chemistry
68
Visualization
3
N(CH2(CH3)2)3
12
-1
2
12
Accumulate
-1
3 + 12 = 15
14
-1
Stack
Chemistry
69
Visualization
N(CH2(CH3)2)3
15
2
12
Push Result
-1
3 + 12 = 15
14
-1
Stack
Chemistry
70
Visualization
N(CH2(CH3)2)3
15
2
12
Multiply Top of Stack by 2
-1
14
-1
Stack
Chemistry
71
Visualization
N(CH2(CH3)2)3
30
2
12
Accumulate
-1
30 + 2 + 12 = 44
14
-1
Stack
Chemistry
72
Visualization
N(CH2(CH3)2)3
Push Result
44
30 + 2 + 12 = 44
14
-1
Stack
Chemistry
73
Visualization
N(CH2(CH3)2)3
Multiply Top of Stack by 3
44
14
-1
Stack
Chemistry
74
Visualization
N(CH2(CH3)2)3
Multiply Top of Stack by 3
132
14
-1
Stack
Chemistry
75
Visualization
N(CH2(CH3)2)3
Accumulate all values
132 + 14 = 146
132
14
-1
Stack
Chemistry
76

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
77
Problem 3
Cake
78
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
79
Ask yourself…
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
80
Legend
Green == No Raisin
Orange == Has Raisin
Number inside == num of Choc
Visualisation
Original Cake
1
2
10
2
3
4
5
Current Chocs  0
Max Chocs  0
Raisin Pieces Taken  0
Max Raisin Pieces  2
Cake
81
Legend
Green == No Raisin
Orange == Has Raisin
White == Taken
Number inside == num of Choc
Visualisation
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
82
Legend
Green == No Raisin
Orange == Has Raisin
White == Taken
Number inside == num of Choc
Visualisation
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
83
Legend
Green == No Raisin
Orange == Has Raisin
White == Taken
Number inside == num of Choc
Visualisation
Original Cake
2
Raisin piece. We
still have leeway
to take it
1
2
3
4
5
Current Chocs  13
Max Chocs  0
Raisin Pieces Taken  1
Max Raisin Pieces  2
10
Potential Take Home Slice
Cake
84
Visualisation
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
1
2
10
Current Chocs  15
Max Chocs  0
Raisin Pieces Taken  1
Max Raisin Pieces  2
2
Potential Take Home Slice
Cake
85
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
1
2
10
2
Current Chocs  18
Max Chocs  0
Raisin Pieces Taken  2
Max Raisin Pieces  2
3
Potential Take Home Slice
Cake
86
Visualisation
Legend
Green == No Raisin
Orange == Has Raisin
White == Taken
Number inside == num of Choc
Original Cake
5
Only chocolate, so
just take it
1
2
10
2
3
Current Chocs  22
Max Chocs  0
Raisin Pieces Taken  2
Max Raisin Pieces  2
4
Potential Take Home Slice
Cake
87
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
1
2
10
2
3
Current Chocs  22
Max Chocs  0
Raisin Pieces Taken  2
Max Raisin Pieces  2
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
Compare this slice against our
max chocolates so far and
record the higher value
1
2
10
2
3
Current Chocs  22
Max Chocs  22
Raisin Pieces Taken  2
Max Raisin Pieces  2
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
Now we need to remove the
first raisin piece so that we can
consider the new piece.
1
2
10
2
3
Current Chocs  22
Max Chocs  22
Raisin Pieces Taken  2
Max Raisin Pieces  2
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
To exclude the first raisin piece,
we need to also exclude all
pieces that come before it.
1
2
10
2
3
Current Chocs  22
Max Chocs  22
Raisin Pieces Taken  2
Max Raisin Pieces  2
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.
2
10
2
3
Current Chocs  21
Max Chocs  22
Raisin Pieces Taken  2
Max Raisin Pieces  2
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.
10
2
3
Current Chocs  19
Max Chocs  22
Raisin Pieces Taken  2
Max Raisin Pieces  2
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
Now that we have excluded the
first raisin piece, we have space
for the new raisin piece.
2
3
Current Chocs  9
Max Chocs  22
Raisin Pieces Taken  1
Max Raisin Pieces  2
4
Potential Take Home Slice
Cake
94
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
2
3
4
5
Potential Take Home Slice
Cake
Current Chocs  14
Max Chocs  22
Raisin Pieces Taken  2
Max Raisin Pieces  2
95
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.
2
3
4
5
Potential Take Home Slice
Cake
Current Chocs  14
Max Chocs  22
Raisin Pieces Taken  2
Max Raisin Pieces  2
96
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.
2
3
4
5
Potential Take Home Slice
Cake
Current Chocs  14
Max Chocs  22
Raisin Pieces Taken  2
Max Raisin Pieces  2
97
Visualisation
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
2
3
4
5
Max Chocs  22
Raisin Pieces Taken  2
Max Raisin Pieces  2
Potential Take Home Slice
Cake
98
Cake class
Main method:
◦ 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
99
Piece class
The encapsulation of the information on each piece
Attributes:
◦ raisin – boolean
◦ amountChocolate – int
Getters:
◦ hasRaisin()
◦ getChocolate()
Cake
100
Algorithm Sketch (1)
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
◦ Kept updated with every piece taken or removed from the slice
Cake
101
Algorithm Sketch (2)
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
102
End Of File
Any Questions?
103
Download