Just another update
This commit is contained in:
parent
a25938f123
commit
00a190b0a6
6591 changed files with 94363 additions and 23227 deletions
|
|
@ -1,30 +1,25 @@
|
|||
(use 'clojure.contrib.combinatorics)
|
||||
(ns rosettacode.24game.solve
|
||||
(:require [clojure.math.combinatorics :as c]
|
||||
[clojure.walk :as w]))
|
||||
|
||||
(defn nested-replace [l m]
|
||||
(cond
|
||||
(= l '()) '()
|
||||
(m (first l)) (concat (list (m (first l))) (nested-replace (rest l) m))
|
||||
(seq? (first l)) (concat (list (nested-replace (first l) m)) (nested-replace (rest l) m))
|
||||
true (concat (list (first l)) (nested-replace (rest l) m))))
|
||||
(def ^:private op-maps
|
||||
(map #(zipmap [:o1 :o2 :o3] %) (c/selections '(* + - /) 3)))
|
||||
|
||||
(defn format-solution [sol]
|
||||
(cond
|
||||
(number? sol) sol
|
||||
(seq? sol)
|
||||
(list (format-solution (second sol)) (first sol) (format-solution (nth sol 2)))))
|
||||
(def ^:private patterns '(
|
||||
(:o1 (:o2 :n1 :n2) (:o3 :n3 :n4))
|
||||
(:o1 :n1 (:o2 :n2 (:o3 :n3 :n4)))
|
||||
(:o1 (:o2 (:o3 :n1 :n2) :n3) :n4)))
|
||||
|
||||
(defn play24 [& digits] (count (map #(-> % format-solution println)
|
||||
(let [operator-map-list (map (fn [a] {:op1 (nth a 0) :op2 (nth a 1) :op3 (nth a 2)})
|
||||
(selections '(* + - /) 3))
|
||||
digits-map-list
|
||||
(map (fn [a] {:num1 (nth a 0) :num2 (nth a 1) :num3 (nth a 2) :num4 (nth a 3)})
|
||||
(permutations digits))
|
||||
patterns-list (list
|
||||
'(:op1 (:op2 :num1 :num2) (:op3 :num3 :num4))
|
||||
'(:op1 :num1 (:op2 :num2 (:op3 :num3 :num4))))
|
||||
;other patterns can be added here, e.g. '(:op1 (:op2 (:op3 :num1 :num2) :num3) :num4)
|
||||
op-subbed (reduce concat '()
|
||||
(map (fn [a] (map #(nested-replace a % ) operator-map-list)) patterns-list))
|
||||
full-subbed (reduce concat '()
|
||||
(map (fn [a] (map #(nested-replace % a) op-subbed)) digits-map-list))]
|
||||
(filter #(= (try (eval %) (catch Exception e nil)) 24) full-subbed)))))
|
||||
(defn play24 [& digits]
|
||||
{:pre (and (every? #(not= 0 %) digits)
|
||||
(= (count digits) 4))}
|
||||
(->> (for [:let [digit-maps
|
||||
(->> digits sort c/permutations
|
||||
(map #(zipmap [:n1 :n2 :n3 :n4] %)))]
|
||||
om op-maps, dm digit-maps]
|
||||
(w/prewalk-replace dm
|
||||
(w/prewalk-replace om patterns)))
|
||||
(filter #(= (eval %) 24))
|
||||
(map println)
|
||||
doall
|
||||
count))
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue