Last active
January 12, 2018 22:09
-
-
Save viesti/9740db2407304bba6dd13f7390b3d81b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; 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