Skip to content

Instantly share code, notes, and snippets.

@kolharsam
Created April 13, 2020 16:08
Show Gist options
  • Save kolharsam/4ec63205ed103eb8c7de1ed1172de9e3 to your computer and use it in GitHub Desktop.
Save kolharsam/4ec63205ed103eb8c7de1ed1172de9e3 to your computer and use it in GitHub Desktop.
Cassidy's Interview Question - 13/04
(require '[clojure.math.combinatorics :as combo]
'[clojure.string :as str])
(defn validParenthesis?
"Returns true if a sequence of parentheses are balanced"
[coll]
(loop [parens_list (apply list coll)
stack []]
(if (empty? parens_list)
(empty? stack)
(if (= (peek parens_list) "(")
(recur (rest parens_list) (conj stack (peek parens_list)))
(if (empty? stack)
(recur (rest parens_list) stack)
(recur (rest parens_list) (rest stack)))))))
(defn generateParens
"Returns a list of valid combinations of parentheses that
can be formed with n parenthesis"
[n]
(let [openParens (repeat n "(")
closedParens (repeat n ")")
allParens (concat openParens closedParens)
parensPerms (combo/permutations allParens)]
(map #(str/join #"" %) (filter validParenthesis? parensPerms))))
(generateParens 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment