0% found this document useful (0 votes)
0 views10 pages

ExamII (Fall2019)

This document is an exam for COE 312 - Data Structures, administered by Dr. Wissam F. Fawaz on December 12, 2019. It includes various problems related to data structures, recursion, algorithm analysis, and queues, with specific instructions for completion and grading. The exam consists of multiple-choice questions, coding tasks, and theoretical analysis, requiring students to demonstrate their understanding of data structures and algorithms.

Uploaded by

obeid2.khaled
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views10 pages

ExamII (Fall2019)

This document is an exam for COE 312 - Data Structures, administered by Dr. Wissam F. Fawaz on December 12, 2019. It includes various problems related to data structures, recursion, algorithm analysis, and queues, with specific instructions for completion and grading. The exam consists of multiple-choice questions, coding tasks, and theoretical analysis, requiring students to demonstrate their understanding of data structures and algorithms.

Uploaded by

obeid2.khaled
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

1

COE 312 – Data Structures

Welcome to Exam II
Thursday December 12, 2019

Instructor: Dr. Wissam F. Fawaz

Name: _______________________

Student ID: ________________

Instructions:

1. This exam is Closed Book. Please do not forget to write your


name and ID on the first page.
2. You have exactly 115 minutes to complete the 7 required
problems.
3. Read each problem carefully. If something appears ambiguous,
please write your assumptions.
4. Points allocated to each problem are shown in square brackets.
5. Put your answers in the space provided only. No other spaces
will be graded or even looked at.

Good Luck!!
2

Problem 1: True or false Questions (15 minutes) [15 points]


1. The recursive solution of the towers of Hanoi problem has exponential complexity.
Answer: True False

2. An algorithm of order O(log2n) is considered asymptotically faster than an algorithm of order O(√𝑛)
Answer: True False

3. 𝑁 is 𝛺(𝑁 )
Answer: True False

4. All recursive methods must have a base case.


Answer: True False

5. 2𝑁 is 𝛳(𝑁)
Answer: True False

6. A total of 10 recursive method calls are needed to recursively calculate the Fibonacci of 4.
Answer: True False

7. 𝑁 is 𝑂(2 )
Answer: True False

8. An interface name can be used as a data type in Java.


Answer: True False

9. Consider an algorithm that matches parentheses using a stack. The maximum number of parentheses
that the stack will hold at any given moment when the algorithm analyzes the following sequence
is 3: (( )(()))
Answer: True False

10. In a circular drifting array-based implementation of a queue data structure, the dequeue operation
requires O(n) time, where n is the size of the queue.
Answer: True False

11. Suppose we have a circular drifting array-based implementation of a queue with 11 items stored in
the queue at indexes 2 through 12. Assume also that the array used to realize the queue has a
capacity of 13. In light of these facts, an enqueue operation would place a new element at index 0
of the queue.
Answer: True False

12. A stack is a FIFO data structure.


Answer: True False

13. Consider the case where a method called f1 that calls a different method called f2, which then
calls the original method f1. In this case, f1 is considered as a recursive method.
Answer: True False

14. The peek method of the java.util.Stack class returns the top element of the Stack.
Answer: True False

15. The Java language has a built-in queue class.


Answer: True False
3

Problem 2: Recursion (15 minutes) [10 points]


(1) Write a recursive method called countVowels that returns the number of vowels in a
string. Note that the vowels are the letters a, e, o, u, and i. Check the appendix for some of
the methods supported by the String class in Java.
int countVowels(String str) {
String vowels = "aeouiAEOUI";
if(str.length() == 0)
return 0;
else if(str.length() == 1) {
if(vowels.indexOf(str.charAt(0)) == -1)
return 0;
else
return 1;
} else if(vowels.indexOf(str.charAt(0)) == -1) {
return countVowels(str.substring(1));
} else {
return 1 + countVowels(str.substring(1));
}

}
(2) Write a recursive function that returns a String made up of the elements stored in an
ArrayList called al listed in reverse order. For instance, if the list contains the values
[1, 2], then the output String should be “2 1”. The function takes as a parameter a
reference to the ArrayList. Check the appendix for more details about the methods
offered by the ArrayList class.
String reverseToString(ArrayList<Integer> al) {
if(al.size() == 0)
return “”;
else if(al.size() == 1) {
return al.remove(0) + "";
} else {
Integer val = al.remove(0);
String str= reverseToString(al);
return str + " " + val;
}

}
4

Problem 3: Analysis of recursive algorithms (10 minutes) [12 points]


1. Unfold the following recurrence relation and obtain a big-Oh characterization, in terms of
N, for T(N). Show your work.
T(N) = T(N/2) + N
T(1) = 1
𝑁 𝑁 𝑁 𝑁 𝑁 𝑁 𝑁 𝑁
𝑇(𝑁) = 𝑇 +𝑁 =𝑇 + +𝑁 =𝑇 + + +𝑁 =⋯=𝑇 + + ⋯+ 𝑁
2 4 2 8 4 2 2 2
1
𝑁 1 1 1 𝑁 1−
=𝑇 +𝑁 + + ⋯+ =𝑇 +𝑁 2
2 2 2 2 2 1
1−
2

= 1 => 𝑘 = log (𝑁) =>

𝑇(𝑁) = 𝑇 +𝑁 =1+2×𝑁× = 2𝑁 − 1 => 𝑇(𝑁) is 𝑂(𝑁)

2. Unfold the following recurrence relation and obtain a big-Oh characterization, in terms of
N, for T(N). Show your work.
T(N) = 2T(N/2) + N
T(1) = 1
𝑁 𝑁 𝑁 𝑁
𝑇(𝑁) = 2 × 𝑇 +𝑁 =2× 2×𝑇 + +𝑁 =2 𝑇 +𝑁+𝑁
2 4 2 4
𝑁 𝑁 𝑁 𝑁
=2 2×𝑇 + + 2𝑁 = 2 𝑇 + 3𝑁 = ⋯ = 2 𝑇 + 𝑘𝑁
8 4 8 2

= 1 => 𝑘 = log (𝑁) =>


𝑇(𝑁) = 2 𝑇 + 𝑘𝑁 = 𝑁 + 𝑁𝑙𝑜𝑔 (𝑁) => 𝑇(𝑁) is 𝑂(𝑁𝑙𝑜𝑔2(𝑁))
5

Problem 4: Algorithm (15 minutes) [10 points]


1. You are given below the header of a method called swapBothHalves that returns a
modified version of the input ArrayList<Integer> L where both the first and second
halves of L are swapped. Assume that there is an even number of elements in L. For
example, if the array list L contains 2, 3, 4, 6, 7, 8 then the resulting output list would be
6, 7, 8, 2, 3, 4.
ArrayList<Integer> swapBothHalves(ArrayList<Integer> al) {
ArrayList<Integer> output = new ArrayList<Integer>();
int halfSize = al.size()/2;

for(int i=halfSize ; i<al.size(); i++)


output.add(al.get(i));
for(int i=0; i<halfSize; i++)
output.add(al.get(i));

return output;

}
2. Implement a method that destructively copies each value in an ArrayList, resulting in
an ArrayList that is twice as long. For example, if the input list contained [1, 2, 3], the
resulting list should contain [1, 1, 2, 2, 3, 3] after the call to this method.
ArrayList<Integer> copyDestructively(ArrayList<Integer> list){
ArrayList<Integer> output = new ArrayList<Integer>();

for(Integer value : list) {


output.add(value);
output.add(value);
}

return output

}
6

Problem 5: Code insertion (10 minutes) [8 points]


For each code below, fill in the blank so that the function has the desired runtime highlighted in
the comment. If the answer is impossible, just write “impossible” in the blank.

public static void f1(int N) { // desired runtime: O(N)


for (int i = 1; i < N; _i += 1) // Blank
{ System.out.println(“hi”); }
}

public static void f2(int N) { // desired runtime O(log N)


for (int i = 1; i < N; i *= 2) // Blank
{ System.out.println(“hi”); }
}

public static void f3(int N) { // desired runtime O(1)


for (int i = 1; i < N; i += N) // Blank
{ System.out.println(“hi”); }
}

public static void f4(int N) { // desired runtime O(2 N)


for (int i = 1; i < N; i++) {
for(int j=1; _j<=2*i; j++) { // Blank
System.out.println(“hi”);
}
}
}
7

Problem 6: Analysis of iterative algorithms (15 minutes) [10 points]


Give the runtime of the following functions in big-Oh notation. Your answer should be a function
of N that is as simple as possible with no unnecessary leading constants or lower order terms.
public static void f1(int N) {
for (int i = 0; i < N*N*N; i += 1) {
for (int j = 0; j < N*N*N; j += 1) {
System.out.print("fyhe");
}
}
}
Answer: __ O(N6)_________

public static void f2(int N) {


for (int i = 0; i < N; i += 1) {
int numJ = Math.pow(2, i + 1) - 1; // <-- constant time!
for (int j = 0; j < numJ; j += 1) {
System.out.print("fhet");
}
}
}
Answer: ___ O(log2N)________

public static void f3(int N) {


for (int i = 0; i < N; i += 1) {
for (int j = 1; j < N; j = j + 2) {
System.out.println(“hi!”);
}
}
}
Answer: ____ O(N2)_______

public static void f4(int N) {


for (int i = 0; i < N; i += 1) {
for (int j = 1; j < N; j = j * 2) {
System.out.println(“hi!”);
}
}
}
Answer: ____ O(Nlog2N)_______

public static void f5(int N) {


int sum = 0;
for (int i = N; i > 0; i -= 1) {
for (int j = 0; j < i; j += 1) {
sum += 1;
}
}}
Answer: _____ O(N2)______
8

Problem 7: Queues (35 minutes) [35 points]


1) Write a class called ArrayBasedQueue that represents a drifting circular array-
based queue data structure. In particular, you are required to:
a. Create the Queue ADT.
b. Implement the exception classes corresponding to the various types of
exceptions that may occur when using the queue.
c. Develop an array based queue class where the methods of the Queue ADT
are implemented to run in O(1) time.
d. Provide a driver class that uses the ArrayBasedQueue to solve the
Josephus problem in the context of a game involving 4 players.

public interface Queue {


public int size();
public boolean isEmpty();
public Object dequeue() throws QueueException;
public void enqueue(Object o) throws QueueException;
public Object front() throws QueueException;
}
public class QueueException extends Exception {
public QueueException(String msg) {
super(msg);
}
}
public class ArrayBasedQueue implements Queue {
private Object[] arr;
private int front, rear, size;
private StringBuilder sb;

public ArrayBasedQueue(int capacity) {


arr = new Object[capacity];
front = rear = size = 0;
sb = new StringBuilder();
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public Object dequeue() throws QueueException {
if(isEmpty())
throw new QueueException("Queue is empty!");
Object toReturn = arr[front];
size--;
arr[front] = null;
front = (front + 1)%arr.length;
sb.delete(0, toReturn.toString().length()+1);
return toReturn;
}
public void enqueue(Object o) throws QueueException {
if(size() == arr.length)
throw new QueueException("Queue is full!");
arr[rear] = o;
size++;
9

rear = (rear + 1) % arr.length;


sb.append(o + " ");
}
public Object front() throws QueueException {
if(isEmpty())
throw new QueueException("Queue is empty!");
return arr[front];
}
public String toString() {
return sb.toString();
}
}
import java.util.Scanner;
public class JosephusProblem {
public static void main(String[] args) {
String[] players = {"Michel", "Hussein", "Toufic"};
int k;
Scanner scan = new Scanner(System.in);
String winner;

System.out.println("Enter k: ");
k = scan.nextInt();

winner = solve(players, k);


System.out.println("Winner: " + winner);
}
private static String solve(String[] players, int k) {
String winner;
ArrayBasedQueue queue = new ArrayBasedQueue(players.length);
try {
for(String player : players)
queue.enqueue(player);

while(queue.size() > 1) {
System.out.println("Queue: " + queue);
for(int i=1; i<=k; i++)
queue.enqueue(queue.dequeue());
System.out.println(queue.dequeue() + " is out");
}
winner = (String) queue.dequeue();
} catch (QueueException e) {
winner = "Could not solve the problem";
}

return winner;
}
}
10

Appendix: Classes and Methods


ArrayList<T>
ArrayList<>(): creates an empty list
boolean add(T e): adds the element e at the end of arraylist
boolean add(int index, T e): adds e at specified index
T get(int index): gets the element at index
boolean remove(T e): removes first occurrence of e
T remove(int index): removes and returns element at index
int size(): returns the size of the list
boolean isEmpty()
boolean contains(T e): returns true if list contains e
int indexOf(T e): returns index of first occurrence of e
String
char charAt(int index): returns the character at index.
String concat(String str): returns a String consisting of this string concatenated with str.
int length(): returns the number of characters in this string
String substring(int offset, int endIndex): returns a new String that is a subset of this
string starting at index offset and extending through endIndex-1.
String substring(int offset): returns a new String consisting of all the characters having an
index of offset and higher.

You might also like