LoginSignup
14

More than 5 years have passed since last update.

ズンドコキヨシ with JavaScript

Last updated at Posted at 2016-03-11

流行り?のズンドコキヨシのJavaScript版です。ついでにコードゴルフしてみました。結果は文字列に足していき、最後にconsole.logで全て出力します。また、文字数を数えるときはカタカナなども1文字としています。

配列にどんどん突っ込む

z="ズン\n", d="ドコ\n", s="", a=[]
while(a.join("") !== z+z+z+z+d) {
  a.shift()
  a[4] = Math.random() < 0.5 ? z : d
  s += a[4]
}
console.log(s + "キ・ヨ・シ!")

JavaScriptの==!=は比較の時に型が変換されることや、whileよりforの方が短くかけることなどを利用して、宣言なども地道に短くしていくと、

for(a=[z="ズン\n",d="ドコ\n",s=""];a+""!=[z,z,z,z,d];s+=a[4]=Math.random()<.5?z:d)a.shift();console.log(s+"キ・ヨ・シ!")

111文字だった。

文字列を切り取って比較

z="ズン\n", d="ドコ\n", s=""
while (s.slice(-15) !== z+z+z+z+d) {
  s += Math.random() < 0.5 ? z : d
}
console.log(s + "キ・ヨ・シ!")

同様に短くすると、

for(z="ズン\n",d="ドコ\n",s="";s.slice(-15)!=z+z+z+z+d;)s+=Math.random()<.5?z:d;console.log(s+"キ・ヨ・シ!")

99文字だった。先ほどの[4]もですが、-15のマジックナンバー感が微妙ですね……。

ズンをカウントし、ドコのとき4以上ならキヨシ、そうでなければリセット

z="ズン\n", d="ドコ\n", c=0, s=""
while(1) {
  if (Math.random() < 0.5) {
    s += z
    c++
  } else {
    s += d
    if (c >= 4) break
    else c = 0
  }
}
console.log(s + "キ・ヨ・シ!")

フラグ、型変換、三項演算子、短絡評価などを組み合わせ、

for(f=z="ズン\n",d="ドコ\n",c=s="";f;)s+=Math.random()<.5?++c&&z:(f=c<4,c=0,d);console.log(s+"キ・ヨ・シ!")

98文字だった。ちょっと複雑すぎる。

文字列検索

z="ズン\n", d="ドコ\n", s=""
while (s.indexOf(z+z+z+z+d) === -1) {
  s += Math.random() < 0.5 ? z : d
}
console.log(s + "キ・ヨ・シ!")

indexOfよりmatchの方が短いので、

for(z="ズン\n",d="ドコ\n",s="";!s.match(z+z+z+z+d);)s+=Math.random()<.5?z:d;console.log(s+"キ・ヨ・シ!")

95文字だった。

まとめ

というわけで、自分の技量だと95文字が限界でした。文字列検索するのが一番短かったわけですが、シンプルでわかりやすい上、マジックナンバーが無く応用しやすそうでいいですね。もっと短く出来るという方、お待ちしております。

参考

ズンドコキヨシまとめ
「ズン ドコ」の検索結果 - Qiita

追記1

ES2015(ES6)で記録更新しました。
ズンドコキヨシ with ES2015 (ES6)

追記2

@gaogao_9 さんの提案をもとに、83文字に!

for(s="";!/(ズン){4}ド/.test(s);s+=Math.random()<.5?"ズン":"ドコ");console.log(s+"キ・ヨ・シ!")

追記3

sの検索と結合をまとめた。82文字!

for(s="";!/(ズン){4}ド/.test(s+=Math.random()<.5?"ズン":"ドコ"););console.log(s+"キ・ヨ・シ!")

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
14