(wat-aro)

生きてます

Rubyで言語処理100本ノック 00-04

www.cl.ecei.tohoku.ac.jp

Rubyの練習のために始めました.
4章からは難しそうなので3章まで頑張りたい.でも飽きたらやめるかも.
コードを書く基礎が足りない気がするのでもっと書かないと.
始めるにあって,とりあえずRuby 2.2.3のStringクラスは一通り目を通してきました.
全体的に末尾再帰でなんとかしようとしてます.
Rubyは末尾再帰の最適化がないって聞いたんですがどうなんですかね? Rubyっぽい書き方がわからないので,Rubocop先生に出来るだけ怒られないように書いてます.

00

# 00 文字列を受け取り,末尾から順に表示する
class String
  def my_reverse
    size = length
    result = ''
    while size > 0
      size -= 1
      result << self[size]
    end
    result
  end

  # Like tail call
  def iter_reverse
    iter('', length)
  end

  private

  def iter(str, str_len)
    if str_len > 0
      iter(str + self[str_len - 1], str_len - 1)
    else
      str
    end
  end
end

'reverse'.my_reverse                # => "esrever"
'a'.my_reverse                      # => "a"
''.my_reverse                       # => ""

'reverse'.iter_reverse          # => "esrever"
'a'.iter_reverse                # => "a"
''.iter_reverse                 # => ""

01

# 01 文字列の奇数番目だけ取り出した新しい文字列を返す
class String
  def str_odd
    iter(0, '')
  end

  private

  def iter(index, str)
    if index < length
      if index.even?
        iter(index + 1, str + self[index])
      else
        iter(index + 1, str)
      end
    else
      str
    end
  end
end

'hello'.str_odd                # => "hlo"
'abcde'.str_odd                # => "ace"
'パタトクカシーー'.str_odd     # => "パトカー"

02

# 02 2つの文字列を受け取り,先頭から交互に混ぜた文字列をつくる
def comb_str(str1, str2)
  iter(str1, str2, '')
end

def iter(str1, str2, result)
  if str1.empty?
    result + str2
  elsif str2.empty?
    result + str1
  else
    iter(str1[1..-1], str2[1..-1], result + str1[0] + str2[0])
  end
end

comb_str('パトカー', 'タクシー') # => "パタトクカシーー"

03

# 03 文字列から数字のリストをつくる
class String
  def pi
    split.map(&:length)
  end
end

"Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.".pi
 # => [3, 1, 4, 1, 6, 9, 2, 7, 5, 3, 5, 8, 9, 7, 10]

04

# 04 文字列を受け取り,単語に分解し,1, 5, 6, 7, 8, 9, 15, 16, 19番目の単語は先頭の1文字
# それ以外の単語は先頭に2文字を取り出し,取り出した文字列から単語の位置(先頭から何番目の単語か)への連想配列を返す
class String
  def element
    recur(split, 1, [])
  end

  private

  def helper(str, i)
    case i
    when 1, 5, 6, 7, 8, 9, 15, 16, 19
      [str[0], i]
    else
      [str[0, 2], i]
    end
  end

  def recur(arr, index, result)
    if arr.empty?
      result
    else
      recur(arr.drop(1), index + 1, result.push(helper(arr[0], index)))
    end
  end
end

"Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can.".element
# => [["H", 1], ["He", 2], ["Li", 3], ["Be", 4], ["B", 5], ["C", 6], ["N", 7], ["O", 8], ["F", 9], ["Ne", 10], ["Na", 11], ["Mi", 12], ["Al", 13], ["Si", 14], ["P", 15], ["S", 16], ["Cl", 17], ["Ar", 18], ["K", 19], ["Ca", 20]]

Stringクラスを一読するのに時間がかかったので今日はこれだけ.