Jump to content

Pascal's triangle/Puzzle: Difference between revisions

no edit summary
m (Fixed lang tags.)
No edit summary
Line 201:
x= 5.00 y=13.00 z= 8.00
</pre>
 
=={{header|Clojure}}==
 
X and Z are the independent variables, so first work bottom up and determine the value of each cell in the form (n0 + n1*X + n2*Z). We'll use a vector [n0 n1 n2] to represent each cell.
<lang lisp>
(def bottom [ [0 1 0], [11 0 0], [0 1 1], [4 0 0], [0 0 1] ])
 
(defn plus [v1 v2] (vec (map + v1 v2)))
(defn minus [v1 v2] (vec (map - v1 v2)))
(defn scale [n v] (vec (map #(* n %) v )))
 
(defn above [row] (map #(apply plus %) (partition 2 1 row)))
 
(def rows (reverse (take 5 (iterate above bottom))))
</lang>
We know the integer value of cells c00 and c20 ( base-0 row then column numbers), so by subtracting these values we get two equations of the form 0=n0+n1*X+n2*Z.
<lang lisp>
(def c00 (-> rows (nth 0) (nth 0)))
(def c20 (-> rows (nth 2) (nth 0)))
 
(def eqn0 (minus c00 [151 0 0]))
(def eqn1 (minus c20 [ 40 0 0]))
</lang>
In this case, there are only two variables, so solving the system of linear equations is simple.
<lang lisp>
(defn solve [m]
(assert (<= 1 m 2))
(let [n (- 3 m)
v0 (scale (eqn1 n) eqn0)
v1 (scale (eqn0 n) eqn1)
vd (minus v0 v1)]
(assert (zero? (vd n)))
(/ (- (vd 0)) (vd m))))
 
(let [x (solve 1), z (solve 2), y (+ x z)]
(println "x =" x ", y =" y ", z =" z))
</lang>
 
 
=={{header|Haskell}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.