Comp1927 Qs
Comp1927 Qs
Comp1927 Qs
Here are the prototypes for some functions you may wish to use
for this task (you can take the code from the lecture)
//Createanewnode,initialisedwiththeitem
provided.Return//pointertonode(link)link
newNode(Itemitem);//Insertanewnodeintoa
givennonemptylist//Thenodeisinserted
directlyaftertheheadofthelistlsvoid
insertNext(linkls,linknode);
typedefcharItem;typedefstructnode*link;struct
node{Itemitem;linknext;};typedefstruct
listImpl*list;structlistImpl{intsize;link
first;linklast;};
Modify the length function you wrote in excercise 1 to work with our
new implementation.
voidappend(dlinklist1,dlinklist2)
Exercise 2
Implementing a Stack with a Linked List
Implement the functions from the Stack.h interface given in Exercise 1, using
a linked list structure. How will you represent your stack?
typedefstructstackNode*link;structstackNode{
//Youneedtodecidewhatgoesinhere}struct
stackImp{//Youneedtodecidewhatgoesin
here};
Assume you have the following local helper function to create Nodes as
follows
staticlinkcreateNode(Itemitem);
Exercise 3 - Stacks
Write a program which, given a string containing round, curly, and square
brackets, will print 'success' if the parentheses are correctly balanced, and
'fail' otherwise.
>./check_parens"()"success>./check_parens
"([])"success>./check_parens"([]){}"success
>./check_parens"([]){"fail>./check_parens
"([sdfdf]ss)fdfsd"success
Hint: the problem is similar to the postfix expression evaluation problem.
Exercise 4 - Function Pointers
Given the following function prototypes and assignments:
intadd(intn1,intn2);linkreverse(linkls);
voidsquare(double*x);x1=add;x2=reverse;
x3=square;
Give the correct variable declarations for x1, x2, and x3.
Exercise 5 - Testing
What is the difference between black box and white box testing ADTs?
Exercise 6 - Blackbox testing
Imagine you have the following test file defined in a file called testStack.c and
it includes the Stack.h interface from Exercise 1:
#include"Stack.h"intmain(intargc,char*argv[])
{printf("Testingnewstack\n");Stacks=
createStack();assert(s>size==0);
printf("Testpassed\n");return0;}
When compiling my test file using
gccWallWerrorOctestStack.c
I get the following compile error
testStack.c:12:5:error:dereferencingpointerto
incompletetype
What does this mean?
Tutorial Exercises Week 03
Exercise 1
Function Growth Rates
Calculate how long T(n) steps would take for different sizes of n for the T(n)
functions in the table below. Assume you are running it on a computer that
performs one million steps per millisecond. Note: A millisecond is a
thousandth of a second.
T(n) =
log n
T(n)
=n
T(n) = n
log n
T(n) =
n2
T(n) =
n3
T(n) =
2n
10
20
50
100
1000
1000
0
For what size of n does the computation time for T(n) = 2 n become too large to
be practical? Would it help if we used a computer that was a million times
faster?
Exercise 2
Write a recursive function
intallEven(inta[],intl,intr);
which takes an array, the left-most and right-most index of the current
segment of the array as an argument and checks if all elements in an array
are even.
It must use a divide and conquer approach, by splitting the array in half, first
checking if all the elements in the left half are even, and then (only if
necessary) checking the right half.
Exercise 3
Binary Search Tree Insertion, Deletion and Traversal
Insert the following keys into a BST: 10 20 5 30 15 25 24
What is the height of the resulting tree?
Delete 5 30 20 (assume we replace nodes with the left-most of the right subtree when necessary)
What is the height of the resulting tree?
Show the output obtained by traversing the tree and printing out each node in
the following orders:
prefix (NLR)
postfix (LRN)
infix (LNR)
Exercise 4
BST Functions
Assume the following representation of a BST
typedefstructtreenode*treelink;structtreenode{
Itemitem;treelinkleft;treelinkright;}
Assume your tree holds items of type int. Write a function to recursively
sum the items of a BST tree. Your function should have the following
prototype:
intsumItems(treelinktree);
Write a function that searches for a given item in a BST. Your function
should return 1 if the item is found and 0 otherwise. You should use an
iterative approach and a recursive approach
intiterativeSearch(treelinkt,Itemi);
intrecursiveSearch(treelinkt,Itemi);
Write a function that will free all the memory associated with a tree
voidfreeTree(treelinkt);
Write a function to insert an item into a BST. It should return the root of
the tree.
treelinkinsert(treelinkt,Itemi);
3,2,4,8,1
Sorted order:
1,2,3,4,5
Reverse order:
5,4,3,2,1
a. Show how each of these arrays above change as they are sorted by
the program above.
b. How many swaps are performed on the random, sorted, reverse
ordered data sets shown above
c. How many comparisons are peformed on the random, sorted and
reverse ordered data sets shown above. By comparison we mean
comparing two data elements from the array - we are not including the
loop counter comparisons.
d. With each line of code associate a cost and a formula expressing the
number of times the C statement on that line will be executed when
sorting nitems in the worst case.
e. What is the asymptotic worst case time complexity of the algorithm
implemented by this program.
f. What is the time complexity of the algorithm in the best case?
g. Modify the program to implement bubble sort with early exit. What is
the asymptotic worst case time complexity now? What is the time
complexity now in the best case?
Exercise 3
Insertion Sort
1voidinsertionSort(intitems[],intn){2int
i,j,key;34for(i=1;i<n;i++){5
key=items[i];6for(j=i;j>0;j){7
if(key<items[j1]){8items[j]=
items[j1];//itemshiftsalongtomakeroom9
}else{10break;11}12
}13items[j]=key;14}15}
a. Show how each of the arrays from the previous question (sorted,
random, reverse), change as they are sorted by the program above.
For each one count the number of comparisons and number of shifts.
b. With each line of code associate a cost and a formula expressing the
number of times the C statement on that line will be executed when
sorting nitems in the worst case.
c. What is the asymptotic worst case time complexity of the algorithm
implemented by this program.
d. What is the time complexity of the algorithm implemented by this
program in the best case?
Exercise 4
a. Explain what stability means in the context of sorting
b. Suppose you have an implementation of a sorting algorithm that sorts
strings and is case insensitive (for example 'a' and 'A' are considered to
be equal). Explain what is wrong with the following argument:
I ran the following input through the program
AAAAAzzzzzabcdeaaaaa
typedefintItem;#definekey(A)(A)#defineless(A,
B)(key(A)<key(B))#defineexch(A,B){Itemt=A;
A=B;B=t;}intpartition(Itema[],intl,int
r);voidquicksort(Itema[],intl,intr){int
i;if(r<=l)return;i=partition(a,l,r);
quicksort(a,l,i1);quicksort(a,i+1,r);}
intpartition(Itema[],intl,intr){inti=
l1,j=r;Itemv=a[r];for(;;){while
(less(a[++i],v));while(less(v,a[j]))if(j
==l)break;if(i>=j)break;exch(a[i],
a[j]);}exch(a[i],a[r]);returni;}
Trace the execution of the partition function on sorting the following input
sequence of numbers: 4711467256.
Trace the execution of the partition function on the following sequence of
numbers: 12345678910
Exercise 2
Quicksort with median of three partitioning
One improvement to the Quicksort algorithm that we discussed was the use of
Median-of-Three partitioning. In this version of Quicksort, three items in the
array are sampled and the median of the three values is used to partition the
array. Without looking at the C code given in lectures, complete the following
program by replacing the comments with the relevant C program statements.
//QuicksortwithMedianofThreePartitioningvoid
quicksortMT(Itema[],intl,intr){inti;
if(r<=l)return;if(rl>1){
medianOfThreePivot(a,l,r);i=partition(a,
l+1,r1);}else{i=partition(a,l,r);
}quicksortMT(a,l,i1);quicksortMT(a,i+1,
r);}voidmedianOfThreePivot(intitems[],intlow,
inthigh){//Swapmedian(valuemidway
betweenlowandhigh)withitems[high1]//
Compareitems[low],items[high1]anditems[high]
//Rearrangevalues://lowestvaluetobestored
initems[low]//highestvaluetobestoredin
items[high]//medianvaluetobestoredin
items[high1]}
Trace the call of medianOfThreePivot and then partition on the sequence 12
345678910
Exercise 3
Mergesort
Exercise 4
Given the following definition of an adjacency list representation of a graph,
write a function that would be able to find the degree of a given Vertex.
typedefintVertex;typedefstructvnode*vlink;
structvnode{Vertexv;vlinknext;};
structgraph{intV;intE;vlink*adj;
//anarrayoflinkedlists};
Discuss how the following graph could be stored using the given
representation:
01/\23\45
Write a function that would be able to find the degree of a given Vertex.
Your function should have the following prototype:
intGRAPHdegree(Graphg,Vertexv);
Exercise 5
Sorting Linked Lists
This is good practice for the prac test. Given the following definition of a linked
list
typedefstructnode*link;structnode{Item
item;linknext;};
Exercise 1
Cheapest Least Visited Strategies
In what order would you visit the nodes if you started at vertex 0 and used the
cheapest least visited approach from assn2 and you had stamina of 100000?
(Show the first 10 vertices you would visit in the order you would travel to
them).
What about if you had a stamina level of 50?
Exercise 2
Depth First Traversal
Suppose that you started at the node labelled 0. Show the order in which
nodes might be visited while performing a depth-first traversal of the graph.
(You can assume, when faced with a choice of which node to visit next, you
visit the node with the lowest label.)
What would the contents of the st array be?
Show the same DFS traversal, but include vertices you backtrack to.
What about if you started from node 3?
Exercise 3
Graph Implementations
//Graph.hdefinitions//verticesdenotedbyintegers
0..N1typedefstructgraphRep*Graph;typedefint
Vertex;typedefstructedgeEdge;//edgesare
pairsofvertices(endpoints)structedge
{Vertexv;Vertexw;};
//Adjacencymatrixunweightedgraphrepresentation
structgraphRep{intnV;//#vertices
intnE;//#edgesint**adj;//matrixof
booleans(0or1)};
//Adjacencylistgraphrepresentationtypedefstruct
vNode*VList;structvNode{Vertexv;
VListnext;};structgraphRep{intnV;//
#verticesintnE;//#edgesVListVList
*adj;//arrayoflists};
Implement a function
intisEdgeInGraph(GraphG,Edgee);
that tests whether a given graph edge is present in the graph. The
function should return 1 if the edge exists in the graph and 0 otherwise.
How could you store a label for each vertex in graph, that you could
access easliy via its vertex id?
Suppose that you started at the node labelled 0. Show the order in which
nodes might be visited while performing a breadth-first traversal of the graph.
(You can assume, when faced with a choice of which node to visit next, you
visit the node with the lowest label.)
Exercise 2
Dijkstra's Shortest Path Algorithm
Suppose that you started at the node labelled 3. Trace through Dijkstra's
algorithm. What values do the dist and st arrays have in them when the
algorithm is completed? What is the length of the shortest path from node 3 to
node 2? What is the actual path?
Exercise 3
Minimal Spanning Trees
Find a minimal spanning tree of the weighted graph in Question 2 using:
1. the Prim-Jarnik MST algorithm
3. In each of the following questions, start with the tree in the state shown
above. Show the effect of executing each of the following operations on
the tree:
a. t4->right = rotateRight(t5)
b. t0 = rotateLeft(t0)
c. t0 = rotateRight(t0)
d. t0 = partition(t0,5)
e. t0 = partition(t0,8)
f. t0->left = partition(t1,3)
The following questions are extra questions to do at home as practice for the
prac exam.
Extra Question 1
Directed Graph DFS
What order would the nodes be visited while performing a depth first search
starting at node d. What about if we started at node g?
Extra Question 2
Directed Graph BFS
What order would the nodes be visited while performing a breadth first search
starting at node d. What about if we started at node g?
Extra Question 3
Graph Properties
In the 18th Century, the Prussian town of Konigsberg (now Kaliningrad) was
famous for the seven bridges connecting its two central islands with the ban
ks of the River Pregel, as shown in the diagram. Can you draw a path which c
rosses each bridge exactly once? If not, explain why.
Tutorial Exercises Week 08
Exercise 1
Balanced Trees
Explain how we could globally balance a binary search tree using the partition
function.
Exercise 2
Splay Trees
What is the difference between splay tree insertion and root insertion?
a splay tree
Insert the same keys into a randomised binary search tree - get
someone to flip a coin each time a decision needs to be made as to
whether the node is inserted at the leaf or root of the given subtree.
Heads can mean root, tails can mean leaf. Note: in the actual
implementation from lectures the probability that it is inserted at the
root is approx 1/n and not just 0.5 like a coin toss.
Exercise 3
Hashtables
Draw a hash table of size 13. Use the hash function "k%13" and insert the
keys: 5, 29, 32, 0, 31, 20, 23 and 18 into your table (in that order) using the
following strategies for handling collisions.
1. Chaining
2. Linear Probing
3. Double Hashing with a second hash function "7 - (k%7)". (Why would a
second hash function such as "k%7" not be very useful?)
If there is any remaining time, use it to finish any questions that you did not
cover in previous weeks.
Work on assn2
Assessment
Deadline: 11:59pm Tuesday 4th February 2014
Total Marks: 3
Setup for Task 2 of the lab
Change into your lab07 directory and run the following command:
cp/home/cs1927/public_html/14x1/labs/lab07/files/*.
Note the "." at the end of the command, meaning "into the current directory". If
you've done the above correctly, you should find the following files now in the
directory:
client.c
a program to use and test your symbol table ADT
test_data
data to test your ADT with
ST.h
A symbol table ADT interface
Item.h
An interface for an item.
Item_str.c
An implementation of an item.
ST_bstree_lab.c A partially implemented bst that you must complete
Task1: Assignment 1 Mark
0.5 lab mark for implementing stage 0 of the assignment and being able to
pass the first dryrun test of the assignment
0.5 lab mark for implementing stage 1 of the assignment and being able to
pass the second dryrun test of the assignment
For this part of the lab - use the normal give set up for assn2.
Task2: Symbol Tables - 2 Marks
1 Mark Compile the client program and run it with test_data as input:
%gccWallWerrorgoclientclient.cItem_str.c
ST_bstree_lab.c%./client<test_data
1 Mark
You must write some white box tests to ensure the partition and rotate
functions are working correctly. Be thorough.
Submission
When you are happy with your work, please show it to your tutor to get it
marked. Before you leave your lab, remember to submit your lab via the give
command
givecs1927lab07ST_bstree_lab.cclient.c
Lab Exercises Week 8
Objectives
Assessment
Deadline: 11:59pm Tuesday 11th February 2014
Total Marks: 3
Related Chapters of textbook
Chapter 12.8 - 13.2 Sedgewick
Chapter 14 Sedgewick
Setting Up
Set up a directory for this lab under your cs1927/labs directory, change into
that directory, and run the following command:
cp/home/cs1927/public_html/14x1/labs/lab08/files/*.
lns
/home/cs1927/public_html/14x1/labs/lab08/largeFiles/d
ict3dict3lns
/home/cs1927/public_html/14x1/labs/lab08/largeFiles/d
ict4dict4lns
/home/cs1927/public_html/14x1/labs/lab08/largeFiles/d
ict5dict5
If you've done the above correctly, you should now find the following files:
Tree.h
Tree.c
words.c
Item.h
Makfile
dict0
dict1
dict2
a file containing 7106 words
Setup
Unix has a large dictionary of English words which available to use for tasks
such as spell checking. This dictionary is normally held in a file called
/usr/dict/words which contains almost 100000 words, including a large number
of proper names (e.g. John, Sydney), and also including possessive forms of
most nouns (e.g. cat and cat's). For spell-checking, we would scan a file of
text and check whether each word in the file also appeared in the dictionary;
any word that did not would be treated as a spelling error. This essentially
means using the dictionary as a "lookup table".
Before /usr/dict/words can reasonably be used as a lookup table, it needs to
be put into a more useful form than a list of words (albeit alphabetically
ordered).One possibility is to load the dictionary into a binary search tree and
do the searches on this data structure.
The difference between dict4 and dict5 is that all of the proper names and all
of the possessive forms have been removed. Apart from dict0, the other
dictionaries are randomly-chosen subsets of dict4. All of the files are sorted in
alphabetical order. Note that we give you links to the large dictionaries rather
than copies of them because they occupy a non-trivial amount of disk quota. If
you want to work on this exercise at home and use the large dictionaries,
you'll need to grab copies of them.
We have implemented a program, words.c that reads the dictionary words into
Tree structures for fast lookup.
Task1: Balancing Trees - 1 Marks
The main program words reads from a user-specified file of words, and, once
the words are loaded, prints out the number of nodes and the height of the
tree used to store the words. It also prints out what kind of rebalancing
strategy was used.
It takes a command-line argument containing the name of the dictionary file to
be loaded along with an integer that represents what tree balancing strategy
should be used by the tree. The program works as follows:
It inserts all the words from the test file dictionary into a dictionary ADT that is
implemented via a tree. The program then prints out properties of the resulting
underlying tree.
Make the file and confirm that it runs using the dict0 file and using balance
strategy 0 (No rebalancing) by running it as follows
./wordsdict00
Once you have implemented REBALANCE_1 strategy you could also try the
approach where the tree has been rebalanced after every insertion by
running:
./wordsdict01
Consider the following approaches for rebalancing a BST.
1. NO_REBALANCE : No rebalancing - normal BST insertion
2. REBALANCE_1 : Global rebalancing after every insertion
3. REBALANCE_100 : Global rebalancing after every 100 items are
inserted
4. REBALANCE_1000 : Global rebalancing after every 1000 items are
inserted
5. RANDOMISED : Using randomised BST insertion
6. SPLAY: Using splay insertion
7. MY_REBALANCE: A rebalance strategy that you will devise for task 2.
The task is to complete a function called treeInsert that is partially
implemented in the file tree.c
voidtreeInsert(Treetree,Itemit);
The function should call the appropriate insertRecursive and balance
functions according to the specified rebalancing approach. The function
already handles the first balancing strategies (not balancing the tree at all),
you need to add code to handle the rest.
Note: All the necessary functions for standard insertion, balancing, random
insertion and splay insertion are provided. You just need to call them
appropriately.
Once you have implemented the above strategies, run all approaches on the
different dictionaries supplied and record the
the amount of user time it takes to insert and search for all keys
the amount of user time it takes to insert all keys (comment out the line
in the main function that calls the searchAllWords function)
Note: Make sure you run the randomised BST approach a number of times to
get an average (as this is a randomised approach and heights will differ
'randomly' each time).
Discuss the reasons for the differences in height and run times between these
different approaches and algorithms. How does each algorithm influence the
time to insert vs the time to search vs the height of the resulting tree? What
other tests could you run to compare these implementations.
Task2: Your own rebalancing strategy - 1 Mark
In task 1 you experimented with different approaches to calling rebalance on
the tree. For example rebalancing the tree after every insertion vs rebalancing
the tree after every 1000 insertions.
For this part of the lab, implement your own approach MY_REBALANCE and
rerun the tests from above and compare your approach to the ones from
task1.
In your approach you should decide upon some kind of strategy for when to
rebalance the whole tree. It does not matter if it performs worse than the ones
from task 1 as long as you can explain why. For example, you could try and
rebalance when the tree reached a certain level of imbalance - of course you
would have to decide how to determine this measure. Or you can use any
other ideas of your own.
Record and discuss your results in BalancedTrees.txt
Task3: Search in a splay tree - 1 Mark
In lectures, we discussed inserting an item into a splay tree (Balanced tree
examples). The amortised cost of insert and search operations on splay trees
is only valid if we also perform splay rotations during searching for an item. An
partial of implementation of splaySeach has been provided in Tree.c to get
you started. Its prototype is as follows:
linksearchSplay(linkn,Keyk,int*found);
It searches for an item and performs splay rotations on the traversed path,
much like the function splayInsert() does.
NOTE: Once an item has been found it ismoved to the root of tree. If the key
does not exist in the tree, the last node on the search path should be moved
to the root.
You can look at insertSplay to help you implement this function.
NOTE2: Because the search function changes the root of the tree, it needs to
return a pointer to the new root, thus the actual result of the search should be
stored in the variable pointed to by found. This should be 1 if the key was in
the tree and 0 otherwise.
The treeSearch function needs to be modified so that it calls the appropriate
version of searching ,depending what balancing strategy is used. ie it calls