Implement a function that determines the score of a hand in the card game 21 Blackjack.
The function will receive an array filled with strings that represent each card in the hand. Your function should return the score of the hand as an integer.
Number cards count as their face value (2 through 10). Jack, Queen and King count as 10. An Ace can be counted as either 1 or 11.
Return the highest score of the cards that is less than or equal to 21. If there is no score less than or equal to 21 return the smallest score more than 21.
Examples
["A"] ==> 11
["5", "4", "3", "2", "A", "K"] ==> 25
Tests
["A", "J"]
["A", "10", "A"]
["5", "3", "7"]
This challenge comes from jodymgustafson on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (10)
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
Codepen
In Python:
Clojure ✌🏿
Elixir
Some recursion
In Ruby. Iterate over each card and total as you go. If it's a face card, count is as 10. If it's a number card, count is as what it is. If it's an ace and the current score is below 21 and counting an ace as a 11 wouldn't push it over 21, count is as 11. Otherwise, count is a 1.
The examples
A possible flaw is that you should be seeing cards one at a time, instead of as a whole then deciding on how to handle aces.
A .map or .inject method could clean this up in Ruby.
Isn't
(["5", "3", "7"]) # ==> 21
wrong.Python
C++
Code can be optimized by caculating
scoreCount
seperately and then passingit as an argument in the function.
Test cases --
Output --
Elm
From what I understood about the game, the cards are revealed at each draw. I may have implemented a wrong version though.
Tests