岩、紙、はさみ、トカゲ、スポック[閉鎖]


16

入力として2つの文字列を受け取り、結果に対して単一の出力を返す関数を作成します。最も人気のある答えが勝ちです。

じゃんけん・トカゲ・スポックのルールは次のとおりです。

  • はさみカット紙
  • 紙は岩を覆う
  • ロッククラッシュトカゲ
  • トカゲはスポックを毒する
  • スポックはハサミを打ちます
  • はさみはトカゲを断頭します
  • トカゲは紙を食べる
  • 紙はスポックを反証する
  • スポックは岩を蒸発させる
  • 岩はさみ

考えられるすべての入力ケースの出力は次のとおりです。

winner('Scissors', 'Paper') -> 'Scissors cut Paper'
winner('Scissors', 'Rock') -> 'Rock breaks Scissors'
winner('Scissors', 'Spock') -> 'Spock smashes Scissors'
winner('Scissors', 'Lizard') -> 'Scissors decapitate Lizard'
winner('Scissors', 'Scissors') -> 'Scissors tie Scissors'
winner('Paper', 'Rock') -> 'Paper covers Rock'
winner('Paper', 'Spock') -> 'Paper disproves Spock'
winner('Paper', 'Lizard') -> 'Lizard eats Paper'
winner('Paper', 'Scissors') -> 'Scissors cut Paper'
winner('Paper', 'Paper') -> 'Paper ties Paper'
winner('Rock', 'Spock') -> 'Spock vaporizes Rock'
winner('Rock', 'Lizard') -> 'Rock crushes Lizard'
winner('Rock', 'Scissors') -> 'Rock breaks Scissors'
winner('Rock', 'Paper') -> 'Paper covers Rock'
winner('Rock', 'Rock') -> 'Rock ties Rock'
winner('Lizard', 'Rock') -> 'Rock crushes Lizard'
winner('Lizard', 'Spock') -> 'Lizard poisons Spock'
winner('Lizard', 'Scissors') -> 'Scissors decapitate Lizard'
winner('Lizard', 'Paper') -> 'Lizard eats Paper'
winner('Lizard', 'Lizard') -> 'Lizard ties Lizard'
winner('Spock', 'Rock') -> 'Spock vaporizes Rock'
winner('Spock', 'Lizard') -> 'Lizard poisons Spock'
winner('Spock', 'Scissors') -> 'Spock smashes Scissors'
winner('Spock', 'Paper') -> 'Paper disproves Spock'
winner('Spock', 'Spock') -> 'Spock ties Spock'

@Sean Cheshireが提案する追加の課題:このサイトのリストなどのカスタムリストを許可します。nアイテムのリストでは、アイテムは前の(n-1)/ 2に負け、次の(n-1)/ 2に勝ちます。


7
25要素のルックアップテーブルを作成することは容易ではなく、人気があることはコードチャレンジではありません。
ピーターテイラー

6
そして、私が人気があることはコードチャレンジではないと言うとき:そのタグの説明は始まりますコードチャレンジは、コードサイズ以外の客観的な基準のためにプログラミングパズルを解決する創造的な方法の競争です。「最も人気のある回答が勝つ」は客観的な基準ではありません。2つの回答のテキストを誰かに渡して、最も人気のあるものを尋ねることはできません。
ピーターテイラー

1
@ PeterTaylor、dansalmoは正しい、そのルックアップテーブルがループ内にある限り:これはConwayの有名な定理です:en.wikipedia.org/wiki/FRACTRAN
boothby

1
@dansalmoリンクするチャレンジは、popularity-contestタグが存在する前に作成されました。
プリモ

1
チャレンジに追加する提案- このサイトから最大101項目までのカスタムリストを許可します。nアイテムのリストでは、アイテムは前の(n-1)/ 2に負け、次の(n-1)/ 2に勝ちます
SeanC

回答:


13

APL

vs←{
    n←'Scissors' 'Paper' 'Rock' 'Lizard' 'Spock'
    x←n⍳⊂⍺ ⋄ y←n⍳⊂⍵ ⋄ X←⍺ ⋄ Y←⍵ ⋄ r←{X,⍵,⊂Y}
    x=y:     r (-x=0)↓'ties'
    y=5|1+x: r x⌷'cut' 'covers' 'crushes' 'poisons' 'smashes'
    y=5|3+x: r x⌷'decapitate' 'disproves' 'breaks' 'eats' 'vaporizes'
    ⍵∇⍺
}

タイ/タイを含む、すべての場合に必要なとおりに正確に出力します。実際の単語を除き、ルックアップテーブルはありません。

あなたはhttp://ngn.github.io/apl/web/でそれを試すことができます

'Spock' vs 'Paper'
Paper  disproves  Spock

APLは知っています!


+1、今までAPLに気付いたことはありません。魅惑的。あなたの構造もクールです。最後の行が一番好きです。
ダンサルモ

@dansalmoありがとう:)とても気に入っています。そして今、github.com / ngn / aplのおかげで、オープンソースでウェブ対応の通訳者がいます(何十年もの間、商用通訳者しかいませんでした)
Tobia

@dansalmoところで、APLは、Pythonでやろうとしているような機能的なコーディングに最適です(私もやりたいです)
Tobia

10

SED

#!/bin/sed
#expects input as 2 words, eg: scissors paper

s/^.*$/\L&/
s/$/;scissors cut paper covers rock crushes lizard poisons spock smashes scissors decapitates lizard eats paper disproves spock vaporizes rock breaks scissors/
t a
:a
s/^\(\w\+\)\s\+\(\w\+\);.*\1 \(\w\+\) \2.*$/\u\1 \3 \u\2/
s/^\(\w\+\)\s\+\(\w\+\);.*\2 \(\w\+\) \1.*$/\u\2 \3 \u\1/
t b
s/^\(\w\+\)\s\+\1;\(\1\?\(s\?\)\).*$/\u\1 tie\3 \u\1/
:b

1
これは...悪魔的なものです。
ウェインコンラッド14年

4

これは、任意のサイズのルール文字列に基づいた一般的なソリューションです。適切な名前「Spock」に対して正しい大文字化を実行し、複数のオブジェクトに対して「tie」ではなく「tie」を指定するルールも許可します。

def winner(p1, p2):
    rules = ('scissors cut paper covers rock crushes lizard poisons Spock'
    ' smashes scissors decapitate lizard eats paper disproves Spock vaporizes'
    ' rock breaks scissors tie scissors'.split())

    idxs = sorted(set(i for i, x in enumerate(rules) 
                      if x.lower() in (p1.lower(), p2.lower())))
    idx = [i for i, j in zip(idxs, idxs[1:]) if j-i == 2]
    s=' '.join(rules[idx[0]:idx[0]+3] if idx 
          else (rules[idxs[0]], 'ties', rules[idxs[0]]))
    return s[0].upper()+s[1:]

結果:

>>> winner('spock', 'paper')
'Paper disproves Spock'
>>> winner('spock', 'lizard')
'Lizard poisons Spock'
>>> winner('Paper', 'lizard')
'Lizard eats paper'
>>> winner('Paper', 'Paper')
'Paper ties paper'
>>> winner('scissors',  'scissors')
'Scissors tie scissors'    

定義する際rulesに、リテラル連結の代わりに複数行の文字列を使用できます。これにより、冗長な括弧を削除できます。
バクリウ

3

Python

class Participant (object):
    def __str__(self): return str(type(self)).split(".")[-1].split("'")[0]
    def is_a(self, cls): return (type(self) is cls)
    def do(self, method, victim): return "%s %ss %s" % (self, method, victim)

class Rock (Participant):
        def fight(self, opponent):
                return (self.do("break", opponent)  if opponent.is_a(Scissors) else
                        self.do("crushe", opponent) if opponent.is_a(Lizard)   else
                        None)

class Paper (Participant):
        def fight(self, opponent):
                return (self.do("cover", opponent)    if opponent.is_a(Rock)  else
                        self.do("disprove", opponent) if opponent.is_a(Spock) else
                        None)

class Scissors (Participant):
        def fight(self, opponent):
                return (self.do("cut", opponent)       if opponent.is_a(Paper)  else
                        self.do("decaitate", opponent) if opponent.is_a(Lizard) else
                        None)

class Lizard (Participant):
        def fight(self, opponent):
                return (self.do("poison", opponent) if opponent.is_a(Spock) else
                        self.do("eat", opponent)    if opponent.is_a(Paper) else
                        None)

class Spock (Participant):
        def fight(self, opponent):
                return (self.do("vaporize", opponent) if opponent.is_a(Rock)     else
                        self.do("smashe", opponent)    if opponent.is_a(Scissors) else
                        None)

def winner(a, b):
    a,b = ( eval(x+"()") for x in (a,b))
    return a.fight(b) or b.fight(a) or a.do("tie", b)

はさみは、「カットして、複数あるS」紙と「decaitate 」トカゲ」は間違っている(最後のものはあまりにもPをミス)と。 『スポックsmashs『スマッシュ』でなければなりません』;)
daniero

@daniero、ありがとう。はさみの問題に気づきましたが、それを修正すると事態が複雑になります。「スマッシュ」の修正。
ウゴレン

@Daniel "Scissors"は複数形です。「はさみ」も単数形です。参照してくださいen.wiktionary.org/wiki/scissors
DavidC

とても微妙です。大好きです。
kaoD

2

Python

def winner(p1, p2):
    actors = ['Paper', 'Scissors', 'Spock', 'Lizard', 'Rock']
    verbs = {'RoLi':'crushes', 'RoSc':'breaks', 'LiSp':'poisons',
             'LiPa':'eats', 'SpSc':'smashes', 'SpRo':'vaporizes', 
             'ScPa':'cut', 'ScLi':'decapitate', 'PaRo':'covers', 
             'PaSp':'disproves', 'ScSc':'tie'}
    p1, p2 = actors.index(p1), actors.index(p2)
    winner, loser = ((p1, p2), (p2, p1))[(1,0,1,0,1)[p1 - p2]]
    return ' '.join([actors[winner],
                     verbs.get(actors[winner][0:2] + actors[loser][0:2],
                               'ties'),
                     actors[loser]])

1
ちなみに、「緩い」は「きつく」の反対です。「敗者」は「勝者」の反対です。そして、コードに数文字を保存します。
ジョー

2

Ruby、算術アプローチ

アクターは、各アクターa[i]がアクターa[i+1]a[i+2]、モジュロ5 に対して勝つような方法で配列に配置できます。

%w(Scissors Lizard Paper Spock Rock)

その後、俳優のためのA指標でi、我々は彼がagains俳優と一致するかを確認することができB、インデックスをj実行してresult = (j-i)%5結果:12俳優Aがそれぞれ彼の前に俳優の1または2ヶ所に対して勝ったことを意味します。3そして、4同様に、彼は、アレイ内の彼の後ろ俳優敗れたことを意味します。0ネクタイを意味します。(これは言語に依存する可能性があることに注意してください。Ruby (j-i)%5 == (5+j-i)%5ではj>i

私のコードの最も興味深い部分は、このプロパティを使用して2つのアクターのインデックスの並べ替え関数を見つけることです。戻り値は、-1、0、または1 になります。

winner,loser = [i,j].sort { |x,y| ((y-x)%5+1)/2-1 }

すべてがここにあります:

def battle p1,p2
    who = %w(Scissors Lizard Paper Spock Rock)
    how = %w(cut decapitate poisons eats covers disproves smashes vaporizes crushes breaks)
    i,j = [p1,p2].map { |s| who.find_index s }

    winner,loser = [i,j].sort { |x,y| ((y-x)%5+1)/2-1 }

    method = (winner-loser)%5/2
    what = method == 0 && "ties" || how[winner*2 + method-1]

    return "#{who[winner]} #{what} #{who[loser]}"
end

2

Python


  def winner(p,q):
        if p==q:
           return(' '.join([p,'tie',q]))
        d = {'ca':'cut','ao':'covers','oi':'crushes','ip':'poisons','pc': 'smashes','ci':'decapitate','ia':'eats', 'ap':'disproves', 'po':'vaporizes','oc': 'breaks'}
        [a,b] = [p[1],q[1]]
        try:
           return(' '.join([p,d[a+b],q]))
        except KeyError:
           return(' '.join([q,d[b+a],p]))

扱いにくい辞書を使用します。


良いですね。 return(' '.join([p,'tie' + 's'*(p[1]!='c'),q]))動詞の時制が正しくなります。
ダンサルモ

2

C#

仮定

対戦相手はnアイテムの配列に配置され、プレイヤーは(n-1)/ 2プレイヤーを前に倒し、後ろの(n-1)/ 2プレイヤーに負けます。(偶数のリストでは、プレーヤーは背後の((n-1)/ 2 + 1)プレーヤーに負けます)

プレーヤーのアクションは、[(indexOfPlayer *(n-1)/ 2)]から[(indexOfPlayer *(n-1)/ 2))+(n-2)/ 2-1の範囲内のアクションの配列に配置されます]。

追加情報

CircularBuffer<T>「無限に」アドレス可能な配列を作成するための配列のラッパーです。このIndexOf関数は、配列の実際の境界内のアイテムのインデックスを返します。

クラス

public class RockPaperScissors<T> where T : IComparable
{
    private CircularBuffer<T> players;
    private CircularBuffer<T> actions;

    private RockPaperScissors() { }

    public RockPaperScissors(T[] opponents, T[] actions)
    {
        this.players = new CircularBuffer<T>(opponents);
        this.actions = new CircularBuffer<T>(actions);
    }

    public string Battle(T a, T b)
    {
        int indexA = players.IndexOf(a);
        int indexB = players.IndexOf(b);

        if (indexA == -1 || indexB == -1)
        {
            return "A dark rift opens in the side of the arena.\n" +
                   "Out of it begins to crawl a creature of such unimaginable\n" +
                   "horror, that the spectators very minds are rendered\n" +
                   "but a mass of gibbering, grey jelly. The horrific creature\n" +
                   "wins the match by virtue of rendering all possible opponents\n" +
                   "completely incapable of conscious thought.";
        }

        int range = (players.Length - 1) / 2;

        if (indexA == indexB)
        {
            return "'Tis a tie!";
        }
        else
        {
            indexB = indexB < indexA ? indexB + players.Length : indexB;
            if (indexA + range < indexB)
            {
                // A Lost
                indexB = indexB >= players.Length ? indexB - players.Length : indexB;
                int actionIndex = indexB * range + (indexA > indexB ? indexA - indexB : (indexA + players.Length) - indexB) - 1;

                return players[indexB] + " " + actions[actionIndex] + " " + players[indexA];
            }
            else
            {
                // A Won
                int actionIndex = indexA * range + (indexB - indexA) - 1;

                return players[indexA] + " " + actions[actionIndex] + " " + players[indexB];
            }
        }
    }
}

string[] players = new string[] { "Scissors", "Lizard", "Paper", "Spock", "Rock" };
string[] actions = new string[] { "decapitates", "cuts", "eats", "poisons", "disproves", "covers", "vaporizes", "smashes", "breaks", "crushes" };

RockPaperScissors<string> rps = new RockPaperScissors<string>(players, actions);

foreach (string player1 in players)
{
    foreach (string player2 in players)
    {
        Console.WriteLine(rps.Battle(player1, player2));
    }
}
Console.ReadKey(true);

1

Python、ワンライナー

winner=lambda a,b:(
    [a+" ties "+b]+
    [x for x in 
        "Scissors cut Paper,Paper covers Rock,Rock crushes Lizard,Lizard poisons Spock,Spock smashes Scissors,Scissors decapitate Lizard,Lizard eats Paper,Paper disproves Spock,Spock vaporizes Rock,Rock break Scissors"
        .split(',') 
     if a in x and b in x])[a!=b]

とてもかっこいい!.split(', ')ルールをまとめてジャムする必要はありません。
-dansalmo

@dansalmo、ありがとう、しかしJammingTheRulesTogetherに害はありません。ゴルフコンテストではありませんが、短ければ短いほど良いと思います。
ウゴレン

1

私が思いついたほんの小さなこと:

echo "winners('Paper', 'Rock')"|sed -r ":a;s/[^ ]*'([[:alpha:]]+)'./\1/;ta;h;s/([[:alpha:]]+) ([[:alpha:]]+)/\2 \1/;G"|awk '{while(getline line<"rules"){split(line,a," ");if(match(a[1],$1)&&match(a[3],$2))print line};close("rules")}' IGNORECASE=1

ここで、ルールは与えられたすべてのルールを含むファイルです。


0

Python

@TobiaのAPLコードに触発されました。

