Skip to content

Instantly share code, notes, and snippets.

@viesti
Last active January 12, 2018 22:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save viesti/9740db2407304bba6dd13f7390b3d81b to your computer and use it in GitHub Desktop.
Save viesti/9740db2407304bba6dd13f7390b3d81b to your computer and use it in GitHub Desktop.
;; Solves math excercise:
;; 9 = 5 [ ] 3 [ ] 4 [ ] 5,
;; , where [ ] should be one of operations: +, -
;; Uses just random brute force :)
user> (def ops #{+ -})
user> (loop [cnt 0
op1 (first ops)
op2 (first ops)
op3 (first ops)]
(let [eq [9 (op3 (op2 (op1 5 3) 4) 5)]
opname #(-> % .getClass .getName clojure.main/demunge (.split "/") second)]
(cond
(= cnt 20) (println "result not found in" 20 "iterations")
(apply = eq) (println (str "result found after " cnt " iterations: "
(->> [op1 op2 op3]
(map opname)
(clojure.string/join " "))))
:else (recur (inc cnt)
(rand-nth (seq ops))
(rand-nth (seq ops))
(rand-nth (seq ops))))))
result found after 5 iterations: + - +
user> ;; Version that uses infix library (https://github.com/rm-hull/infix) to allow using infix notation
user> (def ops #{'+ '-})
#'user/ops
user> (loop [cnt 0
op1 (first ops)
op2 (first ops)
op3 (first ops)]
(let [eq [9 (eval (ic/rewrite (list 5 op1 3 op2 4 op3 5)))]]
(cond
(= cnt 20) (println "result not found in" 20 "iterations")
(apply = eq) (println (str "result found after " cnt " iterations: "
(clojure.string/join " " [op1 op2 op3])))
:else (recur (inc cnt)
(rand-nth (seq ops))
(rand-nth (seq ops))
(rand-nth (seq ops))))))
result found after 6 iterations: + - +
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment