- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the probability of reaching all points after N moves from point N in C++
Suppose we have a number N this represents the initial position of the person on the number line. We also have L which is the probability of the person of going left. We have to find the the probability of reaching all points on the number line after completing N moves from point N. Each move can be either to the left or to the right.
So, if the input is like n = 2, l = 0.5, then the output will be [0.25, 0, 0.5, 0, 0.25]
To solve this, we will follow these steps −
high := 1 - low
Define an array A of size: n+1 x 2*n+1 and fill with 0
A[1, n + 1] = high, A[1, n - 1] = low
for initialize i := 2, when i <= n, update (increase i by 1), do −
for initialize j := 1, when j −= 2 * n, update (increase j by 1), do −
A[i, j] := A[i, j] + (A[i - 1, j - 1] * high)
for initialize j := 2 * n - 1, when j >= 0, update (decrease j by 1), do −
A[i, j] := A[i, j] + (A[i - 1, j + 1] * low)
for initialize i := 0, when i − 2*n+1, update (increase i by 1), do −
display A[n, i]
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; void find_prob(int n, double low) { double high = 1 - low; double A[n + 1][2 * n + 1] = {{0}}; A[1][n + 1] = high; A[1][n - 1] = low; for (int i = 2; i <= n; i++) { for (int j = 1; j <= 2 * n; j++) A[i][j] += (A[i - 1][j - 1] * high); for (int j = 2 * n - 1; j >= 0; j--) A[i][j] += (A[i - 1][j + 1] * low); } for (int i = 0; i < 2*n+1; i++) cout << A[n][i] << endl; } int main() { int n = 2; double low = 0.6; find_prob(n, low); }
Input
2, 0.6
Output
0.36 0 0.48 0 0.16