DEV Community

Discussion on: Daily Challenge #198 - 21 Blackjack

Collapse
 
scrabill profile image
Shannon Crabill

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.

def total(array)
  count = 0
  face_cards = ["J","Q","K"]

  array.each do |card|
    if face_cards.include?(card)
      count = count + 10
    elsif card == "A"
      count = count + 1
    else
      count = count + card.to_i
    end
  end

  if count < 21 && array.include?("A")
    if count + 10 <= 21
      count = count + 10
    end
  end

  count

end

The examples

total(["A"]) # ==> 11
total(["5", "4", "3", "2", "A", "K"]) # ==> 25
total(["A", "J"]) # ==> 21
total(["A", "10", "A"]) # ==> 12
total(["5", "3", "7"]) # ==> 21

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.

Collapse
 
maskedman99 profile image
Rohit Prasad • Edited

Isn't (["5", "3", "7"]) # ==> 21 wrong.