1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby でワンライナーでズンドコキヨシ

1
Last updated at Posted at 2019-01-01

ブログ記事からの転載です。

元ネタ

元ネタが2年以上前でめちゃくちゃ今更なんですが、やってみた。
脳内で考えたコードがワンライナーでそのまま動作したのでちょっとうれしかった

Ruby でズンドコキヨシ

puts (1..).lazy.map { %w(ズン ドコ).sample }.each_cons(5).map(&method(:p)).find(&%w(ズン ズン ズン ズン ドコ).method(:==)).join
puts "キ・ヨ・シ!"
# =>
# ["ズン", "ドコ", "ズン", "ドコ", "ドコ"]
# ["ドコ", "ズン", "ドコ", "ドコ", "ズン"]
# ["ズン", "ドコ", "ドコ", "ズン", "ズン"]
# ["ドコ", "ドコ", "ズン", "ズン", "ドコ"]
# ["ドコ", "ズン", "ズン", "ドコ", "ズン"]
# ["ズン", "ズン", "ドコ", "ズン", "ズン"]
# ["ズン", "ドコ", "ズン", "ズン", "ドコ"]
# ["ドコ", "ズン", "ズン", "ドコ", "ズン"]
# ["ズン", "ズン", "ドコ", "ズン", "ズン"]
# ["ズン", "ドコ", "ズン", "ズン", "ドコ"]
# ["ドコ", "ズン", "ズン", "ドコ", "ドコ"]
# ["ズン", "ズン", "ドコ", "ドコ", "ズン"]
# ["ズン", "ドコ", "ドコ", "ズン", "ズン"]
# ["ドコ", "ドコ", "ズン", "ズン", "ズン"]
# ["ドコ", "ズン", "ズン", "ズン", "ズン"]
# ["ズン", "ズン", "ズン", "ズン", "ドコ"]
# ズンズンズンズンドコ
# キ・ヨ・シ!

ワンライナーで書いているのでちょっと複雑かもしれませんが、やっていることは至極単純で

(1..)                           # Ruby 2.6 から入った (1..) で無限配列を生成
.lazy                           # 遅延処理するようにする
.map { %w(ズン ドコ).sample }   # ランダムな "ズン" "ドコ" な配列に変換
.each_cons(5)                   # 無限リストを5個ずつの配列に分割
.map(&method(:p))               # この時点で一旦出力
.find(&%w(ズン ズン ズン ズン ドコ).method(:==))  # ["ズン", "ズン", "ズン", "ズン", "ドコ"] の組み合わせを探す
.join                           # 結果を結合

無限リスト + #lazy を使って遅延処理しつつ、#each_cons(5) で分割して ["ズン", "ズン", "ズン", "ズン", "ドコ"] という並びがあれば終了する、っていう処理です。
やってることは割と力技。
ちなみに map(&%w(ズン ドコ).method(:sample)) と書きたかったんですが、#sample が引数を受け取ってしまうのでダメでした。

1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?