Skip to content

Instantly share code, notes, and snippets.

@nyuichi
Created May 17, 2011 15:16
Show Gist options
  • Save nyuichi/976664 to your computer and use it in GitHub Desktop.
Save nyuichi/976664 to your computer and use it in GitHub Desktop.
四則ソルバー in Clojure
(use 'clojure.contrib.combinatorics)
(def seeds [7 7 7 9 11 11])
(def answer 218/100)
(defn drop-nth [n coll]
(concat (take n coll)
(drop (inc n) coll)))
(defn comb [n m]
(combinations (range n) m))
(def comb (memoize comb))
(defn choose-2 [coll n m]
(let [a (nth coll n)
b (nth coll m)
rest (drop-nth n (drop-nth m coll))]
[a b rest]))
(defn choose-random-2 [coll]
(for [[a b] (comb (count coll) 2)]
(choose-2 coll a b)))
(defn single? [coll]
(empty? (rest coll)))
(defmacro concatfor [seq-exprs body-expr]
`(apply concat (for ~seq-exprs ~body-expr)))
(defmacro go [op a b coll]
`(let [r# (~op ~a ~b)
n# (conj ~coll r#)
s# (sisoku (sort n#))]
(if (empty? s#)
s#
(map #(conj % (str '~op) ~a ~b) s#))))
(defn sisoku [seeds]
"Return a sequence of answers"
(if (single? seeds)
(if (= (first seeds) answer)
[seeds]
[])
(concatfor [[a b r] (choose-random-2 seeds)]
(concat (go + a b r)
(go - a b r)
(go - b a r)
(go * a b r)
(when-not (zero? b)
(go / a b r))
(when-not (zero? a)
(go / b a r))))))
(def sisoku (memoize sisoku))
; REPLから(sisoku seeds)ってしてね♡
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment