Created
September 23, 2011 22:24
-
-
Save nick-desteffen/1238600 to your computer and use it in GitHub Desktop.
Parans Test
This file contains 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
###### | |
###### Write a function that accepts a string of parenthesis, return true if it is a valid string, false if not. | |
###### Strings are valid if all parens close, ie: () or (()) or (()()()) are valid, ()), ((), )( etc. would be invalid. | |
###### An empty string is also valid. | |
###### | |
require 'test/unit' | |
def valid_parans(string) | |
return false if string[0] == ")" | |
return true if string.strip == "" | |
counter = 0 | |
string.each_char do |char| | |
if char == "(" | |
counter += 1 | |
elsif char == ")" | |
counter -= 1 | |
end | |
end | |
return true if counter == 0 | |
return false | |
end | |
class TestParansFunction < Test::Unit::TestCase | |
def test_all | |
assert valid_parans("()") | |
assert valid_parans("(())") | |
assert !valid_parans("()(") | |
assert !valid_parans("()(()") | |
assert !valid_parans("()((") | |
assert !valid_parans("())") | |
assert valid_parans("(()()())") | |
assert !valid_parans(")(") | |
assert valid_parans("") | |
assert !valid_parans("((()") | |
assert !valid_parans(")))(") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment