Advertisement
Guest User

balancing symbols

a guest
Dec 18th, 2011
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.08 KB | None | 0 0
  1. require 'minitest/autorun'
  2.  
  3. # detect if a string symbols are balanced
  4. # '[()]' => true
  5. # '({)' => false
  6. # '(([[]]))'
  7.  
  8. class Algo
  9.   TABLE = {
  10.     '(' => ')',
  11.     '[' => ']',
  12.     '{' => '}'
  13.   }
  14.  
  15.   OPENINGS = TABLE.keys
  16.  
  17.   def is_balanced str
  18.     stack = []
  19.     str.each_char do |char|
  20.       if OPENINGS.include?(char)
  21.         stack << char
  22.       else
  23.         open_char = stack.pop
  24.         if !open_char or TABLE[open_char] != char
  25.           return false
  26.         end
  27.       end
  28.     end
  29.  
  30.     stack.empty? ? true : false
  31.   end
  32. end
  33.  
  34. describe Algo do
  35.   before do
  36.     @algo = Algo.new
  37.   end
  38.  
  39.   describe "balanced symbols" do
  40.     it "return true if symbols are balanced" do
  41.       assert_equal true, @algo.is_balanced( '()' )
  42.       assert_equal true, @algo.is_balanced( '[()]' )
  43.       assert_equal true, @algo.is_balanced( '[[[({})]]]' )
  44.       assert_equal true, @algo.is_balanced( '' )
  45.     end
  46.  
  47.     it "return false if symbols are not balanced" do
  48.       assert_equal false, @algo.is_balanced( '{()' )
  49.       assert_equal false, @algo.is_balanced( '{' )
  50.     end
  51.   end
  52. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement