Skip to content

Instantly share code, notes, and snippets.

@kolja
Last active September 20, 2017 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kolja/3f581b655a52ad4d6ae1996ca85d42ec to your computer and use it in GitHub Desktop.
Save kolja/3f581b655a52ad4d6ae1996ca85d42ec to your computer and use it in GitHub Desktop.
find out if a string with parens is balanced
#!/usr/local/bin/lumo
(ns balanced.core
(:require [lumo.core :refer [*command-line-args*]]
[clojure.string :refer [join]]))
(defn is-pair? [ch1 ch2]
(let [pairs {"(" ")"
"[" "]"
"{" "}"}]
(= (get pairs ch1) ch2)))
(defn reduce-balanced [parens]
(reduce (fn [stack ch]
(if ((set "{[(") ch)
(str stack ch)
(if (is-pair? (last stack) ch)
(join (butlast stack))
"x"))) "" parens))
;----------- another implementation:
(defn remove-balanced [parens]
(let [replaced (clojure.string/replace parens #"\(\)|\[\]|{}" "")]
(if (= parens replaced)
replaced
(recur replaced))))
;----------- then call either one:
(defn balanced? [parens]
(empty? (reduce-balanced parens)))
(def parens (first *command-line-args*))
(println (if (balanced? parens)
"balanced"
"not balanced"))
@s0k0
Copy link

s0k0 commented Sep 20, 2017

I like the approach using regex a lot! It resembles our initial idea where different 'stacks' of brackets are checked. 👍

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