Upgrade to Pro — share decks privately, control downloads, hide ads and more …

問題1. 解答例

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
Avatar for mizti mizti
November 18, 2012
500

問題1. 解答例

Avatar for mizti

mizti

November 18, 2012
Tweet

Transcript

  1. ソースコードとか class PolishProcessor attr_accessor :arr def initialize(s) #与えられた文字列を解析して配列に入れる @arr =

    arraynize(s) end def evaluate @stack = [] # arrが空になるまで、末尾から一つづつ数字を取り出す while((popped = @arr.pop) != nil) do if Integer === popped then # 取り出されたのが数字だったら、スタックに積む @stack.push popped end if popped == "+" || popped == "*" || popped == "-" then # 取り出されたのが演算子だったら、スタックにつまれた数字2つを取り出し て計算してまたスタックに積む num1 = @stack.pop num2 = @stack.pop @stack.push calc(popped, num1, num2) end end @stack[0] end # 与えられた演算子と数字2つから計算を行う def calc(operator, num1, num2) if operator == "+" then return num1 + num2 elsif operator == "*" then return num1 * num2 elsif operator == "-" then return num1 - num2 else return "Error" end end # 与えられた文字列を分解して配列に入れる def arraynize(s) ret = s.gsub("("," ").gsub(")", " ").split(/¥s* ¥s*/) ret = ret.select{|item| item!=""} ret = ret.collect{|i| if i =~ /¥d+/ then i.to_i else i end} end
  2. 答えの一例: 問題1.ポーの惑星 (* (- 9 20) (+ 7 (- 999

    108)) ) 1. (したごしらえ)読み込んだものから( )を半角スペースで置き換え 2. (したごしらえ) スペースを区切り文字にして配列に入れ、更に空文字””を除去 ["*", "-", 9, 20, "+", 7, "-", 999, 108] * - 9 20 + 7 - 999 108 * - 9 20 + 7 - 999 108 3. 後方から順番に1要素ずつ取り出してスタックに積んで行く ["*", "-", 9, 20, "+", 7, "-"] 108 999 108 999 ウワー ウワー ウワー ウワー
  3. 答えの一例: 問題1.ポーの惑星(2) ["*", "-", 9, 20, "+", 7] 108 999

    4. 演算子が積まれたら、下にある2文字とあわせて計算、結果をスタックに入れる "-" “-” 891 5. 配列が空になるまで繰り返して、スタックに最後に残った数字が答えとなる 891 7 + 898 898 20 9 “-” 898 -11 898 -11 “*” -9878