# An animal climbing something (forward/backward slide): is there a generalized solution?

A snail is at the bottom of a 30 foot well. Every hour the snail is able to climb up 3 feet, then immediately slide back down 2 feet. How many hours does it take for the snail to get out of the well?

I know the answer. But I also like generalizing things. Is there a general formula for resolving this kind of puzzle? The formula must work in every single particular case of general distance, speed up, and speed down.

Assuming the animal doesn't leave the well early enough for the problem to be trivial, a working formula would look like this:

$$t(h_0+kd+r) = t_0 + kp + τ(r)$$

where $$h_0$$ is the height of the first "peak" (3 feet), $$t_0$$ is the time at which it occurs (1 hour), $$p$$ is the time between peaks (also 1 hour), $$d$$ is the distance between peaks (1 foot), and $$τ$$ is an auxiliary function $$[0,d) \mapsto [0,p)$$ that describes the times at which intermediate distances are reached, for cases like "this riddle with 30 feet replaced by 30.5 feet" ($$τ(0)=0,τ(0).

Applying this formula yields

$$t(3+27×1+0) = 1+27×1+0 = 28$$ hours, as desired

To calculate the number of hours it takes for the snail to get out of the well, we can use the following formula:

This is a function of javascript for general cases:
function snail(column, hourClimb, hourFall) {
 const days = (column - hourFall) / (hourClimb - hourFall);
 return days < 1 ? 1 : Math.ceil(days);
}

Let's apply this formula to the current scenario:

Number of hours = (30 - 3) / (3 - 2) + 1 = 27 / 1 + 1 = 27 + 1 = 28

• the code isn't really helping, and you don't explain your reasoning May 29 at 11:45
• the code is the general algorithm to solve this problem May 29 at 15:18

t = d / (pv - nv)

Where,
t = time
d = distance
pv = positive velocity
nv = negative velocity

• this fails to account for the "peak" where the snail reaches the top and then would slide back down, but doesn't. That's why the answer with javascript in it subtracts how much it falls each hour from the total height before dividing. May 29 at 11:45