2013-fpdaa

7
4208 FIRST PUBLIC EXAMINATION SECOND PUBLIC EXAMINATION Preliminary Examination in Computer Science Preliminary Examination in Mathematics and Computer Science Preliminary Examination in Computer Science and Philosophy Honour School of Mathematics FUNCTIONAL PROGRAMMING, DESIGN AND ANALYSIS OF ALGORITHMS TRINITY TERM 2013 Tuesday 11th June, 2:30 pm – 5:30 pm Candidates should answer no more than five questions. with no more than three questions from either half. Please start the answer to each question on a new page. Answers to Questions 1–4 and Questions 5–8 should be submitted in separate bundles, each with its own cover sheet. A cover sheet should be completed for each of the two sections of the paper, even if no question from that section has been attempted. Do not turn over until told that you may do so. –1–

description

Functional Programming and Design & Analysis of Algorithms

Transcript of 2013-fpdaa

Page 1: 2013-fpdaa

4208

FIRST PUBLIC EXAMINATION

SECOND PUBLIC EXAMINATION

Preliminary Examination in Computer Science

Preliminary Examination in Mathematics and Computer Science

Preliminary Examination in Computer Science and Philosophy

Honour School of Mathematics

FUNCTIONAL PROGRAMMING, DESIGN AND ANALYSIS

OF ALGORITHMS

TRINITY TERM 2013

Tuesday 11th June, 2:30 pm – 5:30 pm

Candidates should answer no more than five questions.

with no more than three questions from either half.

Please start the answer to each question on a new page.

Answers to Questions 1–4 and Questions 5–8 should be submitted in separate bundles, eachwith its own cover sheet. A cover sheet should be completed for each of the two sections of the

paper, even if no question from that section has been attempted.

Do not turn over until told that you may do so.

– 1 –

Page 2: 2013-fpdaa

Functional Programming

Note that whenever you are asked to define a function you should use Haskell syntax, and

include a suitable polymorphic type signature and appropriate comments. Any functions from

the standard Haskell Prelude can be freely used without giving a definition, unless a definition is

specifically requested.

Question 1

(a) Give the most general type and definition of the following standard Haskell functions: map,concat, curry and uncurry. (6 marks)

(b) (i) What is the (most general) type of map concat? Explain your reasoning.(2 marks)

(ii) Give the most general type of the function f, where

> f x y z = x (x z) y

Explain your reasoning. (4 marks)

(c) This part of the question is about writing a program that generates Pascal’s triangle. Asillustrated in Figure 1, each non-boundary entry in Pascal’s triangle is the sum of the twoentries directly above it. For example, the entry 6 in the fifth row is the sum of the twoentries 3 directly above it.

11 1

1 2 11 3 3 1

1 4 6 4 11 5 10 10 5 1

1 6 15 20 15 6 11 7 21 35 35 21 7 1

1 8 28 56 70 56 28 8 11 9 36 84 126 126 84 36 9 1

Figure 1: The first 10 rows of Pascal’s triangle

Write the definition of a function pascal which would generate a suitable data structurecontaining the numbers in an infinite Pascal triangle. (8 marks)

4208 – 2 –

Page 3: 2013-fpdaa

Question 2

(a) Let ⊕ and ⊗ be binary operators, and let a be a value, such that:

x ⊕ (y ⊗ z) = (x ⊕ y) ⊗ z (1)

x ⊕ a = a ⊗ x (2)

for all x, y, z and a of suitable types.

Prove that for all finite lists xs,

x ⊕ foldl (⊗) y xs = foldl (⊗) (x ⊕ y) xs (3)

(6 marks)

(b) Using the result from part (a) prove that, if (1) and (2) hold, then for all finite lists xs,

foldr (⊕) a xs = foldl (⊗) a xs (4)

(6 marks)

(c) Define the standard Haskell function concat using foldr. (1 mark)

(d) Use equation (4) to define the standard Haskell function concat using foldl. (3 marks)

(e) Compute the order of growth of:

(i) the number of reduction steps required to evaluate the definition of concat that usesfoldr;

(ii) the number of reduction steps required to evaluate the definition of concat that usesfoldl.

(4 marks)

4208 – 3 – TURN OVER

Page 4: 2013-fpdaa

Question 3

This question requires you to write a Haskell program for counting the frequency of the differentwords in a given text. After all the words have been counted, the program outputs all the wordswith their frequency counts, in decreasing order of frequency. Words that appear with the samefrequency should be output in alphabetical order. You may assume that the given text hasalready been separated into words. Your test for word equality should be case-insensitive. Youmay use any of the Haskell Prelude functions and any of the functions in the Char module inyour answer.

(a) Define two suitable type synonyms, one for words and one for the input text. (2 marks)

(b) Define a function count which, given an input text, returns an unsorted list containingelements of type (word,word frequency). For example,

> count ["Baa","baa","black","sheep","have","you","any","wool","Yes","Sir","yes","Sir","three","bags","full"]

could return:

[("baa",2),("black",1),("sheep",1),("have",1),("you",1),("any",1),("wool",1),("yes",2),("sir",2),("three",1),("bags",1),("full",1)]

(6 marks)

(c) Write a sorting function, sort, which takes as input argument a list xs of the type gen-erated by the function count in part (b) and sorts this list in O(nlogn) steps, wheren =length xs. Sorting should be performed in decreasing order of frequency. Words thatappear with the same frequency should be output in alphabetical order.For example,

> (sort.count) ["Baa","baa","black","sheep","have","you","any","wool","Yes","Sir","yes","Sir","three","bags","full"]

should return:

[("baa",2),("sir",2),("yes",2),("any",1),("bags",1),("black",1),("full",1),("have",1),("sheep",1),("three",1),("wool",1),("you",1)]

(12 marks)

4208 – 4 –

Page 5: 2013-fpdaa

Question 4

A binary search tree represents a set of values. The nodes of the tree are labelled with the ele-ments of the set, such that the value on each node is greater than the values in the correspondingleft subtree, and less than the values in the corresponding right subtree.

(a) Give a Haskell type definition for binary search trees. (2 marks)

(b) Give the Haskell type and definition for a function insert that inserts an element in abinary search tree; you are not expected to give a solution that balances the tree. Howmany comparisons does this take if the tree contains n elements? Give answers for boththe average case and the worst case. (4 marks)

(c) Give the Haskell type and definition for a function foldSTree that forms a fold over abinary search tree, combining the labels on the nodes. (4 marks)

(d) Give a foldSTree-based definition of a function flatten that produces a list, in order, ofall the labels of a binary search tree. (2 marks)

(e) Give a foldSTree-based definition of a function that computes the size of a binary searchtree. (1 mark)

(f) Give a foldSTree-based definition of a function that computes the depth of a binary searchtree. (1 mark)

(g) Give the Haskell type and definition for a function delete that deletes an element from abinary search tree; you are not expected to give a solution that balances the tree.

(6 marks)

4208 – 5 – TURN OVER

Page 6: 2013-fpdaa

Design and Analysis of Algorithms

Question 5

A directed graph of n nodes numbered 0, 1, . . . n − 1 can be represented by an n× n adjacencymatrix E where E[i, j] is true if there is an edge from node i to node j, and E[i, j] is falseotherwise.

For k ≥ 0 we define Pk to be the matrix such that Pk[i, j] is true if there exists a path oflength ≤ k connecting node i to node j, and Pk[i, j] is false otherwise.

(a) Describe P0. What is the relationship between P1 and E. (4 marks)

(b) Describe how to generate Pk+1 from Pk and E, or alternatively from Pk and P1.(4 marks)

(c) How could this step be used in an algorithm that generates the reflexive transitive closureof a graph given its adjacency matrix. (4 marks)

(d) What is the worst case cost of this reflexive transitive closure algorithm in terms of n andm, where m is the maximum path length in the transitive closure? Is your bound tight?

(4 marks)

(e) Describe how to generate P2k from Pk. How could this step be used in an alternativealgorithm for generating the reflexive transitive closure of a given graph. Compare theresulting efficiency with the one you established in Part (d). (4 marks)

Question 6

(a) Explain the divide and conquer strategy of algorithm design and show how it can be usedto produce an O(n log n) sorting algorithm. (4 marks)

(b) Prove that Ω(n log n) is a lower bound on the number of binary comparisons required tosort n elements. [Recall that log n! ∈ Ω(n log n).] (4 marks)

(c) Consider the following task: given a set of n numbers (stored in an array), find thei smallest numbers in sorted (increasing) order using a comparison-based algorithm. Forexample, if the input is the set 8, 14, 2, 7, 9, 10, 6 with i = 3, the output is 2, 6, 7.

For each of the following methods, describe an algorithm that implements it with the bestasymptotic worst-case running time, and analyse the running time of the algorithm, givingan asymptotic tight bound in terms of n and i.

(i) First sort the numbers, then list the i smallest numbers. (4 marks)

(ii) Build a min-priority queue from the numbers, and call Extract-Min i times.(4 marks)

(iii) Use a selection algorithm to find the ith smallest number, partition around thatnumber, and sort the i smallest numbers. (4 marks)

4208 – 6 –

Page 7: 2013-fpdaa

Question 7

(a) What is dynamic programming? What do we mean by the Principle of Optimality?(3 marks)

(b) Describe the knapsack problem without repetition and show how dynamic programmingprovides a solution.

Explain, briefly, the data structures involved in implementing this solution.

What is the runtime of this algorithm in terms of number of items n and total capacityW ? (10 marks)

(c) We can modify the knapsack problem by providing two bags with respective capacities W1

and W2. Each object is placed in at most one bag and we wish to maximise the total valuein the combined bags.

By extending the recurrence relations used to produce the dynamic program in part (b),find a dynamic programming solution to this problem.

What is the runtime of your algorithm? (7 marks)

Question 8

(a) Describe an efficient algorithm that allows you to arrange the nodes of an acyclic directedgraph in an order n1, n2, . . . such that if there is an edge from ni to nj then i < j. Explainwhy your algorithm is correct. What is its runtime? (6 marks)

(b) Show that the following relation on the nodes of a finite directed graph is an equivalencerelation:

a ≡ b if and only if there are paths from a to b and from b to a through thegraph.

(2 marks)

Recall that the equivalence classes under ≡ are called Strongly Connected Components (SCCs).

(c) Suppose a directed graph has all its edges painted black or white. Show that it contains acycle in which there are both black and white edges if and only if there is a SCC in whichthere are both black and white edges. (2 marks)

(d) Show that the statement in (c) is not true if we replace “cycle” by “simple cycle”(2 marks)

(e) Describe an algorithm that given a directed graph (V,E) calculates its SCCs. What is itsasymptotic run time? Explain your answer. (8 marks)

4208 – 7 – LAST PAGE