def winner(p1, p2):
  x,y = map(lambda s:'  scparolisp'.find(s.lower())/2, (p1[:2], p2[:2]))
  v = (' cut covers crushes poisons smashes'.split(' ')[x*(y in (x+1, x-4))] or
       ' decapitate disproves breaks eats vaporizes'.split(' ')[x*(y in (x+3, x-2))])
  return ' '.join((p1.capitalize(), v or 'tie'+'s'*(x!=1), p2)) if v or p1==p2 \
    else winner(p2, p1)

結果:

>>> winner('Spock', 'paper')
'Paper disproves Spock'
>>> winner('Spock', 'lizard')
'Lizard poisons Spock'
>>> winner('paper', 'lizard')
'Lizard eats paper'
>>> winner('paper', 'paper')
'Paper ties paper'
>>> winner('scissors',  'scissors')
'Scissors tie scissors'    

0

C ++

#include <stdio.h>
#include <string>
#include <map>
using namespace std ;
map<string,int> type = { {"Scissors",0},{"Paper",1},{"Rock",2},{"Lizard",3},{"Spock",4} };
map<pair<int,int>, string> joiner = {
  {{0,1}, " cuts "},{{0,3}, " decapitates "}, {{1,2}, " covers "},{{1,4}, " disproves "},
  {{2,3}, " crushes "},{{2,0}, " crushes "},  {{3,4}, " poisons "},{{3,1}, " eats "},
  {{4,0}, " smashes "},{{4,2}, " vaporizes "},
} ;
// return 0 if first loses, return 1 if 2nd wins
int winner( pair<int,int> p ) {
  return (p.first+1)%5!=p.second && (p.first+3)%5!=p.second ;
}
string winner( string sa, string sb ) {
  pair<int,int> pa = {type[sa],type[sb]};
  int w = winner( pa ) ;
  if( w )  swap(pa.first,pa.second), swap(sa,sb) ;
  return sa+(pa.first==pa.second?" Ties ":joiner[pa])+sb ;
}

ちょっとしたテスト

int main(int argc, const char * argv[])
{
  for( pair<const string&, int> a : type )
    for( pair<const string&, int> b : type )
      puts( winner( a.first, b.first ).c_str() ) ;
}

0

Javascript

function winner(c1,c2){
    var c = ["Scissors", "Paper", "Rock", "Lizard", "Spock"];
    var method={
        1:["cut", "covers", "crushes", "poisons", "smashes"],
        2:["decapitate", "disproves", "breaks", "eats", "vaporizes"]};
    //Initial hypothesis: first argument wins
    var win = [c.indexOf(c1),c.indexOf(c2)];
    //Check for equality
    var diff = win[0] - win[1];
    if(diff === 0){
        return c1 + ((win[0]===0)?" tie ":" ties ") + c2;
    }
    //If s is -1 we'll swap the order of win[] array
    var s = (diff>0)?1:-1;
    diff = Math.abs(diff);
    if(diff >2){
        diff = 5-diff;
        s= s * -1;
    }
    s=(diff==1)?s*-1:s;
    if(s === -1){
        win = [win[1],win[0]];
    }
    return c[win[0]] + " " + method[diff][win[0]] + " " + c[win[1]];
}

0

Javascript

これはゴルフのコンテストではないようですが、このスレッドを見つける前にしばらくこのパズルをいじっていました。

これは、278文字の(標準)jsバージョンです。

function winner(a,b){var c={rock:0,paper:1,scissors:2,spock:3,lizard:4},d="crushe,crushe,cover,disprove,cut,decapitate,smashe,vaporize,poison,eat".split(","),i=c[a],j=c[b],I=i==(j+3)%5;return i^j?i==(j+1)%5||I?a+" "+d[i*2+I]+"s "+b:b+" "+d[j*2+(j==(i+3)%5)]+"s "+a:a+" ties "+b}

または、259文字でE6機能(Firefoxでのみ動作する可能性が高い)を使用するもの:

winner=(a,b,c={rock:0,paper:1,scissors:2,spock:3,lizard:4},d="crushe,crushe,cover,disprove,cut,decapitate,smashe,vaporize,poison,eat".split(","),i=c[a],j=c[b],I=i==(j+3)%5)=>i^j?i==(j+1)%5||I?a+" "+d[i*2+I]+"s "+b:b+" "+d[j*2+(j==(i+3)%5)]+"s "+a:a+" ties "+b
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.