Skip to content

Instantly share code, notes, and snippets.

@DNA

DNA/code-test.rb

Last active Jul 22, 2020
Embed
What would you like to do?
Code test
#! /usr/bin/env ruby
# Write a function that returns true if the brackets in a given string are balanced.
# Balanced means that every parenthesis/bracket or brace that is opened must be closed
# And it must be closed in the right order (Always close the last symbol you opened)
# The function must handle parens (), square brackets [], and curly braces {}.
# "(a[0]+b[2c[6]]) {24 + 53}" should return true
# "f(e(d))" should return true
# "[()]{}([])" should return true
# "((b)" should return false
# "(c]" should return false
# "{(a[])" should return false
# "([)]" should return false
# ")(" should return false
# "" should return false
class Char
def initialize(char)
@char = char
end
def bracket?
%w[{ } [ ] ( )].include? @char
end
def open?
%W[{ \[ (].include? @char
end
def inverse
{
'(' => ')',
')' => '(',
'{' => '}',
'}' => '{',
'[' => ']',
']' => '['
}[@char]
end
def to_s
@char
end
end
def parse_brackets(input)
return false if input.empty?
stack = []
input.chars.each do |char|
char = Char.new(char)
next unless char.bracket?
if char.open?
stack << char
elsif stack.last.to_s == char.inverse
stack.pop
else
return false
end
end
stack.empty?
end
pp parse_brackets('(a[0]+b[2c[6]]) {24 + 53}')
pp parse_brackets('f(e(d))')
pp parse_brackets('[()]{}([])')
pp !parse_brackets('((b)')
pp !parse_brackets('(c]')
pp !parse_brackets('{(a[])')
pp !parse_brackets('([)]')
pp !parse_brackets(')(')
pp !parse_brackets('')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment