Skip to content

Instantly share code, notes, and snippets.

@swanandp
Last active August 29, 2015 14:07
Show Gist options
  • Save swanandp/56134978661decf787bb to your computer and use it in GitHub Desktop.
Save swanandp/56134978661decf787bb to your computer and use it in GitHub Desktop.
4Clojure 112 Sequs Horribilis
(ns fourclojure.sequs-112)
;; https://www.4clojure.com/problem/112
(declare sequs reducer)
(defn flatsum [v] (apply + (flatten v)))
(defn present? [_ el] (seq el))
(defn conj-if [f coll el]
(if (f coll el)
(conj coll el)
coll))
(defn reducer [[limit coll] el]
(if (vector? el)
(if (<= (flatsum coll) limit)
[limit (conj-if present? coll (sequs (- limit (flatsum coll)) el []))]
(reduced [limit coll]))
(if (<= (+ (flatsum coll) el) limit)
[limit (conj coll el)]
(reduced [limit coll]))))
(defn sequs
([limit coll] (sequs limit coll []))
([limit coll init]
(last (reduce reducer [limit init] coll))))
;; scratch / quick test
; (sequs 1 [[[[[1]]]]])
; (sequs 10 [1 2 3 [3 [4 [5 [6 [7 8]] 9]] 10] 11])
; (sequs 10 [1 2 3 [1 [2] [3 4] [4]] 4 5])
; (sequs 20 [4 [5 [6 [7 [8 [9 [10]]]]]]])
; (sequs 2 [1 2 3])
; (sequs 20 [1 2 [3 [4 [5 [6 [7 8]] 9]] 10] 11])
; (sequs 10 [1 2 3 4 5 6])
; (sequs -10 [1 2 3 [1 [2 [3]]] 4 5 6])
; (sequs 9 (range))
(ns fourclojure.sequs-112-test
(:require [clojure.test :refer :all]
[fourclojure.sequs-112 :refer :all]))
(deftest sequs-1
(testing "Testcase 1"
(is (= (sequs 10 [1 2 [3 [4 5] 6] 7])
'(1 2 (3 (4)))))))
(deftest sequs-2
(testing "Testcase 2"
(is (= (sequs 30 [1 2 [3 [4 [5 [6 [7 8]] 9]] 10] 11])
'(1 2 (3 (4 (5 (6 (7))))))))))
(deftest sequs-3
(testing "Testcase 3"
(is (= (sequs 9 (range))
'(0 1 2 3)))))
(deftest sequs-4
(testing "Testcase 4"
(is (= (sequs 1 [[[[[1]]]]])
'(((((1)))))))))
(deftest sequs-5
(testing "Testcase 5"
(is (= (sequs 0 [1 2 [3 [4 5] 6] 7])
'()))))
(deftest sequs-6
(testing "Testcase 6"
(is (= (sequs 0 [0 0 [0 [0]]])
'(0 0 (0 (0)))))))
(deftest sequs-7
(testing "Testcase 7"
(is (= (sequs 1 [-10 [1 [2 3 [4 5 [6 7 [8]]]]]])
'(-10 (1 (2 3 (4))))))))
@swanandp
Copy link
Author

Took me almost two hours to fine tune it. I need to get back to algorithmic problem solving.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment