Skip to content

Instantly share code, notes, and snippets.

@masui
Last active August 29, 2015 14:21
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 masui/89fa67d47c1925f89329 to your computer and use it in GitHub Desktop.
Save masui/89fa67d47c1925f89329 to your computer and use it in GitHub Desktop.
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