Skip to content

Instantly share code, notes, and snippets.

@LauraKirby
Last active August 31, 2017 23:20
Show Gist options
  • Save LauraKirby/b9194233d09aa0404f9534976bb7869d to your computer and use it in GitHub Desktop.
Save LauraKirby/b9194233d09aa0404f9534976bb7869d to your computer and use it in GitHub Desktop.
The Ruby Way, Third Edition
# use a stack to validate parenthesis completion
class Stack
def initialize
@store = []
end
def push(x)
@store.push(x)
end
def pop
@store.pop
end
def peek
@store.last
end
def empty?
@store.empty?
end
end
def paren_matcher(str)
stack = Stack.new
lsym = "{[(<"
rsym = "}])>"
str.each_char do |sym|
if lsym.include? sym
stack.push(sym)
elsif rsym.include?(sym)
# if stack is empty, assign top to something that
# will never be in the symbol string
stack.empty? ? top = "-1" : top = stack.peek
top = stack.peek
if lsym.index(top) != rsym.index(sym)
return false
else
stack.pop
end
# ignore non-grouped characters...
end
end
puts "finish and return: #{stack.empty?}"
# Ensure stack is empty
return stack.empty?
end
require_relative './parenthesis_matcher.rb'
describe "#paren_matcher" do
it "returns true with basic parentheses" do
str = "(a)"
expect(paren_matcher(str)).to eq true
end
it "returns false when final closing paren is missing" do
str = "(a"
expect(paren_matcher(str)).to eq false
end
it "returns false when first opening paren is missing" do
str = "a)"
expect(paren_matcher(str)).to eq false
end
it "returns true when multiple embedded parens are valid" do
str = "[[(a-(b-c))], [[x,y]]]"
expect(paren_matcher(str)).to eq true
end
it "returns true when multiple embedded parens are valid and one set is not" do
str = "[[(a-(b-c))], [[x,y]]"
expect(paren_matcher(str)).to eq false
end
it "returns true when multiple embedded parens are valid and one set is not" do
str = "(((a+b))*((c-d)-(e*f))"
expect(paren_matcher(str)).to eq false
end
end
@LauraKirby
Copy link
Author

LauraKirby commented Aug 31, 2017

Added: Line 35

Resolve issue where algorithm fails if the argument's first symbol is included within rsym. Since the stack is empty, stack.peek returns nil. Thus when top stores the value nil. When we call index and pass in nil, an error occurs.
Solution: If the stack is empty, then store any string value in top that you would not ever see in lsym. In this example, I used -1.

Rspec error:
Failure/Error: if lsym.index(top) != rsym.index(sym)
TypeError: type mismatch: NilClass given

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment