Skip to content

Instantly share code, notes, and snippets.

@timraymond
Created Jun 5, 2015
Embed
What would you like to do?
Possible expressions involving the digits 1-9 and operators "-" and "+"
def expressions(nums)
first, second = nums.slice(0, nums.length/2), nums.slice(nums.length/2, nums.length)
if first == ""
return [second]
end
left_sub = expressions(first)
right_sub = expressions(second)
exprs = []
left_sub.each do |l|
right_sub.each do |r|
exprs << "#{l}+#{r}"
exprs << "#{l}-#{r}"
exprs << "#{l}#{r}"
end
end
return exprs
end
expressions("123456789").map {|expr| [expr, eval(expr)] }.select{ |expr,total| total == 100 }.each {|expr, _| puts expr}
# 1+2+3-4+5+6+78+9
# 1+23-4+5+6+78-9
# 1+23-4+56+7+8+9
# 1+2+34-5+67-8+9
# 12+3+4+5-6-7+89
# 123+4-5+67-89
# 123+45-67+8-9
# 12+3-4+5+67+8+9
# 12-3-4+5-6+7+89
# 123-4-5-6-7+8-9
# 123-45-67+89
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment