Last active
August 29, 2015 14:20
-
-
Save epitron/ef985019351b35d438cd to your computer and use it in GitHub Desktop.
Take the numbers 1 through 9, in order, and insert +'s and -'s (or nothing) such that the resulting mathematical expression evaluates to 100.
This file contains hidden or 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
# | |
# Recursively yield all possible expressions for the array of numbers | |
# | |
def exprs(nums) | |
n, *rest = nums | |
if rest.empty? | |
yield "#{n}" | |
else | |
exprs(rest) do |expr| | |
yield "#{n} + #{expr}" | |
yield "#{n} - #{expr}" | |
yield "#{n}#{expr}" | |
end | |
end | |
end | |
# | |
# Print out all expressions that evaluate to 100 | |
# | |
exprs([1, 2, 3, 4, 5, 6, 7, 8, 9]) do |expr| | |
puts "#{expr} = 100" if eval(expr) == 100 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output:
1 + 23 - 4 + 56 + 7 + 8 + 9 = 100
12 + 3 - 4 + 5 + 67 + 8 + 9 = 100
1 + 2 + 34 - 5 + 67 - 8 + 9 = 100
1 + 2 + 3 - 4 + 5 + 6 + 78 + 9 = 100
123 - 4 - 5 - 6 - 7 + 8 - 9 = 100
123 + 45 - 67 + 8 - 9 = 100
1 + 23 - 4 + 5 + 6 + 78 - 9 = 100
12 - 3 - 4 + 5 - 6 + 7 + 89 = 100
12 + 3 + 4 + 5 - 6 - 7 + 89 = 100
123 - 45 - 67 + 89 = 100
123 + 4 - 5 + 67 - 89 = 100