LoginSignup
3
1

More than 5 years have passed since last update.

Rubyで言語処理100本ノック 第1章:準備運動 (06 ~ 09)

Last updated at Posted at 2018-06-03

言語処理100本ノックの挑戦記録です。

前回までの挑戦

配列の集合演算に関して、以下の記事を参考にさせていただきました。
ありがとうございます!
rubyのArrayで集合(和集合・積集合・差集合・対称差集合・補集合)

06. 集合

"paraparaparadise"と"paragraph"に含まれる文字bi-gramの集合を,
それぞれ, XとYとして求め,XとYの和集合,積集合,差集合を求めよ.
さらに,'se'というbi-gramがXおよびYに含まれるかどうかを調べよ.

class Array
  def ngram(n)
    self.each_cons(n).map(&:join)
  end
end

word1 = "paraparaparadise"
word2 = "paragraph"

X = word1.chars.ngram(2)
Y = word2.chars.ngram(2)

# 和集合
puts X | Y
# 積集合
puts X & Y
# 差集合
puts X - Y

puts X.include? "se"
puts Y.include? "se"
結果
# X
["pa", "ar", "ra", "ap", "pa", "ar", "ra", "ap", "pa", "ar", "ra", "ad", "di", "is", "se"]
# Y
["pa", "ar", "ra", "ag", "gr", "ra", "ap", "ph"]
# 和集合
["pa", "ar", "ra", "ap", "ad", "di", "is", "se", "ag", "gr", "ph"]
# 積集合
["pa", "ar", "ra", "ap"]
# 差集合
["ad", "di", "is", "se"]

# Xに "se" が含まれるか
true
# Yに "se" が含まれるか
false

07. テンプレートによる文生成

引数x, y, zを受け取り「x時のyはz」という文字列を返す関数を実装せよ.
さらに,x=12, y="気温", z=22.4として,実行結果を確認せよ.

def template(x, y, z)
  "#{x}時の#{y}#{z}"
end

puts template(12, "気温", 22.4)
結果
"12時の気温は22.4"

08. 暗号文

与えられた文字列の各文字を,以下の仕様で変換する関数cipherを実装せよ.
・ 英小文字ならば(219 - 文字コード)の文字に置換
・ その他の文字はそのまま出力
この関数を用い,英語のメッセージを暗号化・復号化せよ

def cipher(str)
  str.chars
    .map{ |c| c.match?(/[a-z]/) ? (219 - c.ord).chr : c }
    .join
end


word = "Cipher Text"

cipheredWord = cipher(word)

puts cipheredWord
puts cipher(cipheredWord)
結果
"Crksvi Tvcg"
"Cipher Text"

09. Typoglycemia

スペースで区切られた単語列に対して,各単語の先頭と末尾の文字は残し,
それ以外の文字の順序をランダムに並び替えるプログラムを作成せよ.
ただし,長さが4以下の単語は並び替えないこととする.
適当な英語の文
(例えば"I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind .")
を与え,その実行結果を確認せよ.

sentence = "I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind ."

strangeSentence = sentence.split(/\s/)
                    .map{ |word|
                      word.size >= 4 ? word[0] + word[1..-2].chars.shuffle.join + word[-1] : word
                    }
                    .join(" ")

puts strangeSentence
結果
"I culnd'ot beevile taht I colud alcaluty utanrdnesd 
 waht I was rdenaig : the panonmeehl pweor of the huamn mind ."

学んだ事

  • 配列の集合演算
  • 文字とASCII文字コードの相互変換
  • 指定した範囲の文字列の摘出

準備運動でも学ぶことがたくさんありました。
そんな素晴らしい課題を公開されている乾・岡崎研究室の岡崎先生に感謝です。

次回 「第2章: UNIXコマンドの基礎」

3
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1