LoginSignup
2
1

More than 3 years have passed since last update.

if文なしでじゃんけん Javascript版

Last updated at Posted at 2021-03-01

if文なしでじゃんけん を見ました。

事前に勝敗を定義するのは反則な気がしたので作ってみました。
勝敗は自分と相手の手の差に mod(3) を取ればわかります。

コード

const hands = ['', '', ''];
const results = ['あいこ', 'あなたの負け', 'あなたの勝ち'];

hands.forEach((myHand, myVal) => {
  hands.forEach((yourHand, yourVal) => {
    console.log(
      `[${myHand} vs ${yourHand}] ${results[(myVal - yourVal + 3) % 3]}`
    );
  });
});

(myVal - yourVal + 3) % 3 yourVal
✊0 ✌1 ✋2
myVal ✊0 0 draw 2 win 1 lose
✌1 1 lose 0 draw 2 win
✋2 2 win 1 lose 0 draw

結果

[✊ vs ✊] あいこ
[✊ vs ✌] あなたの勝ち
[✊ vs ✋] あなたの負け
[✌ vs ✊] あなたの負け
[✌ vs ✌] あいこ
[✌ vs ✋] あなたの勝ち
[✋ vs ✊] あなたの勝ち
[✋ vs ✌] あなたの負け
[✋ vs ✋] あいこ

応用

手の種類が奇数なら、じゃんけんの拡張も可能
例えば五行に見立てて

(myVal - yourVal + 5) % 5 yourVal
木0 火1 土2 金3 水4
myVal 木0 0 draw 4 lose 3 win 2 lose 1 win
火1 1 win 0 draw 4 lose 3 win 2 lose
土2 2 lose 1 win 0 draw 4 lose 3 win
金3 3 win 2 lose 1 win 0 draw 4 lose
水4 4 lose 3 win 2 lose 1 win 0 draw

手が増えれば増えるほど、事前にすべての勝敗を定義するのが困難になりますよね。

感想

法則性はないかと表を作ってみて気づきました
が、調べてみると一般的なアルゴリズムのようですね。

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