Skip to content

Instantly share code, notes, and snippets.

@stockwellb
Last active June 19, 2016 22:03
Show Gist options
  • Save stockwellb/a17a8ccdce6f00bc2dca7db2433a334f to your computer and use it in GitHub Desktop.
Save stockwellb/a17a8ccdce6f00bc2dca7db2433a334f to your computer and use it in GitHub Desktop.
Bracket push solution
defmodule BracketPush do
def check_brackets(""), do: true
def check_brackets(s) do
do_check_brackets([],String.codepoints(s))
end
defp do_check_brackets(stack,[]) do
length(stack) === 0
end
defp do_check_brackets(stack,["{"|rest]) do
do_check_brackets(["{"|stack],rest)
end
defp do_check_brackets(stack,["["|rest]) do
do_check_brackets(["["|stack],rest)
end
defp do_check_brackets(stack,["("|rest]) do
do_check_brackets(["("|stack],rest)
end
defp do_check_brackets(stack,["}"|rest]) do
case peek(stack) do
{:ok, "{"} ->
[h|t] = stack
do_check_brackets(t,rest)
{:ok, _} -> false
{:error, _} -> false
end
end
defp do_check_brackets(stack,["]"|rest]) do
case peek(stack) do
{:ok, "["} ->
[h|t] = stack
do_check_brackets(t,rest)
{:ok, _} -> false
{:error, _} -> false
end
end
defp do_check_brackets(stack,[")"|rest]) do
case peek(stack) do
{:ok, "("} ->
[h|t] = stack
do_check_brackets(t,rest)
{:ok, _} -> false
{:error, _} -> false
end
end
defp do_check_brackets(stack,[_|rest]) do
do_check_brackets(stack,rest)
end
defp peek([]) do
{:error, nil}
end
defp peek([h|_]) do
{:ok, h}
end
end
ExUnit.start
defmodule BracketPushTest do
use ExUnit.Case, async: true
test "empty string" do
assert BracketPush.check_brackets("")
end
test "appropriate bracketing in a set of brackets" do
assert BracketPush.check_brackets("{}")
end
test "unclosed brackets" do
refute BracketPush.check_brackets("{{")
end
test "more than one pair of brackets" do
assert BracketPush.check_brackets("{}[]")
end
test "brackets are out of order" do
refute BracketPush.check_brackets("}{")
end
test "nested brackets" do
assert BracketPush.check_brackets("{[()]}")
end
test "unbalanced nested brackets" do
refute BracketPush.check_brackets("{[}]")
end
test "bracket closure with deeper nesting" do
refute BracketPush.check_brackets("{[)][]}")
end
test "bracket closure in a long string of brackets" do
assert BracketPush.check_brackets("{[]([()])}")
end
test "should ignore non-bracket characters" do
assert BracketPush.check_brackets("{hello[]([a()])b}c")
end
test "string with newlines" do
assert BracketPush.check_brackets("[]\n{()}\n[(({}))]\n")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment