LoginSignup
24
19

More than 5 years have passed since last update.

ズンドコキヨシ with python / ruby / Lua

Last updated at Posted at 2016-03-10

元ネタ
- 正直これを思いつくのがスゴい。
- fizzbuzzより少し複雑なので言語の勉強によい気がする。

python版

最終コード

  • 基本的なところで間違っていたので、指摘をいただきました。
  • あわせて少しリファクタリングもいただきました。

ズンは四回

def kiyoshi():
    zd=deque(list(),5)
    while ''.join(zd)!='ズンズンズンズンドコ':
        word=choice(['ズン','ドコ'])
        print(word)
        zd.append(word)
    print('キ・ヨ・シ!')

以下間違えたコード

こんな感じ?
deque使うとかなりシンプル。

from collections import deque
from random import choice
def kiyoshi():
    zd=deque(list(),4)
    while True:
        if "".join(zd)=='ズンズンズンドコ':
            print("キ・ヨ・シ!")
            break
        else:
            word=choice(['ズン','ドコ'])
            print(word)
            zd.append(word)

モニタリング

%matplotlib inline
import pandas as pd
def kiyoshi2():
    c=0
    zd=deque(list(),4)
    while True:
        if "".join(zd)=='ズンズンズンドコ':
            print("キ・ヨ・シ!")
            break
        else:
            word=choice(['ズン','ドコ'])
            print(word)
            zd.append(word)
            c+=1
    return c
rslts=[kiyoshi2() for i in range(10000)]
pd.DataFrame(rslts).hist(bins=30)

kiyoshi.png

オリジナルのアルゴリズムはzunカウンターを用いている様子。

def kiyoshi_org():
    zun=0
    while True:
        word=choice(['ズン','ドコ'])
        print (word)
        if word == 'ズン':
            zun+=1
        elif zun>=3:
            print("キ・ヨ・シ!")
            break
        else: zun=0

ruby版

  • こちらの方がスマートです。
  • Ruby楽しくていいな。
kiyoshi.rb
#! ruby -Ku
require "kconv"

def kiyoshi()
  zd=[]
  while zd.join!="ズンズンズンズンドコ" do
    word=["ズン","ドコ"].sample
    p word
    zd<<word
    zd.slice!(0) if zd.length>=6
  end
  p "キ・ヨ・シ!"
end

def kiyoshi_org()
  zun=0
  while true do
    word = ["ズン","ドコ"].sample
    p word
    if word == "ズン"
      zun+=1
    elsif zun <= 3
      zun = 0
    else
      p "キ・ヨ・シ!"
      break
    end
  end
end

kiyoshi()
kiyoshi_org()

いまいち do end構文が慣れないな。

Lua版

  • はじめてlua書いた。確かに早い気がする。
  • 配列の連結みたいの探したけど見つからなかった。
  • 日本語文字化けするので、とりあえずローマ字で。
kiyoshi.lua
function kiyoshi_org()
  words={"zun","doko"}
  zun=0
  while true do
    word = words[math.random (#words)]
    print (word)
    if word == "zun" then zun = zun + 1
    elseif zun < 4 then zun =0
    else break
    end
  end
  print "ki yo shi!"
end


function kiyoshi()
  words={"zun","doko"}
  zd={}
  while true do
    word = words[math.random (#words)]
    print (word)
    table.insert(zd, word)
    str=""
    for i,value in ipairs(zd) do
      str = str .. value
    end
    if #zd==5 then
      if str == "zunzunzunzundoko" then break
      else table.remove(zd,1)
      end
    end
  end
  print "ki yo shi!"
end

次何やろうかな・・・

24
19
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
24
19