AtCoder Beginner Contest 115 D

学んだこと
  • 解説を見ずに再帰を発想できたかった。
  • メソッド定義の外側で宣言したローカル変数はメソッド定義内でつかえないみたい。大文字から始めて定数にするか、@をつけてインスタンス変数にすればメソッド定義内でつかえる。(どちらがいいのだろうか。)
n,x = gets.chomp.split.map(&:to_i)

# レベルiの層の厚さをt[i]に、レベルiのパテ数の合計をp[i]に格納する
@t = [1]
@p = [1]
n.times do
    @t << @t.last*2+3
    @p << @p.last*2+1
end

def f(n,x)
    if n == 0
        return 1
    else
        case x
        when 1
            return 0
        when 2..@t[n-1]+1
            return f(n-1,x-1)
        when @t[n-1]+2
            return @p[n-1] + 1
        when @t[n-1]+3..@t[n]-1
            return @p[n-1]+1+f(n-1,x-2-@t[n-1])
        when @t[n]
            return @p[n]
        end
    end
end

p f(n,x)