gets f=->s,a{x,y,z,w=((a||[])+[0]*4).map &:to_i;s+=d=[x+z,x+w,y+w].max x>0?f[s,a[d==x+z ? 4:5,$$]]:s} p f[0,gets.split]