Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Well formed strings solution #33

Open
wants to merge 6 commits into
base: challenge-well-formed-strings
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions string_validator.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
class StringValidator
attr_reader :token_stack

def initialize
@token_stack = []
end

def pairings
{
"(" => ")",
"[" => "]",
"{" => "}",
}
end

def matched_pair?(t1, t2)
pairings[t1] == t2
end

def left?(token)
pairings.keys.include?(token)
end

def right?(token)
pairings.values.include?(token)
end

def validate(target)
answer = pairs_match?(target) && token_stack.empty?
token_stack.clear
return answer
end

def pairs_match?(target)
target.chars.all? do |token|
if left?(token)
token_stack.push(token)
elsif right?(token)
left = token_stack.pop
matched_pair?(left, token)
end
end
end
end
64 changes: 64 additions & 0 deletions string_validator_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
require 'minitest/autorun'
require './string_validator'

class StringValidatorTest < Minitest::Test
def test_it_exists
assert StringValidator
end

def test_an_empty_string_is_valid
sv = StringValidator.new
assert sv.validate("")
end

def test_single_parens_are_valid
sv = StringValidator.new
assert sv.validate("()")
end

def test_single_inverted_parens_are_not_valid
sv = StringValidator.new
refute sv.validate(")(")
end

def test_single_square_brackets_are_valid
sv = StringValidator.new
assert sv.validate("[]")
end

def test_single_curly_brackets_are_valid
sv = StringValidator.new
assert sv.validate("{}")
end

def test_two_pairs_of_matched_brackets_are_valid
sv = StringValidator.new
assert sv.validate("{}()")
end

def test_mismatched_second_brackets_are_invalid
sv = StringValidator.new
refute sv.validate("{})(")
end

def test_complex_nesting_is_valid
sv = StringValidator.new
assert sv.validate("([{}[]])")
end

def test_complex_nesting_with_some_trash_is_invalid
sv = StringValidator.new
refute sv.validate("([{}[]])]")
end

def test_complex_nesting_with_some_other_trash_is_invalid
sv = StringValidator.new
refute sv.validate("([{}[]])[")
end

def test_validating_a_second_input_works_correctly
sv = StringValidator.new
refute sv.validate("([{}[]])[")
assert sv.validate("()")
end
end