Skip to content

Instantly share code, notes, and snippets.

@pifst
Created October 21, 2013 01:59
Show Gist options
  • Save pifst/da149545afe388a5bbb1 to your computer and use it in GitHub Desktop.
Save pifst/da149545afe388a5bbb1 to your computer and use it in GitHub Desktop.
Given a string ex. "7 10 7 3 4 7', find the optimal cards to play in blackjack, return in same form.
def format_input(input)
array = input.split(" ")
royals = {"10"=>0, "J"=>0, "Q"=>0, "K"=>0}
i = 0
begin
royals[royals.keys[i]] = array.count(royals.keys[i]) unless array.count(royals.keys[i]).zero?
array.map!{ |x| x == royals.keys[i] ? "10" : x }
i += 1
end while i <= royals.length
#puts "#{royals}"
array.map!(&:to_i)
end
def generate(card_set, n)
Hash[card_set.combination(n).map { |cards| [cards, cards.inject(:+)] }.keep_if { |_, sum| sum < 22 }.sort_by { |_, v| v }.reverse]
end
def reduce(gen_hash)
Hash[gen_hash.map { |k, v| [k, v.invert.max] }.max_by { |_, v| v.first }]
end
def cards(best_hand)
best_hand.flatten[1]*" "
end
def sum(best_hand)
best_hand.flatten[0]
end
hand = format_input(ARGV[0])
#hand = [7,7,7,8,8,5]
iterate = 2
groups = {}
begin
groups[(iterate)] = generate(hand, iterate) unless generate(hand, iterate).empty?
iterate += 1
end while iterate <= hand.count
best_hand = reduce(groups)
puts "The optimal blackjack hand is \"#{cards(best_hand)}\" for #{sum(best_hand)} points."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment