Skip to content

Instantly share code, notes, and snippets.

Created October 27, 2011 23:38
Show Gist options
  • Save anonymous/1321208 to your computer and use it in GitHub Desktop.
Save anonymous/1321208 to your computer and use it in GitHub Desktop.
;; fronx's solution to Love Triangle
;; https://4clojure.com/problem/127
(fn [field]
(let [
bit-max (fn [number]
(loop [n 1 i 0]
(if (>= number n)
(recur (* 2 n) (inc i))
i)))
max-bit-max (fn [numbers] (bit-max (apply max numbers)))
flip-down #(reverse %)
flip-right (fn [triangle]
(map #(bit-shift-left % (- (max-bit-max triangle) (bit-max %)))
triangle))
tri-at? (fn [triangle x y field]
(if (>= (count field) (+ y (count triangle)))
(let [triangle (vec (map #(bit-shift-left % x) triangle))
matchfield (subvec field y)]
(every? true?
(map (fn [tri x]
(= tri (bit-and tri x)))
triangle
matchfield)))))
bit-count (fn [numbers]
(let [size (max-bit-max numbers)]
(reduce +
(flatten
(map #(for [x (range 0 size) :when (bit-test % x)] 1)
(vec numbers))))))
wedge (fn wedge
([] (wedge [1]))
([prev] (lazy-cat prev
(wedge [(+ 1 (bit-shift-left (peek prev) 1))])
)))
fir (fn [size]
(map #(bit-or % (bit-shift-left %2 size))
(flip-right (take size (wedge)))
(concat [0] (take (dec size) (wedge)))))
play-button (fn [size]
(concat
(take size (wedge))
(flip-down (take (dec size) (wedge)))))
triangles (fn [size]
(let [a (take size (wedge))
b (flip-right a)
c (flip-down a)
d (flip-down b)
e (fir size)
f (flip-down e)
g (play-button size)
h (flip-right g)]
(set [a b c d e f g h])))
x-max (max-bit-max field)]
(loop [size 2 biggest 0]
(let [found (for [tri (triangles size)
x (range 0 x-max)
y (range 0 (inc (- (count field) (count tri))))
:when (tri-at? tri x y field)]
(bit-count tri))]
(if (or (empty? found)
(<= (apply max found) biggest))
(if (> biggest 0) biggest)
(recur (inc size) (apply max found)))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment