Skip to content

Instantly share code, notes, and snippets.

@johnnymo87
Last active August 29, 2015 14:01
Show Gist options
  • Save johnnymo87/fb633409cf171c14b98c to your computer and use it in GitHub Desktop.
Save johnnymo87/fb633409cf171c14b98c to your computer and use it in GitHub Desktop.
Exercise 2: Parentheses Balancing
# https://class.coursera.org/progfun-004/assignment/view?assignment_id=4
# Exercise 2: Write a recursive function which verifies the balancing of parentheses in a string
def balance(ary, collected = [])
return collected.length.even? if ary.empty?
char = ary.shift
balance(ary, collected + char.scan(/\(|\)/))
end
require 'minitest/autorun'
require 'minitest/pride'
describe 'matching parens' do
describe 'valid' do
it '' do
balance('(if (zero? x) max (/ 1 x))'.split('')).must_equal true
end
it '' do
balance("I told him (that it's not (yet) done). (But he wasn't listening)".split('')).must_equal true
end
end
describe 'invalid' do
it '' do
balance(':-)'.split('')).must_equal false
end
it '' do
balance('())()'.split('')).must_equal false
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment