Balanced brackets: Difference between revisions
Content added Content deleted
Line 1,577: | Line 1,577: | ||
(recur coll (pop stack)))) |
(recur coll (pop stack)))) |
||
(zero? (count stack)))))</lang> |
(zero? (count stack)))))</lang> |
||
There are other ways to express the <code>balanced?</code> function. |
|||
* We can use <code>reduce</code> to consume the sequence: |
|||
:<lang Clojure>(defn balanced? [s] |
|||
(empty? |
|||
(reduce |
|||
(fn [stack first] |
|||
(case first |
|||
\[ (conj stack \[) |
|||
\] (if (seq stack) |
|||
(pop stack) |
|||
(reduced [:UNDERFLOW])))) |
|||
'() |
|||
s)))</lang> |
|||
* Only <code>[</code>s are put on the stack. We can just count the unmatched ones. |
|||
:<lang Clojure>(defn balanced? [s] |
|||
(let [opens-closes (->> s |
|||
(map {\[ 1, \] -1}) |
|||
(reductions + 0))] |
|||
(and (not-any? neg? opens-closes) (zero? (last opens-closes))))) </lang> |
|||
Output: |
Output: |
||
Line 1,582: | Line 1,604: | ||
<pre>user> (->> (range 10) |
<pre>user> (->> (range 10) |
||
(map gen-brackets ,) |
(map gen-brackets ,) |
||
(map (juxt identity balanced?) , |
(map (juxt identity balanced?) ,) |
||
vec) |
|||
[["" true] |
[["" true] |
||
["[]" true] |
["[]" true] |