Skip to content

Instantly share code, notes, and snippets.

@radar
Last active August 15, 2018 01:02
Show Gist options
  • Save radar/81ac67ed2d30fed88917f4ff3ea9b0c2 to your computer and use it in GitHub Desktop.
Save radar/81ac67ed2d30fed88917f4ff3ea9b0c2 to your computer and use it in GitHub Desktop.
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