-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathproblem_238.js
More file actions
64 lines (53 loc) Β· 1.38 KB
/
problem_238.js
File metadata and controls
64 lines (53 loc) Β· 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/* eslint-disable no-restricted-syntax */
const suits = ['β ', 'β₯', 'β¦', 'β£'];
const ranks = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10];
function Card(suit, rank) {
this.suit = suit;
this.rank = rank;
}
const generateDeck = () => {
const deck = [];
for (const suit of suits) {
for (const rank of ranks) {
const card = new Card(suit, rank);
deck.push(card);
}
}
return deck;
};
/**
* Maximizes player score in Blackjack
* @param {Card[]} deck
* @return {number}
*/
function maxPlayerScore(deck) {
if (deck.length < 4) return 0;
const dealer = deck[0].rank + deck[1].rank;
const player = deck[2].rank;
let max = Number.MIN_VALUE;
const start = 3;
let cards = 1;
while (true) {
let playerHand = player;
let dealerHand = dealer;
let next = start;
for (let i = 0; i < cards; i++) {
if (next === deck.length) return 0;
playerHand += deck[next].rank;
next += 1;
}
if (playerHand > 21) break;
while (dealerHand < 17) {
if (next === deck.length) return 0;
dealerHand += deck[next].rank;
next += 1;
}
if (dealerHand > 21 || playerHand > dealerHand)
max = Math.max(max, 1 + maxPlayerScore(deck.slice(next)));
else max = Math.max(max, maxPlayerScore(deck.slice(next)));
cards += 1;
}
return max;
}
const deck = generateDeck();
console.log(maxPlayerScore(deck)); // 8