Basic JavaScript Counting Cards

In the casino game Blackjack, a player can gain an advantage over the house by keeping track of the relative number of high and low cards remaining in the deck. This is called Card Counting.

Having more high cards remaining in the deck favors the player. Each card is assigned a value according to the table below. When the count is positive, the player should bet high. When the count is zero or negative, the player should bet low.

Count ChangeCards
+12, 3, 4, 5, 6
07, 8, 9
-110, ‘J’, ‘Q’, ‘K’, ‘A’

You will write a card counting function. It will receive a card parameter, which can be a number or a string, and increment or decrement the global count variable according to the card’s value (see table). The function will then return a string with the current count and the string Bet if the count is positive, or Hold if the count is zero or negative. The current count and the player’s decision (Bet or Hold) should be separated by a single space.

Example Output
-3 Hold
5 Bet

Hint
Do NOT reset count to 0 when value is 7, 8, or 9.
Do NOT return an array.
Do NOT include quotes (single or double) in the output.

Solution 1

// CountingCards.js
let count = 0;

function CountingCards(card) {
    let regex = /[JQKA]/;
    
    if (card > 1 && card < 7) {
        count++;
    } else if (card === 10 || card.toString().match(regex)) {
        count--;
    }
    
    if (count > 0) 
        return count + " Bet";
    return count + " Hold";
}

console.log(CountingCards(2));
console.log(CountingCards(3));
console.log(CountingCards(7));
console.log(CountingCards('K'));
console.log(CountingCards('A'));

Solution 2

let count = 0;

function CountingCards(card) {
    switch (card) {
        case 2:
        case 3:
        case 4:
        case 5case 6:
            count++;
            break;
        case 10:
        case 'J':
        case 'Q':
        case 'K':
        case 'A':
            count--;
            break;            
    }
    if (count > 0) {
        return count + " Bet";
    } else {
        return count + " Hold";
    }
}

console.log(CountingCards(2));
console.log(CountingCards(3));
console.log(CountingCards(7));
console.log(CountingCards('K'));
console.log(CountingCards('A'));

Cards Sequence 2, 3, 4, 5, 6 should return 5 Bet

Cards Sequence 7, 8, 9 should return 0 Hold

Cards Sequence 10, J, Q, K, A should return -5 Hold

Cards Sequence 3, 7, Q, 8, A should return -1 Hold

Cards Sequence 2, J, 9, 2, 7 should return 1 Bet

Cards Sequence 2, 2, 10 should return 1 Bet

Cards Sequence 3, 2, A, 10, K should return -1 Hold

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值