abstract data structures
abstract data structures
As with one dimensional arrays, we have a couple of methods of declaring static 2D arrays with Java.
Method 1
Method 2
numbers[0][0] = 25;
numbers[0][1] = 10;
numbers[0][2] = 5;
numbers[1][0] = 4;
numbers[1][1] = 6;
numbers[1][2] = 13;
numbers[2][0] = 45;
numbers[2][1] = 90;
numbers[2][2] = 78;
2D array questions
A teacher has decided to use a 2D array to store the marks for one of their classes. The grade book takes the
following form:
Convert the above into a suitable 2D array then write code to determine the following
TODO:
Recursion defines the solution to a problem in terms of itself. It is used to create looping behaviour without
actually using a loop construct. To that end, any recursive algorithm can be solved iteratively, and vice-versa.
A simple example to illustrate recursion is calculating the factorial of a number. As a reminder, a factorial is
the product of an integer and all the positive integers below it. The factorial of the number 4 is 4 x 3 x 2 x 1
which is 24. This may be calculated using a recursive or iterative approach as follows:
# Iterative solution
def factorial(n):
value = 1
while n > 0:
value = value * n
n = n - 1
return value
# Recursive solution
def factorial(n):
if n > 1:
return n * factorial(n-1) # Notice the function is calling itself!
else:
return n
● Ab ase case: a point at which the recursion will stop because the most basic endpoint has been
reached, so a simple answer can be given.
● A t est: to determine if we have reached the base case. If we don't have a test, our recursive loop could
go for infinity.
In a recursive algorithm, the computer "remembers" every previous state of the problem. This information is
"held" by the computer on the "activation stack" (i.e., inside each function's memory workspace). Every
function has its own workspace for every call of the function.
Recursive functionality particularly suit some types of problems. It can make algorithms a lot more elegant
than the iterative equivalent. The trade off, however, is that stack space is limited and the computer will only
be able to recurse so many times before it runs out of memory.
2.1 Factorials
Without worrying about the programming, focusing just on the pseudo code
logic, how would you create a fractal drawing algorithm?
Only once you are satisfied with your pseudo code and trace table should you attempt the code
implementation. This is the Java version from https://rosettacode.org/wiki/Fractal_tree#Java
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
private void drawTree(Graphics g, int x1, int y1, double angle, int depth) {
if (depth == 0) return;
int x2 = x1 + (int) (Math.cos(Math.toRadians(angle)) * depth * 10.0);
int y2 = y1 + (int) (Math.sin(Math.toRadians(angle)) * depth * 10.0);
g.drawLine(x1, y1, x2, y2);
drawTree(g, x2, y2, angle - 20, depth - 1);
drawTree(g, x2, y2, angle + 20, depth - 1);
}
@Override
public void paint(Graphics g) {
g.setColor(Color.BLACK);
drawTree(g, 400, 500, -90, 9);
}
drawFlake(200,4)
2.4 Fibonacci
The fibonacci sequence is where each number is the sum of the previous two numbers.
The first few numbers in the sequence is: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144
Determine the pseudo code, do a trace table test of your algorithm, then code it in Java.
● We are finished when the entire tower has been moved to another peg.
● We can only move one disk at a time.
● We can never place a larger disk on a smaller one.
(note: you'd very quickly find solutions online... while I can't stop you, I emphasis this would deprive yourself
of the learning experience the problem solving brings)
Here is an array of 50 sorted names you can use for your binary search.
String[] names =
{"Aaliyah","Abigail","Adalyn","Aiden","Alexander","Amelia","Aria","Aubrey","Ava","Av
ery","Benjamin","Caden","Caleb","Carter","Charlotte","Chloe","Daniel","Elijah","Emil
y","Emma","Ethan","Evelyn","Grayson","Harper","Isabella","Jack","Jackson","Jacob","J
ames","Jayden","Kaylee","Layla","Liam","Lily","Logan","Lucas","
Luke","Madelyn","Madi
son","Mason","Mia","Michael","Noah","Oliver","Olivia","Riley"," Ryan","Sophia","Willi
am","Zoe"};
2.7 Sudoku
If you’ve completed a number of the above and are looking for a challenge, the popular numbers game of
Sudoku is actually a recursive puzzle. Can you write an algorithm that will solve it? Check the Sudoku
algorithm explainer on wikipedia.
3. Data structures overview
An abstract data structure:
● Uses the principle of abstraction. You create a model to represent data in the form you require, and
hide the " behind the scenes" complexity of how it functions.
● Uses dynamic memory allocation to resize the data structure as required.
Dynamic Static
Memory is allocated as the program runs. Memory size is fixed, and is set at time of
compilation.
Advantage: Makes most efficient use of Disadvantage: Potentially wasted memory space.
memory, uses only what is required.
Inserting a node
To insert a new node into an existing list involves:
1. Create the new node with the intended value
2. Adjust the pointers of the existing nodes so it becomes part of the chain
Deleting a node
To delete a node from a list involves:
1. Save a reference to the target node into a temporary variable
2. Update the chain of node pointers so the target node is no longer in the list
3. USe the temporary reference to delete the target node from memory
● addHead( value ) - add a node with this value to the front of the list
● addTail( value ) - add a node with this value to the end of the list
● addAt( value, index ) - add a node with this value to this specific place in the list
● add( value ) - same as addTail()
● insert( value ) - in order insertion
● delete( value ) - find this value in the list and delete it
● list()
● getNext() - advance pointer to next item in the list
● resetNext() - returns to the beginning of the list
● hasNext() - returns true/false if there is a next item
● isEmpty()
● isFull()
The Node class forms the basis of the internal data structure for the linked list.
Node(int value) {
this.value = value;
this.next = null;
}
public int g
etValue() {
return value;
}
The LinkedList class is a container for Node objects, and contains methods for the programmer to use to
access and mutate the data in a more organised way, similar to an ArrayList.
public LinkedList() {
head = new Node(-1); // Dummy value that we will just ignore
listCount = 0;
}
public v
oid addTail(int val) {
// T ODO: Code this yourself
}
public v
oid addHead(int val) {
// T ODO: Code this yourself
}
public int s
ize() {
return listCount;
}
class Main {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.addSorted(5);
list.addSorted(10);
list.addSorted(15);
list.addSorted(30);
list.addSorted(40);
list.addSorted(45);
list.addSorted(20);
System.out.println(list);
}
}
A stack is a LIFO (last in, first out) data structure with the following methods:
A real world example of the stack is your undo buffer in an editing program.
import java.util.LinkedList;
public MyStack() {
list = new LinkedList();
}
Real world examples of the queue are your networking buffer, keyboard buffer or printing queue.
import java.util.LinkedList;
public MyQueue() {
list = new LinkedList();
}
If we wanted to implement our own stack or queue, in addition to using a dynamic structure such as the
LinkedList like we used above, we can make one quite easily using an object that used a static array as an
instance variable.
2. For any given string, use a stack to determine if every opening parenthesis is matched with a closing
parenthesis.
3. What does the following code fragment print when n is 50? Give a high-level description of what the
code fragment does when presented with a positive integer n.
void f unc(int n) {
MyQueue q = new MyQueue();
q.enqueue(0);
q.enqueue(1);
for (int i = 0; i < n; i++) {
int a = q.dequeue();
int b = q.dequeue();
q.enqueue(b);
q.enqueue(a + b);
print(a);
}
}
5. (challenging) For any given string, use a stack to create a PEMDAS compliant calculator. For example,
calculate("( 2 + ( ( 3 + 4 ) * ( 5 * 6 ) ) )");
6. Binary trees
Trees are a commonly used data structure in computing. One place
you will have used them all the time without even a moment's
thought is when navigating the folder/file structure of your computer.
This course only requires you to be familiar with the binary tree, a
tree that has no more than two branches coming off each node.
● Left child
● Right child
● Parent
● Sub tree
● Root
● Leaf
● Height of a node: The length of the longest downward path to a leaf from that node.
● Depth of a node: The length of the path to its root (i.e., its root path)
There are three ways of traversing a tree, starting from the root:
● Pre order: Print the node, visit the left node, visit the right node
● In order: Visit the left node, print the node, visit the right node
● Post order: Visit the left node, visit the right node, print the node.
A simple way of visually remembering these traversal methods is to imagine flags as follows
● Pre order: The order in which you visit the green flags
● In order: The order in which you visit the blue flags
● Post order: The order in which you visit the red flags
Example
So, with the original tree shown at the start (root node = 2), what would the pre-order, in-order and postorder
traversal be?
Create the MyBinaryTree class such that the following would work...
1. Program the function inorder() to output the data contained in a binary tree using inorder tree
traversal
2. Program the function preorder() to output the data contained in a binary tree using preorder tree
traversal
3. Program the function postorder() to output the data contained in a binary tree using postorder tree
traversal
4. Program the function lookup(), which given a value, will search the binary tree to determine if the
value is present in the tree, and returns true or false accordingly (you may assume the contents of the
tree are sorted in order)
5. Program the function insert(), which given a value, will insert a new node with the given value at the
correct location within the tree, and shuffles the rest of the tree accordingly as required.
6. Program the function maxdepth() which returns the longest path from the root node to the furthest
leaf node.
7. Program the function isInOrder() which searches the contents of the tree and returns true if the
contents are sorted for in order traversal.
(when you are ready, ask me for the solutions file, "cs-unit-5-binarytree-problems-with-solutions.pdf")
Past paper questions for review
(refer to separate document)