Skip to content

Instantly share code, notes, and snippets.

@epitron
Last active August 29, 2015 14:20
Show Gist options
  • Save epitron/ef985019351b35d438cd to your computer and use it in GitHub Desktop.
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.
#
# 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
@epitron
Copy link
Author

epitron commented May 10, 2015

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment