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 cfd0e46

Browse files
author
hasibulislam999
committed
Sum Game problem solved
1 parent e0510ec commit cfd0e46

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

‎Game Theory/1927_sum-game.js‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* Title: Sum Game
3+
* Description: Alice and Bob take turns playing a game, with Alice starting first.
4+
* Author: Hasibul Islam
5+
* Date: 06/05/2023
6+
*/
7+
8+
/**
9+
* @param {string} num
10+
* @return {boolean}
11+
*/
12+
var sumGame = function (num) {
13+
const middle = num.length / 2;
14+
// < 0 - the sum on the right side is bigger
15+
// > 0 - the sum on the left side is bigger
16+
let diff = 0;
17+
// < 0 - question marks have left on the left side
18+
// > 0 - question marks have left on the right side
19+
let turns = 0;
20+
21+
// turns- diff+ help to ensure that the sum on the side with question marks
22+
// is lower than the other one
23+
for (let i = 0; i < middle; i += 1) {
24+
if (num[i] === "?") {
25+
turns -= 1;
26+
} else {
27+
diff += num[i] - "0";
28+
}
29+
}
30+
31+
// counting pure diffs
32+
for (let i = middle; i < num.length; i += 1) {
33+
if (num[i] === "?") {
34+
turns += 1;
35+
} else {
36+
diff -= num[i] - "0";
37+
}
38+
}
39+
40+
// Alice wins if the number of turns doesn't allow Bob
41+
// to keep playing a change by 9 per 2 turns: (Alice-Bob) 0-9 1-8 2-7 3-6 etc,
42+
// which would reduce the diff of sums to 0 in the end.
43+
return diff !== turns * 4.5;
44+
};

0 commit comments

Comments
(0)

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