Professional Documents
Culture Documents
Week16Lecture S21 Induction To Recursion 11012023 095027pm 20022023 061608pm
Week16Lecture S21 Induction To Recursion 11012023 095027pm 20022023 061608pm
Tahir Iqbal
Bahria University Lahore Campus
Covering Chessboard with Triminos
Covering Chessboard with Triminos
Covering 2xN Grid with Dominos
• In how many ways we can cover a 2𝑥𝑁 grid with dominos.
• Grid has 2 rows and 𝑁 columns.
• We want to cover it with 1𝑥2 domino-tiles.
Covering 2xN Grid with Dominos
• In how many ways we can cover a 2𝑥𝑁 grid with dominos.
Covering 2xN Grid with Dominos
• In how many ways we can cover a 2𝑥𝑁 grid with dominos.
Example
Stone-picking Game
Example
Game of Nim
Rules:
There are 3 piles of stone.
Each player, on his turn, may pick any number of
stones from any one pile.
Player, who picks up the last stone in the game, wins
the game.
Write Code !
Power Function – revisited
• How to compute 𝑎𝑛 ?
• 𝑎𝑛 = 𝑎 ∗ 𝑎𝑛−1
Write Code !
How to Code ?
else return a;
{ else
int ans = power(a, n/2); {
if (n % 2 == 0) if (n % 2 == 0)
return ans * ans;
return power(a, n/2) * power(a, n/2);
else
else
return ans * ans * a;
return power(a, n/2) * power(a, n/2)
}
* a;
} }
}
Power Function
int power (int a, int n) int power (int a, int n)
{ How many recursive {
else return a;
{
int ans = power(a, n/2);
𝑂 𝑁 vs 𝑂 log 𝑁 else
{
if (n % 2 == 0) if (n % 2 == 0)
return ans * ans;
return power(a, n/2) * power(a, n/2);
else
return ans * ans * a; (Make trees of both) else
return power(a, n/2) * power(a, n/2)
}
* a;
} }
}
Power Function
Fibonacci Sequence
• 𝐹𝑛 = 𝐹𝑛−1 + 𝐹𝑛−2
Write code …
Fibonacci Sequence
• 𝐹𝑛 = 𝐹𝑛−1 + 𝐹𝑛−2
Write code …
Recursive relation?
Write code?
Factorial
int factorial (int n)
{
if ( (n == 0) || (n == 1) )
return 1;
else
{
return n * factorial(n-1);
}
}
Combinations (Later with Counting)
Combinations (Later with Counting)
int choose (int n, int k)
{
if ( (k == 0) || (n == 0 ) )
return 1;
else
return choose (n-1, k) + choose(n-1, k-1) ;
}
Permutations (Later with Counting)
• Example: {1,2,3} --- permutations?
Recursion as “Navigating through a Maze”
• We can look at all recursive programs as variations on the process of
navigating through a maze.
How does a computer solve a maze like the
following?
The first step is to convert the graphic into a
numerical representation.
• The following maybe be done manually or through a program.
This information can be stored in a 2D array
0 1 2 3 4 5 ...
0 0 0 0 0 0 0
1 0 0 0 0 0 1
2 0 0 0 0 0 0
3 0 0 0 0 1 0
4 0 0 0 1 0 1
5 0 1 0 0 1 0
…
Looking at the maze or the stacks in not really useful in analyzing a program for time and space!
From the tree of the maze problem, you can compute the
total time for the recursive program