0

I have an exercise where I should count the ways of climbing a ladder with n amount of steps, with the following restriction: You can only go up by 1, 3 or 5 steps.

I readed that I should use Fibonacci recursion. So I adapted that restriction to the examples of 1, 2 and 3 steps rules that I could find.

(define (climb n)
   (cond [(<= n 0) 0]
         [(<= n 2) 1]
         [(= n 3) 2]
         [(> n 1) (+ (climb (- n 1)) (climb (- n 3)) (climb (- n 5)))]
   )
)

But this don't work, for example: with (climb 5) the output is 4 and should be 5:

(1 1 1 1 1), (1 3), (3 1), (3 1 1), (1 3 1), (1 1 3), (5). The 5 ways of climbing the ladder.

Risker
  • 358
  • 3
  • 15

2 Answers2

0

Update your base conditions, return 1 when the input value is equal to 0. For example, for input 5, you can climb the ladder using step 5 only. Which will generate a situation like, climb(5): 5-5 = 0.

The following fix will help:

(define (climb n)
   (cond [(< n 0) 0]   <---- updated here
         [(<= n 2) 1]
         [(= n 3) 2]
         [(> n 1) (+ (climb (- n 1)) (climb (- n 3)) (climb (- n 5)))]
   )
)

Another valid solution:

(define (climb n)
   (cond [(< n 0) 0]
         [(= n 0) 1]
         [(> n 0) (+ (climb (- n 1)) (climb (- n 3)) (climb (- n 5)))]
   )
)

Algorithm:

func Count(x):
 if x < 0: return 0
 if x == 0: return 1
 return Count(x-1)+Count(x-3)+Count(x-5)
end
Kamol Hasan
  • 12,218
  • 1
  • 37
  • 46
0

A simple dynamic programming algorithm can solve this problem.

The function is like this:

f(n < 1) = 0,
f(1) = 1,
f(2) = 1,
f(3) = 2,
f(4) = 3,
f(5) = 5,
f(n > 5) = f(n - 1) + f(n - 3) + f(n - 5)

It may look like Fibonacci in the beginning but soon you note it's different.

f(7) =         f(6)         + f(4) + f(2)
f(7) = (f(5) + f(3) + f(1)) + f(4) + f(2)
f(7) =   5   +  2   +  1    +  3   +  1
f(7) = 12  //fibonacci value should be 13
Daniel
  • 7,357
  • 7
  • 32
  • 84