Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit afaed26

Browse files
author
hasibulislam999
committed
Can I Win problem solved
1 parent 9af2fd1 commit afaed26

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

‎Game Theory/464_can-i-win.js‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* Title: Can I Win
3+
* Description: In the "100 game" two players take turns adding, to a running total, any integer from 1 to 10. The player who first causes the running total to reach or exceed 100 wins.
4+
* Author: Hasibul Islam
5+
* Date: 06/05/2023
6+
*/
7+
8+
/**
9+
* @param {number} maxChoosableInteger
10+
* @param {number} desiredTotal
11+
* @return {boolean}
12+
*/
13+
function canIWin(maxChoosableInteger, desiredTotal) {
14+
if (desiredTotal === 0) return true;
15+
if ((maxChoosableInteger * (maxChoosableInteger + 1)) / 2 < desiredTotal)
16+
return false;
17+
18+
const initialChoices = Math.pow(2, maxChoosableInteger) - 1;
19+
20+
const dp = [];
21+
22+
function DP(choices, total) {
23+
if (total <= 0) return false;
24+
25+
if (dp[choices] !== undefined) {
26+
return dp[choices];
27+
}
28+
29+
let pow = 0;
30+
let choicesCopy = choices;
31+
32+
dp[choices] = false;
33+
34+
while (choicesCopy > 0) {
35+
if (choicesCopy % 2 && !DP(choices - (1 << pow), total - pow - 1)) {
36+
dp[choices] = true;
37+
break;
38+
}
39+
choicesCopy >>= 1;
40+
pow++;
41+
}
42+
43+
return dp[choices];
44+
}
45+
46+
return DP(initialChoices, desiredTotal);
47+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /