I'm trying to implement a function defined as such:
f(n) = n if n < 4
f(n) = f(n - 1) + 2f(n - 2) + 3f(n - 3) + 4f(n - 4) if n >= 4
The iterative way to do this would be to start at the bottom until I hit n
, so if n = 6:
f(4) = (3) + 2(2) + 3(1) + 4(0) | 10
f(5) = f(4) + 2(3) + 3(2) + 4(1) | 10 + 16 = 26
f(6) = f(5) + 2f(4) + 3(3) + 4(2) | 26 + 2(10) + 17 = 63
Implementation attempt:
; m1...m4 | The results of the previous calculations (eg. f(n-1), f(n-2), etc.)
; result | The result thus far
; counter | The current iteration of the loop--starts at 4 and ends at n
(define (fourf-iter n)
(cond [(< n 4) n]
[else
(define (helper m1 m2 m3 m4 result counter)
(cond [(= counter n) result]
[(helper result m1 m2 m3 (+ result m1 (* 2 m2) (* 3 m3) (* 4 m4)) (+ counter 1))]))
(helper 3 2 1 0 10 4)]))
Several problems:
- The returned result is one iteration less than what it's supposed to be, because the actual calculations don't take place until the recursive call
- Instead of using the defined algorithm to calculate f(4), I'm just putting it right in there that
f(4) = 10
- Ideally I want to start
result
at 0 andcounter
at 3 so that the calculations are applied tom1
throughm4
(and so thatf(4)
will actually be calculated out instead of being preset), but then0
gets used for m1 in the next iteration when it should be the result off(4)
instead (10
)
tl;dr either the result calculation is delayed, or the result itself is delayed. How can I write this properly?