Suppose you have an elevator that only consists of up and down buttons.
It means that it can only go up as much as “up” or go down as much as “down”.
Suppose we want to go from floor A to B. Using the dynamic programming method, write an algorithm that moves from floor A to B with the least number of button presses.
Input: up, down, A, B, and the output is the least number of button presses.
This is my pseudo code but it doesn’t work.
FUNCTION calclMinSteps(startPos, destination, upVal, downVal, r, s):
IF startPos < 0 OR startPos > destination OR startPos > 11:
RETURN MAX_VALUE - 1
IF (destination - startPos) MOD upVal == 0:
s[startPos] = upVal
RETURN (destination - startPos) / upVal
IF r[startPos] != 0:
RETURN r[startPos]
p = calclMinSteps(startPos + upVal, destination, upVal, downVal, r, s) + 1
IF upVal != downVal:
q = calclMinSteps(startPos - downVal, destination, upVal, downVal, r, s) + 1
IF p < q:
r[startPos] = p
s[startPos] = upVal
RETURN p
ELSE:
r[startPos] = q
s[startPos] = downVal
RETURN q
ELSE:
RETURN p
`
alireza is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.