Created
December 29, 2011 07:19
-
-
Save manishym/1532543 to your computer and use it in GitHub Desktop.
Converting tree recursive process into iterative process
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defun crazy-func (n) | |
(cond ((< n 3) n) | |
(t (+ (crazy-func (- n 1)) | |
(* 2 (crazy-func (- n 2) )) | |
(* 3 (crazy-func (- n 3))))))) | |
(defun crazy-func-iter (n) | |
(crazy-iter 2 1 0 3 n)) | |
;;; iter alogrithm: | |
; let us store cf of n-1, n-2 and n-3 as state variables. At any point, we can | |
; return the caly of crazy-func if we have these values. | |
; let a=n-1, b=n-2 c=n-3, cf(n) = a+2b+3c | |
; cf(n+1) = a+2b+3c + a + b | |
(defun crazy-iter (a b c count n) | |
(if (> count n) | |
a | |
(crazy-iter (+ a (* 2 b) (* 3 c)) a b (1+ count) n ))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment