Last active
August 29, 2015 14:21
-
-
Save masui/89fa67d47c1925f89329 to your computer and use it in GitHub Desktop.
1時間以内に解けなければプログラマ失格となってしまう5つの問題(2)
This file contains hidden or 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
# | |
# https://blog.svpino.com/2015/05/08/solution-to-problem-5-and-some-other-thoughts-about-this-type-of-questions | |
# | |
def power(n, alts, &block) | |
_power(n, 0, [], alts, &block) | |
end | |
def _power(total, level, res, alts, &block) | |
if level < total then | |
alts.each { |op| | |
res[level] = op | |
_power total, level+1, res, alts, &block | |
} | |
else | |
yield res | |
end | |
end | |
power(8,['+','-','']){ |arg| | |
# arg = ['', '+', '+', '-', '', '+', '-', ''] => exp = '12+3+4-56+7-89' | |
exp = [] | |
(1..9).each_with_index{ |v,i| exp[i*2] = v } | |
arg.each_with_index{ |v,i| exp[i*2+1] = v } | |
exp = exp.join('') | |
val = eval(exp) | |
puts "#{exp} ==> #{val}" if val == 100 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment