Last active
July 6, 2017 16:34
-
-
Save temochka/ee0d1b5fcd085f4097ba8d858d96022c to your computer and use it in GitHub Desktop.
4clojure #112
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
(defn eval-expr [max-sum [sum sequence stack] lexeme] | |
(case lexeme | |
"[" [sum (conj sequence "(") (cons ")" stack)] | |
"]" [sum (conj sequence ")") (next stack)] | |
(let [x (Integer/parseInt lexeme)] | |
(if (<= (+ sum x) max-sum) | |
[(+ sum x) (conj sequence lexeme) stack] | |
(reduced [sum (concat sequence stack) nil]))))) | |
(defn horribilis [max-sum program] | |
(->> program | |
prn-str | |
(re-seq #"(?:\-?\d+)|(?:[\[\]])") | |
(reduce #(eval-expr max-sum %1 %2) [0 [] nil]) | |
((fn [[_ x _]] x)) | |
(apply println-str) | |
read-string)) | |
(= (horribilis 10 [1 2 [3 [4 5] 6] 7]) | |
'(1 2 (3 (4)))) | |
(= (horribilis 30 [1 2 [3 [4 [5 [6 [7 8]] 9]] 10] 11]) | |
'(1 2 (3 (4 (5 (6 (7))))))) | |
; Can’t run infinite programs :-( | |
#_(= (horribilis 9 (range)) | |
'(0 1 2 3)) | |
(= (horribilis 1 [[[[[1]]]]]) | |
'(((((1)))))) | |
(= (horribilis 0 [1 2 [3 [4 5] 6] 7]) | |
'()) | |
(= (horribilis 0 [0 0 [0 [0]]]) | |
'(0 0 (0 (0)))) | |
(= (horribilis 1 [-10 [1 [2 3 [4 5 [6 7 [8]]]]]]) | |
'(-10 (1 (2 3 (4))))) | |
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
(defn horribilis | |
([n xs] | |
(horribilis n xs (fn [_ xs] (or xs (list))))) | |
([n [x & xs] f] | |
(cond | |
(sequential? x) | |
(recur n x #(let [[sum x] (horribilis %1 xs vector)] (f sum (cons %2 x)))) | |
(and n x (<= x n)) | |
(recur (- n x) xs #(f %1 (cons x %2))) | |
:else | |
(f (when-not x n) nil)))) | |
(= (horribilis 10 [1 2 [3 [4 5] 6] 7]) | |
'(1 2 (3 (4)))) | |
(= (horribilis 30 [1 2 [3 [4 [5 [6 [7 8]] 9]] 10] 11]) | |
'(1 2 (3 (4 (5 (6 (7))))))) | |
(= (horribilis 9 (range)) | |
'(0 1 2 3)) | |
(= (horribilis 1 [[[[[1]]]]]) | |
'(((((1)))))) | |
(= (horribilis 0 [1 2 [3 [4 5] 6] 7]) | |
'()) | |
(= (horribilis 0 [0 0 [0 [0]]]) | |
'(0 0 (0 (0)))) | |
(= (horribilis 1 [-10 [1 [2 3 [4 5 [6 7 [8]]]]]]) | |
'(-10 (1 (2 3 (4))))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment