search
LoginSignup
22

More than 5 years have passed since last update.

posted at

updated at

ズンドコキヨシ with Ruby

参考: http://qiita.com/y__sama/items/7c451dfd706f9b36729d

ひとまず1つめの実装を張っておきます
他に思いついたら足していきます

単にループ

def zundoko
  z, d = zd = ['ズン', 'ドコ']
  w1, w2, w3, w4, w5 = 5.times.map { nil }

  until [w1, w2, w3, w4, w5] == [z, z, z, z, d]
    w1, w2, w3, w4, w5 = w2, w3, w4, w5, zd.sample.tap(&method(:print))
  end

  print 'キ・ヨ・シ!'
end

zundoko

Enumerator

なるほど

def zundoko
  z, d = zd = ['ズン', 'ドコ']

  loop.lazy.map { zd.sample }.each_cons(5).with_index do |nominees, i|
    i.zero? ? nominees.each(&method(:print)) : print(nominees.last)
    break if nominees == [z, z, z, z, d]
  end

  print 'キ・ヨ・シ!'
end

zundoko

その2


def zundoko
  z, d = zd = ['ズン', 'ドコ']

  loop.lazy.map { zd.sample }.reduce([]) do |nominees, w|
    break print('キ・ヨ・シ!') if nominees == [z, z, z, z, d]
    nominees.last(4) + [w.tap(&method(:print))]
  end
end

zundoko

再帰

Z, D = ZD = ['ズン', 'ドコ']

def zundoko(nominees = [])
  return print('キ・ヨ・シ!') if nominees == [Z, Z, Z, Z, D]

  zundoko(nominees.last(4) + [ZD.sample.tap(&method(:print))])
end

zundoko

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
What you can do with signing up
22