Skip to content

Instantly share code, notes, and snippets.

@tonytonyjan
Last active January 6, 2016 17:36
Show Gist options
  • Save tonytonyjan/03792f2f803e3971f6d2 to your computer and use it in GitHub Desktop.
Save tonytonyjan/03792f2f803e3971f6d2 to your computer and use it in GitHub Desktop.
Bulls and Cows
answer = 0.upto(9).to_a.sample(4).join
while true
puts 'wrong format, should be 4 digits.' until (guess = gets.chop!) =~ /^\d{4}$/
a = b = 0
guess.each_char.each_with_index do |c1, idx1|
answer.each_char.each_with_index do |c2, idx2|
if c1 == c2
idx1 == idx2 ? a += 1 : b += 1
break
end
end
end
if a == 4
puts 'Bingo!'
break
else
puts "#{a}a#{b}b"
end
end
answers = '0123456789'.chars.permutation(4).to_a.map!(&:join)
while answers.length > 1
answer = answers.sample
puts %Q{Is it #{answer}?}
puts 'wrong format, soubld be "{number}a{number}b"' until gets.chop! =~ /^(\d)[Aa](\d)[Bb]$/
answers.select! do |possible|
a = b = 0
possible.each_char.each_with_index do |c1, idx1|
answer.each_char.each_with_index do |c2, idx2|
if c1 == c2
idx1 == idx2 ? a += 1 : b += 1
break
end
end
end
$1.to_i == a && $2.to_i == b
end
if answers.length == 1
puts "The answer is #{answers.first}!"
elsif answers.empty?
puts 'You cheat!'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment