The lab is designed to provide extra questions for you to practise and as such you are not expected to finish the lab during our lab session. We recommend that you do eventually complete the lab on your own time. |
1. Key-Value pairs
We would like to design a program that implements a KVPair
. [1] A KVPair
contains pairs as elements. We will use {< >}
to represent an empty KVPair
and (k,v)
to represent a pair.
-
The first element of the pair
k
is called a key. -
the second element of the pair
v
is called a value.
So a KVPair
holds key-value pairs. We would like to create a KVPair
that has Point
s as keys and Shape
s as values. You can reuse your code for Point
and Shape
from previous Lectures/Labs/Assignments.
Here is a table of the operations along with their specifications and comments.
Operation | Specification | Comments |
---|---|---|
|
|
|
|
{<>}.isEmpty() = true {<(k,v), (k1,v1), ...>}.isEmpty() = false |
|
|
{<>}.size() = 0 {<(k,v), (k1,v1), ...>}.size() = 1 + {<{k1,v1,...>}.size() |
|
|
{<>}.add(a,b) = {<(a,b)>} {<(k,v), (k1,v1), ...>}.add(a,b) = {<(a,b), (k,v), (k1,v1),...>} |
|
|
{<>}.replace(a,b) = {<>} {<(a,c), (k1,v1), ...>}.replace(a,b) = {<(a,b),(k1,v1),...>} {<(x,c), (k1,v1), ...>}.replace(a,b) = {(k1,v1),...>}.replace(a,b).add(x,c) |
|
|
{<>}.delete(x) = {<>} {<(x,v), (k1,v1), ...>}.delete(x) = {<(k1,v1), ...>} {<(y,v), (k1,v1), ...>}.delete(x) = {<(k1,v1), ...>}.delete(x).add(y,v) |
|
|
{<>}.has(x) = false {<(x,v), (k1,v1), ...>}.has(x) = true {<(y,v), (k1,v1), ...>}.has(x) = {<(k1,v1), ...>}.has(x) |
|
|
{<>}.get(x) = ERROR {<(x,v), (k1,v1), ...>}.get(x) = v {<(y,v), (k1,v1), ...>}.get(x) = {<(k1,v1), ...>}.get(x) |
|
2. Binary Trees
An Integer BinaryTree (IBT) comprises of a leaf or a node. Both a leaf and a node contain an integer value. A node however also contains two sub trees called the left and the right subtree.
Here are some examples of IBTs
Ex1 | Ex2 | Ex3 |
---|---|---|
We would like to create a string representation of our our IBTs using the following rules
-
For a leaf create a string with
-
the integer value inside the leaf
-
-
For a node create a string with
-
a left parenthesis first.
-
the integer value stored at this node.
-
a space.
-
its left-subtree.
-
a space
-
the right subtree.
-
a right parenthesis.
-
The table below shows how the IBTs from above get printed out
Pretty print Leaf example |
Pretty print Node example |
Pretty print Node example |
|
|
|