Created
May 23, 2015 04:22
-
-
Save WizardOfOgz/0c8859492f70c2d6f5e6 to your computer and use it in GitHub Desktop.
Sum digits to 100
This file contains 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
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