DEV Community

Discussion on: Daily Challenge #198 - 21 Blackjack

Collapse
 
centanomics profile image
Cent

Javascript

This solution doesn't consider the fact that an ace could be both a 1 and an 11 (2+ aces in a hand). But this solution does solve all of the tests


const blackJack = (cards) => {
  let total = [0, 0]
  cards.forEach((card) => {
    switch(card) {
      case "2":
      case "3":
      case "4":
      case "5":
      case "6":
      case "7":
      case "8":
      case "9":
      case "10":
        total[0] += parseInt(card);
        total[1] += parseInt(card);
        break;
      case "J":
      case "Q":
      case "K":
        total[0] += 10;
        total[1] += 10;
        break;
      case "A":
        total[0] += 1;
        total[1] += 11;
        break;
    }
  })

  return Math.max(...total) <= 21 ? Math.max(...total) : Math.min(...total)
}

Enter fullscreen mode Exit fullscreen mode

Codepen