- Related Questions & Answers
- Stone Game in C++
- Elimination Game in C++
- Dungeon Game in C++
- Zuma Game in C++
- 24 Game in C++
- Nim Game in C++
- Jump Game III in C++
- Card Flipping Game in C++
- Stone Game II in C++
- Chalkboard XOR Game in C++
- Jump Game V in C++
- Jump Game IV in C++
- Stone Game III in C++
- Flip Game II in C++
- A Number Link Game in C/C++?

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

#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)); }

6 1 10

0.6

Advertisements