2009-01-15練習:たのしいRuby
P.203 (3) balanced? メソッドを定義する
(, ), {, } という 4 つの文字を要素とした配列がある。この配列に対して、
カッコが正しく対応しているかを調べるメソッド balanced? を定義しましょう。
「カッコが正しく対応している」とは、以下のような状態のことです。
・( と ) の数が同じ
・{ と } の数が同じ
・「( )」の対応と「{ }」の対応が交差することはない
書いたもの 1
正規表現を使ってみた。
def balanced?(ary) str = ary.join while (/\(\)/ =~ str) || (/\{\}/ =~ str) result = str.gsub!(/\(\)|\{\}/, "") end if result == "" return true else return false end end p balanced?(%w! ( !) p balanced?(%w! { } !) p balanced?(%w! ( { { } ( ) } ( ) ) !) p balanced?(%w! ( { { ( } ( ) } ( ) ) !)
実行結果
false true true false
書いたもの 2
今度は、スタックを使って。
def balanced2?(ary) stack = [] ary.each {|elem| case elem when "(" stack << elem when "{" stack << elem when ")" if stack.last != "(" return false else stack.pop end when "}" if stack.last != "{" return false else stack.pop end else return false end } if stack.size == 0 return true else return false end end p balanced2?(%w! ( !) p balanced2?(%w! { } !) p balanced2?(%w! ( { { } ( ) } ( ) ) !) p balanced2?(%w! ( { { ( } ( ) } ( ) ) !)
実行結果
false true true false
引数 nums を書き換えることは意図したことではないです。手元のものは以下のように修正しました。
def square3(nums)
copy = nums.dup
copy.each_index{|index|
copy[index] **= 2
}
end
蛇足ですが、square3 は、最初はこんなふうに書いていました。
def square3(nums)
indexes = (0...nums.size).to_a
result = []
while index = indexes.shift
result << nums[index] ** 2
end
return result
end
これなら、nums を書き換えてはいなかったです。
インデックスの配列をわざわざつくらなくても、Ruby にはインデックスに対して何かをするメソッドがあるのではと思っていたところ、Array#each_index を見つけ、これを使いました。
マニュアルを読んで使い方を理解したつもりだったのですが、まだまだですね。