Skip to content

Instantly share code, notes, and snippets.

@biesnecker
Created January 31, 2012 03:59
Show Gist options
  • Save biesnecker/1708690 to your computer and use it in GitHub Desktop.
Save biesnecker/1708690 to your computer and use it in GitHub Desktop.
Stirling numbers
(defn- stirling-loop-internal
[^long n ^long k compfunc]
{ :pre [(<= k n)] }
(let [workitems (for [n' (range 1 (inc n)) k' (range 0 (inc (- n k)))
:when (and (>= (- n' k') 0) (>= k (- n' k')))] [n' (- n' k')])]
(loop [current (first workitems) items (rest workitems) results {}]
(cond
(= current [n k]) ((compfunc current results) current)
(= (current 0) (current 1))
(recur (first items) (rest items)
(assoc results current 1))
(= (current 1) 0)
(recur (first items) (rest items)
(assoc results current 0))
:else
(recur (first items) (rest items)
(compfunc current results))))))
(defn stirling-1
"Returns the Stirling number of the first kind s(n, k)"
[^long n ^long k]
{ :pre [(<= k n) (>= k 0) (pos? n)] }
(stirling-loop-internal n k
(fn [[n' k'] resultmap]
(assoc resultmap [n' k']
(- (resultmap [(dec n') (dec k')])
(*' (dec n') (resultmap [(dec n') k'])))))))
(defn stirling-2
"Returns the Stirling number of the second kind s(n, k)"
[^long n ^long k]
{ :pre [(<= k n) (>= k 0) (pos? n)] }
(stirling-loop-internal n k
(fn [[n' k'] resultmap]
(assoc resultmap [n' k']
(- (resultmap [(dec n') (dec k')])
(*' k' (resultmap [(dec n') k'])))))))
(defn stirling-1-recursive
"Returns the Stirling number of the first kind s(n, k) (recursively)."
[n k]
{ :pre [(<= k n) (>= k 0) (pos? n)] }
(cond
(= k n) 1
(= k 0) 0
:else (- (stirling-1-recursive (dec n) (dec k))
(*' (dec n) (stirling-1-recursive (dec n) k)))))
(defn stirling-2-recursive
"Returns the Stirling number of the second kind s(n, k) (recursively)."
[n k]
{ :pre [(<= k n) (>= k 0) (pos? n)] }
(cond
(= k n) 1
(= k 0) 0
:else (- (stirling-2-recursive (dec n) (dec k))
(*' k (stirling-2-recursive (dec n) k)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment