Vous êtes sur la page 1sur 8
AMCN 4208 DECA 4208 DMAS 4208 FIRST PUBLIC EXAMINATION Honour Moderations in Mathematics and Computation: Paper 4 SECOND PUBLIC EXAMINATION Honour School of Engineering and Computing Science Part I: Paper ECS2 Honour School of Mathematical Sciences (3 year course): Paper 03 FUNCTIONAL PROGRAMMING AND ALGORITHM DESIGN Wednesday 12th June, 2002 9.30 a.m. - Noon Engineering and Computing Science candidates should attempt no more than four questions. Hand in your answers to Questions 1-4 and 5-8 in separate bundles, each with its own cover sheet, Please hand in cover sheets for both parts, even if you choose not to answer questions on one or the other. Please start the answer to each question on a new page. Do not turn over until told that you may do so. Functional Programming Question 1 Node-labelled binary trees are trees that are labelled with data values on their nodes, but not on their leaves. For example, the tree tl = Node (Node Empty 5 Empty) 3 (Node (Node Empty 7 Empty) 4 Empty) is illustrated below, where the blobs («) represent leaves. 3 aa Ng “yy dé’ (a) Give a Haskell type definition for node-labelled binary trees. (2 marks) (b) Explain informally what is meant by a binary search tree. Why are binary search trees useful? (3 marks) (c) Give a Haskell type and definition for a function foldTree that forms a fold over a node-labelled binary tree, combining together the labels on the nodes in some appropriate way. (6 marks) (@ Use foldTree to define a function Labels that produces a list, in order, of all the labels of a node- labelled tree. For example, labels t1 = (5,3,7,4] (4 marks) (©) Using Labels, or otherwise, give a Haskell type and definition for a function i sBS'T that tests whether anode-labelled tree is a binary search tree. (6 marks) 4208 Question 2 In the football World Cup competition, teams are arranged in groups of 4, and each team plays every other team in its group. The aim of this question is to develop a program to print a group table, as below, showing the relative standings of the teams after some, but not necessarily all, of the matches have been played. Team P WD OL F A GD Pts England 211032 14 Peper) =f) ab (est 8) aan Nigeria 2102122 -13 Sweden eye Oude teal aed ‘The colurmns in the table have the following meanings: P The number of matches played by this team; Ww The number of matches won by this team; D The number of matches drawn by this team; L The number of matches lost by this team; F The number of goals scored by (for) this team; ‘A. The number of goals scored against this team; GD The goat difference for this team: the difference between goals for and goals against; Pts The number of points earned by this team: three points are eamed for a win, and one point for a draw. ‘The table is arranged in decreasing order of points scored; when two teams have the same number of points (for example, Argentina and Nigeria, above), the team with the higher goal difference is placed higher. ‘We will use the following types to represent teams, the score for a team in a match, and the result of a match: > type Team = String > type Score = Int > type Result = (Team, Score, Team, Score) For example, the following list of results would lead to the above group table: "sweden", 1), "england", 2)] [(Argentina", 2, "Nigeria", 0), ("England", ("Sweden", 0, "Nigeria", 1), ("Argentina*, (a) Write functions > hasWon, hasLost, hasDrawn :: Team -> Result -> Bool that test whether the given team has won, lost or drawn a match with the given result; the given team might not have actually played in the match. 4208 TURN OVER Also write functions > goalsFor, goalsAgainst :: Team -> Result -> Int that retum the number of goals scored for or against a team in @ match with the given result; again, the given team might not have actually played in the match. (4 marks) (b) Next we will calculate the statistics to be entered in the table for a single team. We will calculate a result of type: > type Statistics = (Team, Int, Int, Int, Int, Int, Int, Int, Int) where the nine fields correspond to the nine columns of the table, in order. Write a function > getstats tr sult] -> Team -> Statist that calculates these statistics. (5 marks) (©) Now write a function > getallstats :: [Result] -> [Team] -> [Statistics] that calculates the statistics for all the teams. The statistics should be listed in the order they will appear in the group table, as described above. (6 marks) (@) Write a function > showfable :: [Statistics] -> String that creates the group table from the statistics. Format the team name in a column 10 characters wide, the goal difference in a column 4 characters wide, and all the other data in columns 3 characters wide. Hence write a function > makeTable [Result] -> [Team] -> I0() that calculates the statistics and prints the table. You may use the following functions: > rjustify > justify > spaces n st = spaces (n - length st) ++ st st = st ++ spaces (n - length st) replicate n ' ' nee (5 marks) 4208 4 Question 3 A bag is like a set except that a given element can occur more than once in it. A bag can be represeated by a list of pairs, where each pair consists of an element together with a count of the number of times the element appears in the bag. Forexample, {(Apple, 3), (Orange, 4) ] represents a bag contai 1g 3 Apples and 4 Oranges. Note elements are listed in the representation only if they occur at least once in the bag, and the same element cannot appear in two different pairs. (@) Define a type synonym for a bag. Does the type synonym capture all the aspects of the representation described above? (2 marks) (b) The union of two bags is a new bag in which the number of occurrences of each element is the sum of the number of occurrences in the two bags separately. ‘The intersection of two bags is a new bag in which the number of occurrences of each element is the rminimum of the number of occurrences in the two bags separately. + Write Haskell functions, together with their types, to calculate the union and intersection of two bags. ‘© What are the costs of these functions (using O notation)? (©) Now suppose that an order relation, <, is available over the type of elements. ‘* Suggest an improvement in the representation of bags. ‘* Re-implement the union and intersection functions for this new representation. ‘+ What are the costs of these functions? Question 4 Let & and @ be binary operators, and let a be a value, such that, for all x, y and z: x@ (yz) = (xey) oz x@a=aex (a) Prove that for all finite lists xs, x ® foldl (@) y xs foldl (®) (x ® y) xs (b) Hence prove that for all finite lists xs, foldr (®) axs = foldl (@) a xs (©) Define the function reverse using foldr. (@) Hence use equation (3) to define reverse wing fold1. 4208 -S- (9 marks) (@ marks) a @) (6 marks) @) (6 marks) (2 marks) (6 marks) TURN OVER Algorithm Design Question 5 (a) i) Define a function merge that merges two sorted lists into a single sorted list, and complete, with- out proof: T(mexge)(p,q) = O(?). ii) Using merge, define a simple recursive function Merge that merges a list of sorted lists into a single sorted list. iii) Derive a recurrence for T(Merge)(n, k) for lists of length n. each of whose elements is a list of length k, and complete, with brief justification: T(Merge)(n, k) = O(?), (8 marks) (b) Am algorithm is required that, given a list L = ([9,..., tq~1] of integers, where n is a power of 2, finds in O(n log n) time the length of a longest even segment of Z, that is, the length of a segment [7;,.. rj] of L each of whose elements is even and that is at least as long as any other even segment of L. Design a divide-and-conquer algorithm for this problem, implement it as function > seg :: [Int] -> Int Explain why it is correct, and justify that T(seg)(n) = O(n log n | n a power of 2). (12 marks) Question 6 A rectangular board, divided into squares, is laid out on the ground. Its rows are numbered 0 to r ~ 1 from north to south, and its columns are numbered 0 to c— 1 from west to east. On square (i, j), that is, the square in row i and column j, sits a stack of pi, plates, and po. = Pr—i.e~1 = 0. A robot is to walk from square (r — 1,e~ 1) to square (0,0) moving one square north or one square west at each step and picking up the plates in a square on entering it Given the r x © matrix whose i, j entry is pi, itis required to determine (i) a path that would result in the robot entering square (0,0) carrying as many plates as possible, and ({i) the number of plates the robot would be carrying on entering square (0, 0) after following that path. (2) Propose a simple greedy algorithm for the problem, and either prove that itis correct or give a minimal counterexample to its correctness. (4 marks) (b) Describe a dynamic-programming algorithm for the problem, justify its correctness, and state with brief justification a precise estimate of its worst-case running time, describing any data structures employed. (10 marks) (©) Describe a dynamic-programming algorithm for the variation of the problem in which the robot can carry at most M plates in total. Explain exactly what the algorithm achieves, justify its correctness, and estimate its worst-case running time. (6 marks) 4208 -6- Question 7 (a) Given a finite list A = [ag,...,@,~1] of positive integers and a nonnegative integer 6, it is required to find the largest integer m find :: [Int] -> Int -> Int that solves the problem and satisfies T(£ind)(n,p) = O(nlogn), where n is the length of the list ‘argument, assuming that addition of two integers takes constant time. Justify the O-estimate for your function. (9 marks) (©) Suppose condition ii, in part (a) is changed to: fil, if a; € S and a; < aj, then a; € S. Does the function you defined in part (a) solve the modified problem? If so, explain why. If not, modify your function to obtain a solution. (4 marks) (©) Now assume that you are provided with a function > divide :: [Int] -> ([Int], Int, (Int]) such that T(divide)(n) = O(n) and if B is a finite nonempty list of integers and (C,2,D) divide B, then - © ++ [a] 4+ Disa permutation of B - wis the median of B fy € C then y a [Length © — length D| <1. Use divide to define a function find that solves the problem in part (a) and satisfies T(£ind)(n,p) = O(n). Justify the O-estimate for your function. (7 marks) 4208 7+ TURN OVER Question 8 Suppose G = (V,E) is a finite undirected graph, vo € V, and F is a forest obtained by carrying out a depth-first search of G from vp. (a) Define the terms sree edge and backward edge, and show that each edge of G is either a tree edge or a backward edge. (6 marks) (©) Explain how the results of the depth-first search can be used to determine whether or not G has a cycle, and justify your answer. (6 marks) (©) Let Gp be the graph obtained from G by deleting vp and every edge incident on vp. Show that Gp is connected if and only if vy has at most one child in F. (4 marks) (d) Mlustrate your answers to (a), (b), and (c) by drawing F,, listing the tree edges and the backward edges, displaying a longest cycle in G, and determining whether Go is connected when V = {1,2,..., 10}, E = {(i,j) |i #j and (i divides j or j divides i)}, vp = 1, and in the depth-first seach, the neighbours of a node are visited in increasing order. (4 marks) 4208 LAST PAGE

Vous aimerez peut-être aussi