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

ADS

The document covers key concepts in recursion, including its definition, the importance of base conditions, and potential errors like stack overflow. It also provides examples of recursive functions in Java, as well as discussions on hash codes, hash tables, and graph representations. Additionally, it addresses tree structures, including nodes, ancestors, descendants, and their properties.
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)
8 views10 pages

ADS

The document covers key concepts in recursion, including its definition, the importance of base conditions, and potential errors like stack overflow. It also provides examples of recursive functions in Java, as well as discussions on hash codes, hash tables, and graph representations. Additionally, it addresses tree structures, including nodes, ancestors, descendants, and their properties.
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

Page 49:

1. What is Recursion?
Recursion is a programming technique where a function calls itself in order
to solve a problem. It breaks down a problem into smaller, more
manageable sub-problems of the same type. Recursive functions typically
have a base case that stops the recursion and prevents infinite loops.
2. What is base condition in recursion?
The base condition (or base case) in recursion is a condition that stops the
recursive calls. It is a critical part of a recursive function because it defines
the simplest instance of the problem that can be solved directly, without
further recursion. Without a base condition, the function would call itself
indefinitely, leading to a stack overflow error.
3. Why Stack Overflow error occurs in recursion?
A stack overflow error occurs in recursion when the recursive function calls
itself too many times without reaching a base condition. Each function call
consumes a certain amount of stack space, and if the recursion is too
deep (i.e., too many nested calls), it can exceed the stack size limit,
causing a stack overflow.
4. What is the importance of the stopping case in recursive functions?
The stopping case, or base case, is crucial in recursive functions because
it prevents infinite recursion and ensures that the function eventually
terminates. It provides a condition under which the function can return a
result without making further recursive calls, thus allowing the recursion to
unwind and produce a final result.
5. Recursive function for the mathematical function:

public class RecursiveFunction {


public static int f(int n) {
if (n == 1) {
return 1;
} else {
return 2 * f(n - 1);
}
}

public static void main(String[] args) {


int result = f(5); // Example usage
System.out.println("f(5) = " + result);
}
}

6. Function using Recursion to print numbers from n to 0::

public class PrintNumbers {


public static void printNumbers(int n) {
if (n < 0) {
return;
} else {
System.out.println(n);
printNumbers(n - 1);
}
}

public static void main(String[] args) {


printNumbers(5); // Example usage
}
}
7. Output for the following version of reverse():
import java.io.IOException;

public class ReverseString {


public static void reverse() throws IOException {
int ch = getChar();
if (ch != '\n') {
reverse();
}
System.out.print((char) ch);
}

public static int getChar() throws IOException {


return System.in.read();
}

public static void main(String[] args) throws IOException {


System.out.println("Enter a string followed by Enter:");
reverse();
}
}

//—------------------------------------------------------------------------------------------------------------------------------------------------------------
Page 74:
Question 1: Hash Code for Vehicle Identification Numbers

To generate a good hash code for a vehicle identification number (VIN) such as “9XXX9X9XX99999”:

● Assign values to letters and digits, e.g., ′0′→0,′1′→1,…,′X′→10'0' \rightarrow 0, '1' \rightarrow 1,
\dots, 'X' \rightarrow 10′0′→0,′1′→1,…,′X′→10.
● Sum the weighted values (weight can be positional, like multiplying each character's value by its
index).
● Return the result modulo the table size mmm.

public class VINHash {


public static int hashCode(String vin, int tableSize) {
int hash = 0;
for (int i = 0; i < vin.length(); i++) {
int value = (vin.charAt(i) == 'X') ? 10 :
Character.getNumericValue(vin.charAt(i));
hash += value * (i + 1);
}
return hash % tableSize;
}

public static void main(String[] args) {


String vin = "9XXX9X9XX99999";
int tableSize = 11;
System.out.println("Hash Code: " + hashCode(vin, tableSize));
}
}

Question 2: Hash Table with Chaining

Using the function h(i)=(3i+5)mod 11h(i) = (3i + 5) \mod 11h(i)=(3i+5)mod11, hash the keys: 12, 44, 13,
88, 23, 94, 11, 39, 20, 16, 5.

Steps:

1. Compute h(i)h(i)h(i) for each key.


2. Place each key in its corresponding bucket (using chaining for collisions).

Key h(i)h(i)h(i) Bucket

12 (3×12 + 5) % 11 = 10 10 → [12]

44 (3×44 + 5) % 11 = 7 7 → [44]

13 (3×13 + 5) % 11 = 5 5 → [13]

88 (3×88 + 5) % 11 = 3 3 → [88]

23 (3×23 + 5) % 11 = 5 5 → [13, 23]

94 (3×94 + 5) % 11 = 10 10 → [12, 94]

11 (3×11 + 5) % 11 = 9 9 → [11]

39 (3×39 + 5) % 11 = 3 3 → [88, 39]

20 (3×20 + 5) % 11 = 7 7 → [44, 20]

16 (3×16 + 5) % 11 = 10 10 → [12, 94, 16]

5 (3×5 + 5) % 11 = 9 9 → [11, 5]

Final Hash Table (Chaining):


0: -
1: -
2: -
3: [88, 39]
4: -
5: [13, 23]
6: -
7: [44, 20]
8: -
9: [11, 5]
10: [12, 94, 16]

Question 3: Hash Table with Linear Probing

Linear probing resolves collisions by checking the next available slot.

Steps:

1. Calculate h(i)h(i)h(i) and place the key. If occupied, move sequentially until an empty slot is found.

Result:

Key h(i)h(i)h Placement Slot


(i)

12 10 10

44 7 7

13 5 5

88 3 3

23 5→6 6

94 10 → 0 0

11 9 9

39 3→4 4

20 7→8 8

16 10 → 1 1

5 9→2 2
Final Hash Table (Linear Probing):

makefile
Copy code
0: 94
1: 16
2: 5
3: 88
4: 39
5: 13
6: 23
7: 44
8: 20
9: 11
10: 12

Question 8: Different Probing Methods

Given keys = [67, 815, 45, 39, 2, 901, 34] and table size m=11m = 11m=11:

(a) Linear Probe (c=1c = 1c=1)


h(i)=key%11h(i) = key \% 11h(i)=key%11

Insert keys sequentially, shifting to the next slot when occupied.

(b) Linear Probe (c=3c = 3c=3)


h(i)=(key+c×attempt)%11h(i) = (key + c \times attempt) \% 11h(i)=(key+c×attempt)%11

Question 9 & 10

For rehashing with new hash functions, follow the same insertion logic after computing the new
h(i)h(i)h(i).

//—------------------------------------------------------------------------------
Page 105:

2. If GGG is a simple undirected graph with 12 vertices and 3 connected components,


what is the largest number of edges it might have?

For a graph with:

● V=12V = 12V=12 vertices,


● 3 connected components.

To maximize edges:

● Allocate vertices as evenly as possible among the components: 4,4,44, 4, 44,4,4.


● In a simple graph, the maximum edges in a component of kkk vertices is
k(k−1)2\frac{k(k-1)}{2}2k(k−1)​.

Thus:

● For each component with 4 vertices: 4(4−1)2=6\frac{4(4-1)}{2} = 624(4−1)​=6 edges.


● Total edges: 3×6=183 \times 6 = 183×6=18.

Answer: The largest number of edges is 18.

3. Draw an adjacency matrix representation of the undirected graph shown in Figure 14.1.

Since Figure 14.1 is missing, I cannot draw the exact matrix. However, to represent an
undirected graph:

● Use a square matrix AAA where A[i][j]=1A[i][j] = 1A[i][j]=1 if there is an edge between
vertex iii and vertex jjj, otherwise A[i][j]=0A[i][j] = 0A[i][j]=0.
● AAA is symmetric for undirected graphs.

4. Draw an adjacency list representation of the undirected graph shown in Figure 14.1.

Adjacency list:

● Use a list of vertices where each vertex points to its neighbors (connected vertices).

Example:
1 → [2, 3]
2 → [1, 4]
3 → [1]
4 → [2]

5. Why does insertVertex take O(1)O(1)O(1) and removeVertex take O(m)O(m)O(m) in


the edge list structure?

● InsertVertex: Adding a new vertex involves appending it to a list, which is O(1)O(1)O(1)


time complexity.
● RemoveVertex: Removing a vertex requires scanning through the edge list (size mmm)
to delete all edges associated with the vertex, which takes O(m)O(m)O(m).

6. Give pseudocode for insertEdge(u, v, x) in O(1)O(1)O(1) time using the adjacency


matrix representation.

Pseudocode in Java:

java
Copy code
void insertEdge(int[][] matrix, int u, int v, int x) {
matrix[u][v] = x; // Add weight x at (u, v)
matrix[v][u] = x; // For undirected graph, mirror the edge
}

Explanation:

● O(1)O(1)O(1) because accessing and updating an element in a 2D matrix is constant


time.

7. Would you use the adjacency matrix or adjacency list?

a. The graph has 10,000 vertices and 20,000 edges, and it is important to use as little
space as possible.

● Use adjacency list because:


○ Adjacency matrix requires V2=108V^2 = 10^8V2=108 space.
○ Adjacency list only requires O(V+E)=10,000+20,000=30,000O(V + E) = 10,000 +
20,000 = 30,000O(V+E)=10,000+20,000=30,000.
b. The graph has 10,000 vertices and 20,000,000 edges, and it is important to use as little
space as possible.

● Use adjacency list because:


○ Matrix still takes 10810^8108 space, which is too large.
○ Adjacency list requires O(V+E)=10,000+20,000,000O(V + E) = 10,000 +
20,000,000O(V+E)=10,000+20,000,000, which is far smaller.

c. You need to answer getEdge(u, v) as fast as possible, no matter how much space
you use.

● Use adjacency matrix because:


○ Accessing matrix[u][v]matrix[u][v]matrix[u][v] is O(1)O(1)O(1) time.
○ Adjacency list would take O(degree(u))O(\text{degree}(u))O(degree(u)) time.

//—------------------------------------------------------------------------------
Page 131:

a. Which node is the root?


The root node is /user/rt/courses/.

b. What are the internal nodes?


Internal nodes are nodes that have children. They are:

● /user/rt/courses/
● cs016/
● cs252/
● homeworks/
● programs/
● projects/
● papers/

c. How many descendants does node cs016/ have?


Node cs016/ has 6 descendants:

● grades
● homeworks/
○ hw1, hw2, hw3
● programs/
○ pr1, pr2, pr3
d. How many ancestors does node cs016/ have?
Node cs016/ has 1 ancestor: /user/rt/courses/.

e. What are the siblings of node homeworks/?


The siblings of homeworks/ are:

● grades
● programs/

f. Which nodes are in the subtree rooted at node projects/?


The nodes in the subtree rooted at projects/ are:

● papers/
○ buylow, sellhigh
● demos/
○ market

g. What is the depth of node papers/?


The depth of papers/ is 3.

● Root (/user/rt/courses/) → Depth 0


● cs252/ → Depth 1
● projects/ → Depth 2
● papers/ → Depth 3

h. What is the height of the tree?


The height of the tree is 4.

● From the root /user/rt/courses/ to the deepest leaf node (buylow, sellhigh,
market) → there are 4 levels.

You might also like