Created
November 21, 2024 03:47
-
-
Save jbranchaud/8eb832603f4e89fd98a9868544a64873 to your computer and use it in GitHub Desktop.
Send More Money solved with Ruby (brute-force)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Send More Money | |
# | |
# Verbal Arithmetic https://en.wikipedia.org/wiki/Verbal_arithmetic | |
letters = %i[s e n d m o r y] | |
check = ->(vals) do | |
# leading zeros are not allowed | |
return false if vals[:s] == 0 || vals[:m] == 0 | |
send = ("%{s}%{e}%{n}%{d}" % vals).to_i | |
more = ("%{m}%{o}%{r}%{e}" % vals).to_i | |
money = ("%{m}%{o}%{n}%{e}%{y}" % vals).to_i | |
send + more == money | |
end | |
# this makes 10 items for 0 through 9 assignments | |
items = letters + [nil, nil] | |
items.permutation.each_with_index do |set, i| | |
number_processed = i + 1 | |
solution = set # one permutation of letters + 2 nils | |
.zip(0..9).to_h # zip into hash with positions, aka values | |
.reject { |key, _| key.nil? } # throw out the nils | |
case solution | |
when check | |
puts "" # newline | |
puts "Solution Found (potential solutions processed: #{number_processed})" | |
puts solution | |
break | |
else | |
print "." | |
end | |
end | |
# Solution Found (potential solutions processed: 2005114) | |
# {:o=>0, :m=>1, :y=>2, :e=>5, :n=>6, :d=>7, :r=>8, :s=>9} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment