Last active
September 20, 2017 14:18
-
-
Save kolja/3f581b655a52ad4d6ae1996ca85d42ec to your computer and use it in GitHub Desktop.
find out if a string with parens is balanced
This file contains 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
#!/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")) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I like the approach using regex a lot! It resembles our initial idea where different 'stacks' of brackets are checked. 👍