Dana Vrajitoru
C311 Programming Languages

Dynammic Programming

Dynamic Programming

Bottom-Up DP

Fibonacci

(defun fib1 (n)
  (if (<= n 1) 1
    (+ (fib1 (- n 1))
       (fib1 (- n 2)))))

(defun fib (n)
  (let ((f0 1) (f1 1) (f 1) (i 2))
    (while (<= i n)
      (setq f (+ f0 f1) f0 f1 f1 f i (+ i 1)))
    f))

(fib 5) ; 8

Top-Down DP

Combinations
C(n, m) = n! / (m! (n-m)! )
C(n, m) = C(n-1, m) + C(n-1, m-1)

(defun comb (n m)
  (cond
   ((= n m) 1)
   ((= m 0) 1)
   ((= m 1) n)
   (t (+ (comb (- n 1) m)
         (comb (- n 1) (- m 1))))))
(comb 3 2) ; 3
(comb 5 2) ; 10

Improved version with DP:

(defun el10 (n m)
  (+ (* n 10) m)) ; 10*n+m

(setq C (make-vector 200 nil))

(defun comb1 (n m)
  (let ((res 0))
    (if (setq res (elt C (el10 n m))) res
      (setq res
            (cond
             ((= n m) 1)
             ((= m 0) 0)
             ((= m 1) n)
             (t (+ (comb1 (- n 1) m)
                   (comb1 (- n 1) 
                          (- m 1))))))
      (aset C (el10 n m) res))))

(comb1 7 3) ; 35
(comb1 10 5) ; 252

Knapsack Problem

General Solution
For every possible object Oi(sizei, valuei) of size less or equal to the capacity of the knapsack:

Simple Recursive Solution

(defun knapsack (S Olist)
  "Simple recursive knapsack."
  (if (= S 0) 0
    (let ((maxval 0) (res 0) (size 0) 
          (val 0))
      (dolist (c Olist maxval)
        (setq size (car c) val (cdr c))
        (cond ((>= S size)
               (setq res (knapsack 
                          (- S size) Olist))
               (if (> (+ res val) maxval)
                   (setq maxval 
                         (+ res val))))))))
(setq Obj-list '((3 . 4) (4 . 5) (7 . 10) 
                 (8 . 11) (9 . 13)))
(knapsack 17 Obj-list) ; 24

Solution with DP

(setq store (make-vector 20 nil))

(defun knapsack1 (S Olist)
  "Recursive knapsack with dynamic programming."
  (let ((maxval 0) (res 0) (size 0) (val 0))
    (cond ((setq res (elt store S)) res)
          ((= S 0) 0)
          (t
           (dolist (c Olist maxval)
             (setq size (car c) val (cdr c))
             (cond ((>= S size)
                    (setq res (knapsack1 
                               (- S size) Olist))
                    (if (> (+ res val) maxval)
                        (setq maxval (+ res
                                        val))))))
           (aset store S maxval)))))

(knapsack1 17 Obj-list); 24