Quick actions

cmd+k|ctrl+k

Navigation

Languages

Blackjack hand value

Snippet info

Language

TypeScript

Visibility

public

Author

kodlikejamesz

Created

2024-05-23T10:23:07.984425Z

Updated

2024-06-06T20:31:58.69846Z

function blackjackHandValue(hand: string[]): number {
    let totalPoints = 0;
    let aces = 0;

    hand.forEach(card => {
        let value = card.split(' ')[0]; // ดึงอันดับของการ์ด
        switch (value) {
            case 'Ace':
                aces += 1;
                totalPoints += 11; // เริ่มต้นด้วยการนับ Ace เป็น 11
                break;
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
            case '10':
                totalPoints += parseInt(value);
                break;
            case 'Jack':
            case 'Queen':
            case 'King':
                totalPoints += 10;
                break;
        }
    });

    // ปรับค่า Ace จาก 11 เป็น 1 หากจำเป็น
    while (totalPoints > 21 && aces > 0) {
        totalPoints -= 10;
        aces -= 1;
    }

    return totalPoints;
}

// ตัวอย่างการใช้งาน
const hand = ["Ace of Spades", "10 of Hearts", "3 of Clubs"];
console.log(blackjackHandValue(hand)); // Output: 14
INFO