Skip to content

Instantly share code, notes, and snippets.

@kaz-yos
Created November 29, 2014 06:47
Show Gist options
  • Save kaz-yos/54ae2a180c7c82a79a6d to your computer and use it in GitHub Desktop.
Save kaz-yos/54ae2a180c7c82a79a6d to your computer and use it in GitHub Desktop.
;;; Twelve boxes question
;; https://global-math.com/pr/quiz/6
;; Twelve boxes with numbers exist.
;; All neighboring 4 sum to 50.
;; What goes into the 6th box?
;; |15| |10| | |? | | | | | |20|
;;; Define condition checkers
;; sum checker skeleton
(defn add-up-to-sum? [sum boxes]
(= sum (apply + boxes)))
;; sum = 50 checker
(def fifty? (partial add-up-to-sum? 50))
(clojure.test/is (not (fifty? [1 2 3 4])))
(clojure.test/is (fifty? [1 2 3 44]))
;; sum = 150 checker
(def one-fifty? (partial add-up-to-sum? 150))
(clojure.test/is (not (one-fifty? [1 2 3 4 100])))
(clojure.test/is (one-fifty? [1 2 3 44 100]))
;; sum of all neighboring four = 50 checker
(defn all-fifty? [boxes]
(if (> 4 (count boxes))
true
;; if there are more than four elements, check the first four
(if (fifty? (take 4 boxes))
(recur (rest boxes))
false)))
;; Checker for the last element being 20 (only this one is essential)
(defn last-20? [boxes]
(= 20 (last boxes)))
(clojure.test/is (not (last-20? [1 2 3])))
(clojure.test/is (last-20? [1 2 20]))
;;; Actual solvers
;; Function to create a seed (first four boxes given x for the second box)
(defn first-four-with-x-in-second [x]
[15 x 10 (- 50 (+ 15 x 10))])
(clojure.test/is (fifty? (first-four-with-x-in-second 10)))
;; Function to build on the sequence on the top the seed
(defn all-boxes-with-x-in-second [x]
(let [seed (first-four-with-x-in-second x)]
;;
(loop [acc seed]
(if (= 12 (count acc))
;; Stop at 12 elements
acc
;; Otherwise create the next element and recurse
(recur (conj acc (- 50 (apply + (take 3 (reverse acc))))))))))
(clojure.test/is (all-fifty? (all-boxes-with-x-in-second 10)))
(clojure.test/is (one-fifty? (all-boxes-with-x-in-second 10)))
;; Search for the answer within the search-range
(def search-range (range -100 100))
(def ans (for [x search-range
:let [candidate (all-boxes-with-x-in-second x)]
:when (last-20? candidate)]
candidate))
(print ans)
;; => ([15 5 10 20 15 5 10 20 15 5 10 20])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment