Algorithm Assignment 2 Sol, Assignments of Algorithms and Programming

Assignment 2 Preferred Answers

Typology: Assignments

2019/2020

Uploaded on 06/11/2020

usyd9120
usyd9120 🇦🇺

1 document

1 / 9

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Due: 26th April 2020 at 11:59pm
Submit your assignment via Canvas. Submission must be in pdf format and cannot be
handwritten. This assignment is worth 12% of your final grade.
COMP9007 Algorithms Assignment 2
Semester 1 2020
As a first step go to the last page and read the section: Advice on how to do the assignment.
Question 1
Consider the following graph below:
a) Is this graph strongly connected? Explain why or why not. (3 marks)
b)
Is this graph bipartite? Explain why or why not. If it is, provide the two sets of
vertices S1and S2.(3 marks)
c) Provide a topological ordering of this graph if one exists.
(4 marks)
1
pf3
pf4
pf5
pf8
pf9

Partial preview of the text

Download Algorithm Assignment 2 Sol and more Assignments Algorithms and Programming in PDF only on Docsity!

Due: 26th April 2020 at 11:59pm

Submit your assignment via Canvas. Submission must be in pdf format and cannot be handwritten. This assignment is worth 12% of your final grade.

COMP9007 Algorithms – Assignment 2

Semester 1 2020

As a first step go to the last page and read the section: Advice on how to do the assignment.

Question 1

Consider the following graph below:

a) Is this graph strongly connected? Explain why or why not. (3 marks)

b) Is this graph bipartite? Explain why or why not. If it is, provide the two sets of vertices S 1 and S 2. (3 marks)

c) Provide a topological ordering of this graph if one exists. (4 marks)

Solution:

a) Yes, the graph is strongly connected. Choose any node s. From the lecture, a graph is strongly connected if and only if s is reachable from every node, and every node is reachable from s. For example, choose node A. The following are valid paths (cycles) in the graph that link nodes to A, ensuring they are reachable from A and A is reachable from them:

  • A,B,C,E,G,A
  • A,B,C,J,I,D,A
  • A,B,C,E,G,F,D,A
  • A,B,C,E,G,H,I,D,A Together they encompass all nodes.

b) No, the graph is not bipartite. From the lecture, if a graph contains an odd- length cycle, it is not bipartite. This graph contains multiple odd-length cycles:

  • A,B,C,E,G
  • B,C,J

c) No topological ordering exists because the graph is not a directed acyclic graph (DAG). It contains multiple cycles, as described previously.

must have substituted a number of increment operations with a doubling operation from the algorithm’s solution. However the algorithm never performs increment twice in a row in order to warrant a substitution because decrementing an odd number always results in an even number and subsequent halving step. In essence, the algorithm will return the number of steps with the maximum doubling present. The algorithm’s result is the optimal solution.

c) Let the number of iterations of the while loop be k. Note that whenever n is decremented, the next iteration of the while loop will halve n because an odd number minus one is an even number. Therefore, on each pair of iterations, n decreases by at least half. Since the loop ends when n is 1, n ≥ 2 k/^2. The number of iterations is proportional to log 2 n. On each iteration, constant time operations are performed for checking divisibility, comparisons, halving, incrementing and decrementing. Therefore the total running time is O (log n ).

Question 3

A mountain range is defined by an array of n distinct integers A = [ h 0 , h 1 , h 2 , h 3 , h 4 , ...., hn − 1 ] representing the heights of the peaks of each mountain (above sea level), given in the order that they appear in the mountain range. Suppose you are a climber standing at one of the peaks. You want to know the nearest taller mountain looking left down the mountain range and also the nearest taller mountain looking right down the mountain range. The goal is to find an algorithm to compute this for ALL n mountains.

Essentially, for all mountains x ∈ [0 , n − 1], compute the two closest indices i and j to x such that:

i < x ,

j > x ,

A [ i ] > A [ x ] and

A [ j ] > A [ x ].

Your algorithm should return two arrays of length n:

L [0 ...n − 1] where L [ x ] denotes the index ( i ) of the nearest taller mountain from mountain x looking left (or None if no such mountain exists).

R [0 ...n − 1] where R [ x ] denotes the index ( j ) of the nearest taller mountain from mountain x looking right (or None if no such mountain exists).

Note:

  • A [∗] denotes the element at index ∗ in the array
  • Indices start at 0

Examples: Input: A=[5,2,6,8,1,4,3,9] Output: L=[None, 0, None, None, 3, 3, 5, None] R=[2, 2, 3, 7, 5, 7, 7, None]

Input: A=[4,2,3,1,8,5,6,9] Output: L=[None, 0, 0, 2, None, 4, 4, None] R=[4, 2, 4, 4, 7, 6, 7, None]

Input: A=[8,2,1] Output: L=[None, 0, 1] R=[None, None, None]

a) Design a divide-and-conquer algorithm to solve this problem in O ( nlogn ) time. (20 marks)

b) Prove your algorithm is correct. (10 marks)

