-
-
Save radar/81ac67ed2d30fed88917f4ff3ea9b0c2 to your computer and use it in GitHub Desktop.
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
require 'minitest/autorun' | |
require 'pry' | |
PAIRS = { '{' => '}', '[' => ']', '(' => ')' }.freeze | |
def balanced?(string) | |
return false if string.length.odd? | |
chars = string.chars | |
PAIRS.keys | |
.map do |opening| | |
[opening, chars.count { |char| char == opening }] | |
end | |
.reject { |_char, count| count.zero? } | |
.all? do |opening, expected_count| | |
chars.count { |char| char == PAIRS[opening] } == expected_count | |
end | |
end | |
class BalancedTest < MiniTest::Test # :nodoc: | |
def test_balanced | |
assert balanced?('(())') | |
end | |
def test_unbalanced | |
refute balanced?('((()') | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment