
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
New 21 Game in C++
Suppose Rima plays the following game, that is loosely based on the card game "21". So Rima starts with 0 points, and draws numbers while she has less than K points. Now, during each draw, she gains an integer number of points randomly from the range [1, W], where W is given, and that is an integer. Now each draw is independent and the outcomes have equal probabilities. Rima stops drawing numbers when she gets K or more points. We have to find the probability that she has N or less points?
So if N = 6, K is 1 and W is 10, then the answer will be 0.6, as Rima gets a single card, then stops, In 6 out of 10 probabilities, She is at or below N = 6 points.
To solve this, we will follow these steps −
- If k is 0, or N >= K + W, then return 1
- make an array dp of size N + 1, set dp[0] := 1
- set wsum := 1.0, ret := 0.0
- for i in range 1 to N
- dp[i] := wsum / W
- if i < K, then wsum := wsum + dp[i], otherwise ret := ret + dp[i]
- if i – W >= 0, then wsum := wsum – dp[i - W]
- return ret
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: double new21Game(int N, int K, int W) { if(K == 0 || N >= K + W) return 1.0; vector <double> dp (N + 1); dp[0] = 1; double Wsum = 1.0; double ret = 0.0; for(int i = 1; i <= N; i++){ dp[i] = Wsum / W; if(i < K){ Wsum += dp[i]; }else ret += dp[i]; if(i - W >= 0) Wsum -= dp[i - W]; } return ret; } }; main(){ Solution ob; cout << (ob.new21Game(6, 1, 10)); }
Input
6 1 10
Output
0.6