c) Analyse the running time of your algorithm: derive the recurrence and solve it. (8 marks)

d) (Optional) Implement your algorithm on Edstem. https://edstem.org/courses/3901/assessments/

1 def ntm(x): 2 #base case 3 if len(x)==0: 4 return [],[] 5 if len(x)==1: 6 return [None],[None] 7 n=len(x) 8 mid=n// 9 #divide 10 left = x[0: mid] 11 right = x[mid:len(x)] 12 13 l1 ,r1 = ntm(left) 14 l2 ,r2 = ntm(right) 15 16 #merge 17 i=mid - 18 i2= 19 20 #find matches between mountains that currently have None 21 while i >= 0 and i2 < len(right): 22 if r1[i] != None: 23 i -= 1

b) Since this is a recursive algorithm, we can use a proof by mathematical induction. Trivially, the base case is true because a single mountain cannot see any other mountains left or right.

Assume the algorithm works for all possible input sizes up to k. Now consider an input of size > k. We divide the input into halves and by the inductive hypothesis, the solution for each half will be correct for the nearest taller mountain looking left and right within those halves.

The merge step matches None values in R1 and L2. Suppose the NTM of the cell updated by the algorithm can be found elsewhere in a position that does not contain None within the other corresponding array. For example, looking right from R1 we can see a NTM in L2 that does not contain None in its corresponding cell. This means that from that mountain in L2, it can see an NTM within the same array looking left, which is towards us and should be blocking our view of it. We have a contradiction - the NTM in L2 must contain None within its cell. Similar reasoning holds for vice versa. Since the algorithm only updates the cell of the mountain with smaller height, the taller one still retains its null value unless another taller one is discovered while travelling outwards from the centre of the array. By travelling from the end→start of R1 and start→end of L2, we always consider the closest pairs of None values first, ensuring the selected taller mountain is nearest. This process restores the invariant once L2 and R2 have been reindexed and then L1 and L2 are concatenated to make the solution for L and R1 and R2 are concatenated to make the solution for R. Thus the algorithm is correct for size > k given that it is correct for size < k.

Given that the algorithm is correct for the base case, it will also be true for n=2, then n=3, and so on for all integers n.

c) On each call of the function:

  • Checking the base case takes O(1).
  • Finding the middle takes O(1), just divide the size by 2 (storing other variables also takes O(1))
  • Dividing the array in half takes O(n) using slicing, values are copied into new arrays
  • The while loop runs for n iterations, on each iteration only performing constant time operations for array access, comparisons and increment/decre- menting.
  • Reindexing loop takes O(n) to check not null for each of the cells in L2, R and update accordingly
  • Concatenating the two arrays L1+L2 and R1+R2 takes O(n), the values are copied into new arrays.

In total the recurrence relation is: T ( n ) = 2 T ( n/ 2) + O ( n ). The algorithm calls itself recursively twice with sub-problems half the size, and on each recursive call, O(n) work is done. Using the master theorem, a = 2 and b = 2 so we get O ( n log^2 2 ) = O ( n^1 ) = O ( n ). When compared with f ( n ) = O ( n ), it’s case 2, (with

k=0) so the result is T ( n ) = O ( n log n ),

Question 4

For each of the following problems indicate which algorithmic approach (Greedy, Divide- and-conquer, Dynamic Programming) you would use to attempt to solve the problem efficiently and why? You do not have to give an algorithm.

a) In an n × n array, a peak is an element that is greater than its four neighbours (left, right, top and bottom). Peaks can also lie on edges or corners, they are greater than their three or two (respectively) neighbours. There can be more than one peak in an array. The algorithm should efficiently find a peak in an n × n array. (8 marks)

b) You are in charge of assigning planes to gates at an airport. After a plane lands, it needs to be assigned to a gate, where it must remain until it takes off. Given a list of plane arrival and departure times, the algorithm should assign planes to gates in an efficient manner. (8 marks)

c) Your small town has grown large enough that it has to be divided into suburbs to efficiently allocate resources (e.g. electricity, water, school zones). The algorithm should assign households into five ”geographically close” suburbs – i.e. divide houses into five groups so that the minimum distance between houses in different suburbs is maximized. (8 marks)

d) Determine how many ways you can make 15 by summing six numbers (possibly repeated) from 0, 1, 2, 3, 6. (8 marks)

Solution:

a) Use divide-and-conquer. The Greedy approach (gradient ascent) will run O ( n^2 ) time by potentially traversing in a snake pattern left-right then right- left then left to right, top down through the grid in the worst case instance. Therefore, divide and conquer is the best method: dividing the grid in half each time can yield a running time of O ( n log n ).

b) Greedy. This is an example of the Interval Partition problem from lectures, and can be solved with a greedy algorithm.

c) Greedy. This is an example of the k-clustering problem. We can solve this with Kruskal’s algorithm, which is a greedy algorithm for computing an MST.

d) Dynamic programming. This is a variation of the coin-change problem where we count the number of combinations that can make up a total rather than whether or not a combination can make up a total. The changes required to the coin-change DP algorithm are minimal.