Skip to content

Instantly share code, notes, and snippets.

@timraymond
Created June 5, 2015 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timraymond/f3d0bb86c8a14cde3f9a to your computer and use it in GitHub Desktop.
Save timraymond/f3d0bb86c8a14cde3f9a to your computer and use it in GitHub Desktop.
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