OSDN Git Service

[1] A function 'lin-solve' was added.
[ierope/bitcalc.git] / dynamics / src / math.clj
1 (ns src.math)
2 ;(alias 'cl 'clojure.core)
3
4 (defn neg-index [cnt x]
5   (if (neg? x) (+ cnt x) x))
6
7 (defn swap [i j s]
8   (let [[i j] (map (partial neg-index (count s)) [i j])]
9     (assoc (assoc (vec s) i (nth s j))
10            j (nth s i)
11            )))
12
13 (defn search-non-zero [mat pivot]
14   (let [width (count (first mat))
15         height (count mat)]
16     (first (for [j (range pivot (dec width))
17                  i (range pivot height)
18                  :when (not= 0 (nth (nth mat i) j))]
19                 [i j]))))
20
21 (defn lin-solve [mat]
22   (let [width  (count (first mat))
23         height (count mat)]
24     (loop [pivot 0 m (vec (map vec mat))]
25       (if (>= pivot (max (dec width) height))
26         m
27         (let [[col row] (search-non-zero mat pivot)]
28           (if (nil? col)
29             m
30             (recur (inc pivot)
31                    (swap pivot row
32                          (map (partial swap pivot col) m)
33                          ))))))))