quarta-feira, 14 de março de 2012

Dynamic racket pascal


Through HN, I have stumbled upon Cletus blog, and I have
read this
of his. It enticed me to try out some version of mine for
the dynamic programming version. Here it is, coded in racket with a
contract and a small test case.
#lang racket

(provide (contract-out
          [pascal-triangle (-> exact-positive-integer? vector?)]))

(define (pascal-triangle n)
  (define (loop accumulator row)
    (if (= n row)
        (let* ([previous (vector-ref accumulator
                                     (sub1 (vector-length accumulator)))]
                (vector-append #(1)
                               (for/vector ((i (in-range 1 row)))
                                           (+ (vector-ref previous (sub1 i))
                                              (vector-ref previous i)))
          (loop (vector-append accumulator (vector current-row)) (add1 row)))))
  (loop #(#(1)) 1))

(for ([row (pascal-triangle 30)])
     (displayln row))

See you.

Nenhum comentário:

Postar um comentário