Last active
August 29, 2015 14:13
-
-
Save compwron/d883710cf84bbd213eed to your computer and use it in GitHub Desktop.
matching parens
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
# Task: write a function to determine if a string is | |
# 'balanced'. Balanced means that opening and closing | |
# brackets match each other in the proper order. Other | |
# characters are possible and should be handled. The | |
# possible characters for balancing are {}, (), and [] | |
# Example Input: | |
# '{}' -> True | |
# '{[]}' -> True | |
# '{5}' -> True | |
# '{[}' -> False | |
# '[A]{}d()' -> True | |
# 'a' -> True | |
# 'a}' -> False | |
# '([)]' -> False | |
# '{' -> False | |
# ((({{{{{[[[[(sdfklxlcdfja)]]]]}}}}}))) | |
MATCHES = {'{' => '}', '[' => ']', '(' => ')'} | |
def balanced?(input) | |
a = input.chars.map.with_index.inject([]) { |current_open, c| | |
c_val, c_index = c | |
if MATCHES.keys.include?(c_val) | |
current_open << c_val | |
elsif MATCHES.values.include?(c_val) | |
should_match = current_open.pop | |
if MATCHES[should_match] == c_val | |
current_open | |
else | |
msg = "FAILED at index #{c_index} with character #{c_val}" | |
p msg | |
[msg] | |
end | |
end | |
} | |
a.empty? | |
end | |
def should actual, expected | |
if actual != expected | |
puts "No! Got #{actual} instead of #{expected}" | |
else | |
puts "good" | |
end | |
end | |
def bah | |
(0..1000000).map {|i| Random.rand(2) == 0 ? MATCHES.keys.sample : MATCHES.values.sample}.join | |
end | |
should(balanced?(bah), true) | |
should(balanced?('{}'), true) | |
should(balanced?('{[]}'), true) | |
should(balanced?('([)]'), false) | |
should(balanced?('[]]'), false) | |
should(balanced?('[[]'), false) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment