Skip to content

Instantly share code, notes, and snippets.

@kachick
Created April 30, 2012 04:51
Show Gist options
  • Select an option

  • Save kachick/2555607 to your computer and use it in GitHub Desktop.

Select an option

Save kachick/2555607 to your computer and use it in GitHub Desktop.
Rubyでアルゴリズムやらデータ構造やらのお勉強(Stack - Check Parentheses)
# -*- coding: utf-8 -*-
# Cで書かれたアルゴリズムやらデータ構造なりを、自分なりにRubyで表現してみるお勉強PJ。
# 参考書籍(プログラミングの宝箱 アルゴリズムとデータ構造)
# Ruby1.9.3で動作確認済み
# スタックの項より、標準入力から受け付けた括弧の対応を調べるスクリプト。
# 理屈は聞いたことあったけど、書くの初めてだった。
# 使い方の方が主に感じたので、Stackの実装側は委譲で済ませた。
$VERBOSE = true
class Stack
class UnderFlow < RuntimeError; end
def initialize
@list = []
end
def pop
if empty?
raise UnderFlow
else
@list.pop
end
end
def push(value)
@list.push value
end
def last
@list.last
end
def empty?
@list.empty?
end
end
MatchedParentheses = Struct.new :line_num, :char_pos, :type
PARENTHESES_PAIRS = {
:'(' => :')',
:'{' => :'}',
:'[' => :']'
}
stack = Stack.new
STDIN.each.with_index do |line, line_num|
line.each_char.with_index do |char, char_pos|
case char
when '(', '{', '['
stack.push MatchedParentheses.new(line_num, char_pos, char.to_sym)
when ')', '}', ']'
if stack.empty?
raise "#{line_num}行目の#{char_pos}文字目に現れた閉じ括弧#{char}へ対応するべき開き括弧がありません"
else
last_opened = stack.last
if last_opened.type == PARENTHESES_PAIRS.key(char.to_sym)
stack.pop
else
raise "#{last_opened.line_num}行目の#{last_opened.char_pos}文字目に現れた開き括弧#{last_opened.type}と、#{line_num}行目の#{char_pos}文字目に現れた対応するべき閉じ括弧#{char}の種類が異なります"
end
end
end
end
end
if stack.empty?
puts '括弧の対応が正しく取れています'
else
raise '開き括弧の数が多すぎます'
end
@kachick
Copy link
Copy Markdown
Author

kachick commented Apr 30, 2012

Stackはフツーに使いたい局面出てきそうなので、こういった形にまとめてみた。
https://github.com/kachick/abstractstack

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment