Skip to content

Instantly share code, notes, and snippets.

@WizardOfOgz
Created May 23, 2015 04:22
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 WizardOfOgz/0c8859492f70c2d6f5e6 to your computer and use it in GitHub Desktop.
Save WizardOfOgz/0c8859492f70c2d6f5e6 to your computer and use it in GitHub Desktop.
Sum digits to 100
def sum_digits_to(n)
enumerator = Enumerator.new do |yielder|
# recursive proc (backtracking) which iterates over all possible
# combinations of digits and operators.
p = -> prev_lhs = "", digit = 1 do
lhs = "#{ prev_lhs }#{ digit }"
if digit == 9
yielder << lhs if eval(lhs) == n
else
[" + ", " - ", nil].each do |op|
p.call("#{ lhs }#{ op }", digit.next)
end
end
end
p.call
end
enumerator.to_a
end
puts sum_digits_to(100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment