# Probability of reaching a point with 2 or 3 steps at a time in C++

C++Server Side ProgrammingProgramming

A person “A” is walking from a starting position X = 0, the task is to find the probability to reach exactly X = num, if he/she can either take 2 or 3 steps. Probability for step length 2 i.e. P, the probability for the step length 3 is 1 - P.

Input

num = 5, p = 0.2

Output

0.32

Explanation

There can be 2 ways to reach num, i.e, 5
2+3 with probability 0.2 * 0.8 = 0.16
3+2 with probability 0.8 * 0.2 = 0.16
So, total probability will be 0.16 + 0.16 = 0.32

Input

num = 2, p = 0.1

Output

0.1

## Approach used below is as follows to solve the problem

We will be using dynamic programming approach to solve the problem.

In the solution we will −

• Declare a probability array whose size is num+1 and assign its values as, Set probab[0] = 1, Set probab[1] = 0, Set probab[2] = p, Set probab[3] = 1 – p

• Iterate i from 0 to num, while increment its value

• For every i, Set probab[i] = (p)*probab[i - 2] + (1 - p) * probab[i - 3]

• Return the probab[num]

• Print result.

## Algorithm

Start
Step 1→ declare function to calculate probability of reaching a point with 2 or 3 steps
at a time
float probab(int num, float p)
Declare double probab[num + 1]
Set probab[0] = 1
Set probab[1] = 0
Set probab[2] = p
Set probab[3] = 1 – p
Loop For int i = 4 and i <= num and ++i
Set probab[i] = (p)*probab[i - 2] + (1 - p) * probab[i - 3]
End
return probab[num]
Step 2→ In main()
Declare int num = 2
Declare float p = 0.1
Call probab(num, p)
Stop

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
//function to calculate probability of reaching a point with 2 or 3 steps at a time
float probab(int num, float p){
double probab[num + 1];
probab[0] = 1;
probab[1] = 0;
probab[2] = p;
probab[3] = 1 - p;
for (int i = 4; i <= num; ++i)
probab[i] = (p)*probab[i - 2] + (1 - p) * probab[i - 3];
return probab[num];
}
int main(){
int num = 2;
float p = 0.1;
cout<<"probability is : "<<probab(num, p);
return 0;
}

## Output

If run the above code it will generate the following output −

probability is : 0.1`
Published on 13-Aug-2020 07:21:48