Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
1時間以内に解けなければプログラマ失格となってしまう5つの問題(2)
#
# 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
You can’t perform that action at this time.