Created
December 7, 2014 00:40
-
-
Save Michael0x2a/74c4b54ffd6b0518a705 to your computer and use it in GitHub Desktop.
Clojure: is string balanced?
This file contains hidden or 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
; Given a N different open and close braces in a string ""( { [ } ] )"". | |
; Write a program to check to see if the braces in the string are balanced. | |
(ns braces | |
(:require [clojure.string :as str])) | |
(def braces #{\( \) \[ \] \{ \}}) | |
(def pairs { \) \(, | |
\] \[, | |
\} \{ }) | |
(defn remove-non-braces | |
"Takes a string and removes any characters that is not a brace." | |
[raw-string] | |
(filter #(braces %) raw-string)) | |
(defn is-balanced? | |
"Returns true if all the braces in the string are balanced; returns false otherwise." | |
([raw-string] (is-balanced? (remove-non-braces raw-string) [])) | |
([string stack] | |
(let [[first-char & other] string] | |
(cond | |
; if we finish, but the stack is non-empty, we still have opening braces left. | |
(empty? string) (empty? stack) | |
; if we encounter a closing brace, check it against the top of the stack. | |
(pairs first-char) (if (= (pairs first-char) (peek stack)) | |
(is-balanced? other (pop stack)) | |
false) | |
; if we encounter an opening brace, add it to the stack. | |
:else (is-balanced? other (conj stack first-char)))))) | |
(defn test-strings | |
"Tests the given strings and prints the results." | |
[& strings] | |
(let [format-str (fn [s] (str (is-balanced? s) " : " s))] | |
(println (str/join "\n" (map format-str strings))))) | |
(defn main | |
"The main entry point of the program." | |
[] | |
(println "SHOULD PASS") | |
(test-strings | |
"Hello { ( world ) } [] end" | |
"" | |
"{[] () {[{{ }}]} ([{}])}") | |
(println "") | |
(println "SHOULD FAIL") | |
(test-strings | |
"Hello { world" | |
"{{" | |
"])" | |
"}}{{" | |
"{[))")) | |
(main) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment