iboss
iboss

Reputation: 486

Ruby : stack level too deep (SystemStackError)

I try to solve this problem http://www.nattee.net/~dae/algo/prob/hw03b_tiling/problem.pdf

So I using divide and conquer method to solve it but when I execute my program I get

tile.rb:7: stack level too deep (SystemStackError)

And this is my code

def tile (x, y, bx, by, ex, ey)
    mx = (bx+ex)/2
    my = (by+ey)/2

    if (by<=y && y<=my)
        if (bx<=x && x<=mx) # top-left
            puts "0 #{mx} #{my}"
        elsif (mx+1<=x && x<=ex) # top-right
            puts "1 #{mx} #{my}"
        end
    elsif (my+1<=y && y<=ey)
        if (bx<=x && x<=mx) # bottom-left
            puts "2 #{mx} #{my}"
        elsif (mx+1<=x && x<=ex) # bottom-right
            puts "3 #{mx} #{my}"
        end
    end

    tile(x,y,bx,by,mx,my) #top-left
    tile(x,y,mx+1,by,ey,my) #top-right
    tile(x,y,bx,my+1,mx+1,ey)   #bottom-left
    tile(x,y,mx+1,my+1,ex,ey) #bottom-right

    if ex-bx == 2 && ey-by == 2 then return end
end

temp = []
gets.chomp.strip.split(" ").each do |item|
temp << item.to_i
end

L = temp[0]
x = temp[1]
y = temp[2]

tile(x,y,0,0,L-1,L-1)

I can't find the cause.

Upvotes: 0

Views: 3057

Answers (1)

DGM
DGM

Reputation: 26979

There is no way out of your recursion - for every call to tile, it will make 4 more calls to tile. Recursion always needs a "relief valve" way out before the recursion call. Try moving your return up before the tile calls.

The return statement could stand to be written in more idiomatic ruby.

Try:

return if (ex-bx == 2 && ey-by == 2)

Upvotes: 6

Related Questions