Uploaded by Bethe Change

Muskan PAssignment1 Eso207

advertisement
Muskan
190520
Hackerrank username: muskangoel245
Programming Assignment 1
1a
Alvonia (A)is connected to Borginia (B) and Carpania(C). Similarly Borginia(B) is connected to
Alvonia(A) and Carpanica(C). To travel from B-> A , C->A or A->B will take one day.
Now A(n), B(n) and C(n) are the total number of ways such that you end up in Alvonia, Borginia
and Carpania at the end of nth day, respectively.
Day 0
-> A(0)= Ways that you end up in Alvonia after the 0th day. It is given that you are in Alvonia at
day 0 so this is the only way. Hence A(0)=1
-> B(0)=Ways that you end up in Borginia after the 0th day.It is given that at the start of Day 1,
you will travel for the first time. So there is no way I can reach Borginia after the 0th day. Hence
B(0)=0.
-> C(0)=Ways that you end up in Carpanica after the 0th day.It is given that at the start of Day 1,
you will travel for the first time. So there is no way I can reach Carpanica after the 0th day.
Hence C(0)=0
Now let's say I want to reach A on the 3rd day, then I have to be at either B or C on the 2nd day.
It is given that you will travel on each day so this rules out the possibility of being at A on 2nd
and 3rd day. Now the problem reduces to calculate number of ways for (n-1)th day for city B
and C.
So to reach city X(for example A) at the end of nth day, I have to be at a connected city ( B or C)
on (n-1)th day.It is sufficient to calculate the number of ways to reach the connected cities at (n1)th day and then sum over them to get the number of ways to reach city X.
Mathematically,
A(n)=B(n-1)+C(n-1)
B(n)=A(n-1)+C(n-1)
C(n)=A(n-1)+B(n-1)
(1)
(2)
(3)
At the end of nth day
A(n)
B(n)
C(n)
n=0
1
0
0
n=1
0
1
1
n=2
2
1
1
n=3
2
3
3
n=4
6
5
5
It is clearly visible that entries in this table follow equation 1,2,3.
From equation 2 and 3
Replacing n by n-1
B(n-1)=A(n-2)+C(n-2)
C(n-1)=A(n-2)+B(n-2)
Adding these two equations
B(n-1)+C(n-1)=2A(n-2)+C(n-2)+B(n-2)
A(n) =2A(n-2)+A(n-1)
A(n) =2A(n-2)+A(n-1)
B(n) =2B(n-2)+B(n-1)
We will use equations 1,2,3 only to solve further parts.
C part
Equations 1,2,3 can be rewritten as
A(n)=0*A(n-1) +1*B(n-1) +1*C(n-1)
B(n)=1*A(n-1) +0*B(n-1) +1*C(n-1)
C(n)=1*A(n-1) +1*B(n-1) +0*C(n-1)
(1)
(2)
(3)
C(n) =2C(n-2)+C(n-1)
𝐴(𝑛)
0
(𝐡(𝑛)) = (1
𝐢(𝑛)
1
1 1 𝐴(𝑛 − 1)
0 1) (𝐡(𝑛 − 1))
1 0 𝐢(𝑛 − 1)
𝐴(𝑛)
0
(𝐡(𝑛)) = (1
1
𝐢(𝑛)
1 1
0 1)
1 0
1
(0 )
0
Download