最初はグー、じゃんけん


21

古典的なじゃんけんを実装します。

条件:

  • ユーザーは「r」、「p」または「s」を入力します
  • プログラムは「r」、「p」または「s」と結果を出力します
  • プログラムの選択( 'r'、 'p'または 's')は擬似ランダムでなければなりません(ハワードを見ています
  • 結果は、任意の印刷可能な文字で表すことができます。ユーザーが入力したもの(ユーザーが勝ち、負け、または引き分け)の場合、常に3つの結果が考えられます。
  • ユーザーが何も入力しなかった場合、または「r」、「p」、「s」とは異なる何かが重要でない場合はどうなりますか。

必要がある:

  • ゴルフコードを提供します。
  • 改変されていないコード
  • どのようにプログラムを呼び出しますか
  • サンプル実行

タイが最も多く投票された回答を提示する場合は、文字数の少ない回答を選択します。

良いゴルフと幸運があなたに有利になるかもしれません。

私は自分の答えをJavaで投稿します。

岩の下の山に住んでいる人のために:

r =ロック

p =紙

s =はさみ

岩:はさみに勝ち、紙で負け、岩と結びます。

紙:岩に勝ち、ハサミで負け、紙でネクタイ。

はさみ:紙に勝ち、岩で負け、はさみでネクタイ。

現在のポジション:

  • UN:ユーザー名
  • PL:プログラミング言語
  • CC:文字数
  • UV:賛成票
╔══════════════════╦════════════╦══════╦════╗
║        UN        ║     PL     ║  CC  ║ UV ║
╠══════════════════╬════════════╬══════╬════╣
║ Howard           ║ GolfScript ║    6 ║ 15 ║
║ primo            ║ Perl       ║   27 ║  7 ║
║ TwiNight         ║ APL        ║   31 ║  4 ║
║ primo            ║ Perl       ║   33 ║  7 ║
║ marinus          ║ APL        ║   36 ║  5 ║
║ primo            ║ Perl       ║   38 ║  7 ║
║ primo            ║ Perl       ║   48 ║  7 ║
║ manatwork        ║ Ruby       ║   54 ║ 13 ║
║ w0lf             ║ GolfScript ║   62 ║  4 ║
║ tmartin          ║ K          ║   67 ║  2 ║
║ Abhijit          ║ Python 3   ║   74 ║  5 ║
║ beary605         ║ Python 3   ║   76 ║  4 ║
║ rlemon           ║ javascript ║   85 ║  4 ║
║ ugoren           ║ C          ║   86 ║  3 ║
║ Egor Skriptunoff ║ LUA        ║   87 ║  4 ║
║ Shmiddty         ║ javascript ║   87 ║  3 ║
║ Fors             ║ Befunge    ║  107 ║  3 ║
║ Briguy37         ║ javascript ║  117 ║  2 ║
║ Vi.              ║ Clojure    ║  129 ║  1 ║
║ Henrik           ║ C#         ║  167 ║  4 ║
║ dystroy          ║ Go         ║  169 ║  1 ║
║ Praveen          ║ javascript ║  250 ║  0 ║
║ ryan             ║ javascript ║  256 ║  1 ║
║ primo            ║ ferNANDo   ║  259 ║  5 ║
║ anakata          ║ Java       ║  259 ║  1 ║
║ epoch            ║ Java       ║  387 ║  1 ║
║ jdstankosky      ║ LOLCODE    ║ 1397 ║ 15 ║
╚══════════════════╩════════════╩══════╩════╝

ハワードの答えを選択することはできません。ルールを曲げる(成功した)試みだったためです。

primo 27文字の回答は、それ自体が擬似ランダムではないため選択できません

primo -p答え、「-pは3バイトとしてカウントされます。1つは-、1つはp、そしてもう1つは必要な空白」とカウントされます。

回答したすべての人に感謝します、あなたが楽しい時間を過ごしたことを願っています!

注:隔週でこれを編集して、テーブルを調整し、誰かが現在の回答を破った場合に選択した回答を変更しようとしています。


2
すべての結果-Win、Lose、Draw-が可能でなければならないという節を追加することを検討するかもしれません。
primo

これは人気があるので、私はLOLZ
jdstankoskyで

回答を提出するにルールを編集しました。人気はタイブレーカーのみになります。
jsedano

1
Pfft、それはもう人気ではありませんか?退屈な。
jdstankosky

1
@anakata 従来Perlgolfルール(TON Hospel自身以外のどれによってコンパイルされた)が-pための1:3バイトとしてカウントされることになる-ため、1 p、および1つの以上の必要な空白。ただし、CG.SEに関する他の多くの競合では、各オプションが1バイトとしてカウントされています。通常、どのシステムを尊重するかを決定するのは質問の作成者次第です。
primo

回答:


9

APL、31

'TWL'[1+3|-/x⍳⎕←⍞,(?3)⌷x←'rps']

x←'rps'文字列'rps'を割り当てるx

(?3)⌷ ランダムな整数1〜3を選択し、そのインデックスを選択します x

⍞, マシンの選択にユーザー入力を追加

⎕← 出力結果の文字列

x⍳ indexOfで数値配列に変換します x

-/ 2つの数値の差

1+|3 モジュラス3およびプラス1

'TWL'[...] からインデックス付け 'TWL'

サンプル

r
rp
L

ユーザーがロックを選択、プログラムが紙を選択:失う


42

LOLCODE、1397

注:勝利の要件がゴルフタイブレイクでの人気から人気タイブレイクでのゴルフに変更されたことに気付く前に、これを提出しました。

厳密な構文は実際にはありませんが、これは受け入れられると確信しています。

HAI
    I HAS A CRAZY, LUCKY, CHALLENGE, TREAT
    I HAS YUMMY ITZ "LOL U LOZED"
    I HAS MEH ITZ "NOWAI TIED"
    I HAS GROSS ITZ "OMG U WONNED"
    I HAS BURNT ITZ "LAME"
    GIMMEH CHALLENGE
    BTW I HOPE I R TEH WINZ
    LOL CRAZY IZ BETWEEN 1 AN 3
    I HAS A SUPA ITZ A BUKKIT
    LOL SUPA'Z 1 R "ROCK"
    LOL SUPA'Z 2 R "PAPER"
    LOL SUPA'Z 3 R "SCIZZORS"
    LOL LUCKY R SUPA'Z CRAZY
    GOT CHALLENGE, WTF?
        OMG "Rock"
            GOT LUCKY, WTF?
                OMG ROCK, LOL TREAT R MEH, GTFO
                OMG PAPER, LOL TREAT R YUMMY, GTFO
                OMG SCIZZORS, LOL TREAT R GROSS, GTFO
            OIC
        OMG "Paper"
            GOT LUCKY, WTF?
                OMG ROCK, LOL TREAT R GROSS, GTFO
                OMG PAPER, LOL TREAT R MEH, GTFO
                OMG SCIZZORS, LOL TREAT R YUMMY, GTFO
            OIC
        OMG "Scissors"
            GOT LUCKY, WTF?
                OMG ROCK, LOL TREAT R YUMMY, GTFO
                OMG PAPER, LOL TREAT R GROSS, GTFO
                OMG SCIZZORS, LOL TREAT R MEH, GTFO
            OIC
        OMGWTF
            VISIBLE "WHAT U SAYZ?", LOL TREAT R BURNT
            GTFO
    OIC
        BOTH SAEM TREAT AN BURNT, O RLY?
            YARLY
                VISIBLE "YOU BURNTED MAH TREAT!"
            NOWAI
                VISIBLE SMOOSH "I GUESSED " AN LUCKY
                VISIBLE TREAT
        KTHX
KTHXBAI

これが次のように正常に実行された場合 RockPaperScissors.LOL場合、いくつかの可能なランダムな結果は次のとおりです。

  • 入力: Rock-出力:I GUESSED SCIZZORS U WONNED
  • 入力: Paper-出力:I GUESSED PAPER NOWAI TIED
  • 入力: Scissors-出力:I GUESSED ROCK LOL U LOZED
  • 入力:Tuna-出力:WHAT U SAYZ? YOU BURNTED MAH TREAT!

6
LOLCODEであるためだけに+1。LOLzのために、いつか学ぶべきことのように見えます。
イッツィー

23

GolfScript

n"Draw"

上記のコードは、必要な機能を実装しています。さらに、コンピューターの戦略の(知覚された)不公平のために、プレーヤーが決して怒ったままにならないようにします。

ゴルフされていないバージョン

n"Draw"

プログラムを呼び出す方法

入力( 'r'、 'p'、 's'の単一文字)は、STDINで提供する必要があり、改行で終了する場合があります。

サンプル実行

> echo r | ruby golfscript.rb rockpaperscissors.gsc
r
Draw

コードの説明

GolfScriptに慣れていない人のために、このコードがどのように機能するかの詳細な説明を追加します。コードは基本的に3つの部分から成り立っています。

### Computer's strategy ###
# The strategy used to play r/p/s. 
# The computer is so fast, it can really guess in an instance 
# what the player has played. Since the computer should 
# not play unfair, the best strategy is to always go for a 
# draw and choose the same move.
        # on the stack is player's move
        # choose to play the same -> now the computer's move is on the stack

### Fiddle with input ###
# The input may of may not be delimited by newline.
# In order to make the output readable, we'll give
# a newline here.
n       # Push a newline onto the stack

### Give the result ###
# We can skip a complicated calculation of the result
# since we chose to play draw anyways.
"Draw"  # Push the result onto the stack

# Output is printed automatically when GolfScript code terminates.

ノート

これはコードゴルフではなく人気コンテストなので、私は最短バージョンを選択しませんでした。たぶん同点の場合、短いコードは私のソリューションをノックアウトします。それでも、ゴルフに興味がある人には、次の可能性があります。

  • 適切な入力のみを処理し、ユーザーに強制的に改行を入力させます。これにより、1文字が保存されます。
  • ルールにはわずかな不足があり、ルールを曲げることで別のキャラクターを救うことができます。結果は常に「Win」として印刷できます-正しい結果を印刷する必要があることは指定されていません。ただし、不正プログラムを実装することを選択した場合、プレーヤーはすぐに怒ることに注意してください。
  • 出力形式が適切に指定されていません。0描画の出力として選択できます。したがって、最短の有効なプログラムは単一文字コード0です。

1
OK、ルールにさらに冗長性を追加しました!ルーキーのミスを2回犯したことは認めます。
jsedano

「勝つ唯一の動きはプレーしないことです。」:P
Viezevingertjes

1
未使用バージョンと本当に良い説明のために+1
izlin 14

n"d"質問では、出力は印刷可能な文字である必要があると述べたため、完全な単語の使用については何も言わないことをお勧めします。
ender_scythe 16

20

ルビー:61 54文字

o="rps";p o[c=rand(3)],%w{Draw Win Lose}[c.-o.index$_]

どういうわけか説明:

問題全体は、次の結果を計算することで軽減されます。

  ╲ machine
h  ╲| 0 1 2
u ──┼──────
m 0 │ 0 1 2 
a 1 │ 2 0 1
n 2 │ 1 2 0

数字の意味:

  • 選択肢:0枚の岩、1枚の紙、2枚のはさみ
  • 結果:引き分け0、勝ち1、負け2

これには、machine_choice-human_choiceという式を使用しました。これにより、負の値が得られる場合がありますが、インデックスとしてのみ使用され、負のインデックスは逆方向にカウントされるため、正しい配列要素が選択されます。

# ┌── choosable object type
# │           ┌── machine's choice numeric code
# │           │                  ┌── result type
# │           │                  │                   ┌── human's choice
# │           │          ┌───────┴───────┐           │
  o="rps";p o[c=rand(3)],%w{Draw Win Lose}[c.-o.index$_]
#           └─────┬────┘                   └─────┬────┘  
#                 └── machine's choice letter    │
#                                                └── result numeric code

使用されたメソッド(その他Fixnumの明らかなメソッド):

  • Kernel.p(obj)→obj –「オブジェクトごとに、objを直接書き込みます。inspectプログラムの標準出力への改行が続きます。」
  • Kernel.rand(max = 0)→number –「引数なしで呼び出された場合、またはmax.to_i.abs == 0 randが0.0から1.0の間の擬似ランダム浮動小数点数を返します(0.0を含み、1.0を除く)。」
  • String.index(substring [、offset])→fixnumまたはnil –「str内の指定されたサブストリングまたはパターン(regexp)の最初の出現のインデックスを返します。」

ゴルフをしていない:

object_type = "rps";
result_type = %w{Draw Win Lose}

machine_choice = rand(3)
human_choice = $_

p object_type[machine_choice]

result_code = machine_choice - object_type.index(human_choice)
p result_type[result_code]

サンプル実行:

bash-4.2$ ruby -nle 'o="rps";p o[c=rand(3)],%w{Draw Win Lose}[c.-o.index$_]'
r
"p"
"Win"
p
"p"
"Draw"
s
"p"
"Lose"

1
私に非常に似ています。7バイト[(c-o.index($_)+3)%3]で置き換えることができ[c.-o.index$_]ます。また、-nl少なくとも2つのスコアをスコアに追加する必要があります。
primo

1
ドッ!それは、ネガティブインデックスを使用するという私の最初の意図でした。オペランドの順序の問題を修正した後、このアプローチを再試行するのを忘れたようです。ありがとう、@ primo。そして、もう一つのc.ヒントをありがとう。
マナトワーク

私はこの答えが大好きだと言わざるを得ません!!
jsedano

2
@manatworkのトリックは実際には.-です。点線の演算子の優先順位は、点線のない演算子よりもはるかに低くなります。たとえば、a/(b+c)に置き換えることができますa./b+c
プリモ

9

C#(167文字)

私のゴルフの最初の試み。

ゴルフ

using System;class P{static void Main(string[] i){var m="rspr";var a=m[Environment.TickCount%3];Console.WriteLine(a+" "+(i[0][0]==a?"T":m.Contains(i[0]+a)?"W":"L"));}}

ゴルフをしていない

using System;

class P
{
    static void Main(string[] i)
    {
        var m = "rspr";
        var a = m[Environment.TickCount % 3];
        Console.WriteLine(a + " " + (i[0][0] == a ? "T" : m.Contains(i[0] + a) ? "W" : "L"));
    }
}

サンプルの実行 ザ・アプリはどちらか、アプリケーションへの引数1のような単一の文字入力を必要とするrsまたはp

cmd > app.exe r

すべての可能な結果

  • cmd > app.exe r出力を与えるr T(ロック、タイ)
  • cmd > app.exe r出力p L(紙、紛失)を与える
  • cmd > app.exe r出力s W(はさみ、勝利)
  • cmd > app.exe p出力r W(ロック、勝利)を与える
  • cmd > app.exe p出力p T(ペーパー、タイ)
  • cmd > app.exe p出力s L(はさみ、失われた)を与えます
  • cmd > app.exe s出力r L(岩、失われた)を与える
  • cmd > app.exe s出力p W(紙、勝利)を与える
  • cmd > app.exe s出力s T(はさみ、ネクタイ)を出力します

9

Perl 48バイト

$%=rand 3;print"$%
"^B,(Draw,Lose,Win)[$%-=<>^B]

スクリプトは、コンピューターの観点から結果を出力します。たとえば、プレーヤーが選択rし、コンピューターが選択したs場合、結果はになりLoseます。$%(ページ番号のフォーマット)は整数値のみを含むことができるため、int型のキャストを保存するため、コンピューターの動きを保存するために使用されます。

ゴルフをしていない:

# choose a random move index 0, 1, or 2
$cindex = int(rand 3);
# convert this index to a move
# 0 => r, 1 => s, 2 => p
$cmove = "$cindex" ^ B;

# read the player's move
$pmove = <>;
# convert this move to its index
$pindex = $pmove ^ B;

# print computer's move
print $cmove, $/;
# compare indices, and output result
@result = (Draw, Lose, Win);
print $result[$cindex - $pindex];

サンプル使用法:

$ echo p | perl rps.pl
s
Win

$ echo r | perl rps.pl
r
Draw

$ echo s | perl rps.pl
p
Lose

また、次のように移動を入力して、スクリプトをインタラクティブに実行することもできますEnter

$ perl rps.pl
r
s
Lose

ルールストレッチ

Perl 35 +3バイト

$_=($%=rand 3).(D,L,W)[$%-($_^B)]^B

-pコマンドラインスイッチ(3バイトとしてカウント)が必要です。結果のそれぞれWinLoseおよびDrawにマッピングされていますWLD。コンピューターの選択と結果の間の改行は除外されています。

サンプル使用法:

$ echo r | perl -p rps.pl
sL

Perl 30 +3バイト

$_=($%=rand 3).($%-($_^B))%3^B

もう一度が必要-pです。ここではWinLoseDrawにマッピングされている210それぞれます。印刷可能な文字であるため、これはまだ技術的に準拠しています。

サンプル使用法:

$ echo r | perl -p rps.pl
s1

Perl 24 +3バイト

$_=$^T%3 .($^T-($_^B))%3^B

以前と同様に、に-pマッピングされたWLD が必要です。それぞれをリテラルのASCII文字20に置き換える必要があります。これは確かに少し伸びています。スクリプトが開始されてからエポック以降の秒数を返します。すべての結果が可能ですが、擬似ランダムとして完全に適格ではありません。210^T$^T

サンプル使用法:

$ echo r | perl -p rps.pl
s1

7

APL(38 36)

c[i],(⌽↑⌽∘'TWL'¨⍳3)[⍞⍳⍨c←'rps';i←?3]

引き分け、勝ち、負けに対して「T」、「W」、「L」を出力します。

サンプル実行:

      c[i],(⌽↑⌽∘'TWL'¨⍳3)[⍞⍳⍨c←'rps';i←?3]
p    
rW

(ユーザーは紙に「p」と入力します。コンピューターは「r」(ロック)を選択し、ユーザーが勝ちます)

説明:

  • ⌽↑⌽∘'TWL'¨⍳3:次のマトリックスを生成します。
TLW
WTL
LWT
  • ⍞⍳⍨c←'rps'c文字列'rps'に設定し、ユーザー入力を読み取り、文字列内のユーザー入力のインデックスを取得します(これは1〜3の値になります)。このインデックスは、マトリックスのY座標として使用されます。
  • i←?3:1から3までの乱数を取得して保存しiます。これはコンピューターの選択です。これは、マトリックスへのX座標として使用されます。
  • c[i]iへのインデックスとして使用し、cコンピューターの選択を「r」、「p」、または「s」として表示します。

6

ferNANDo 1184(ゴルフ259)バイト

Pythonで書かれたインタープリターは、リンクされたページの下部にあります。

ferNANDoは、1つの変数タイプ(ブール)と1つの操作(NAND)のみをサポートする難解な言語です。ご想像のとおり、これにより、一見単純なタスクを実行するためのかなり長いロジックが発生する可能性があります。stdinからの読み取り(一度に1バイト)、stdoutへの書き込み(同時に1バイト)、条件付きループ、およびランダムブールジェネレーターもサポートしています。

キーワードは一切ありません。すべてが変数です。ステートメントの関数は、含まれる変数の数によってのみ決定されます。コメントもありませんので、コードを自己コメントにするために最善を尽くしました。最後の4行は少し混乱するかもしれないが、それはおそらく、それが印刷さと言うことで十分であろうWin!LoseまたはDraw結果に応じて。

not sure, but right now i'm guessing you're_not_paper you're_scissors
you're_paper not you're_not_paper
you're_not_scissors not you're_scissors
you're_rock you're_not_paper you're_not_scissors
you're_rock you're_rock

o_shi-
i'm_not_paper right ?
i'm_scissors right ?
i'm_paper not i'm_not_paper
i'm_not_scissors not i'm_scissors
o_shi- i'm_paper i'm_scissors
o_shi- o_shi-
o_shi-
i'm_rock i'm_not_paper i'm_not_scissors
i'm_rock i'm_rock

print right now but only if i'm_not_paper i'm_scissors
print a newline here, not more, not less

i_win_if i'm_scissors you're_paper
or_if i'm_rock you're_scissors
or_even_if i'm_paper you're_rock

i_win i_win_if or_if
i_win i_win
i_win or_even_if

i_lose_if i'm_paper you're_scissors
or_if i'm_scissors you're_rock
or_even_if i'm_rock you're_paper

i_lose i_lose_if or_if
i_lose i_lose
i_lose or_even_if

i_don't_win not i_win
i_don't_lose not i_lose
we_tie i_don't_win i_don't_lose
we_tie we_tie
we_don't_tie not we_tie

print now if i_win i_lose not i_win i_win
print but not we_tie we_don't_tie i_lose i_don't_win we_don't_tie
print right now i_lose i_win i_win we_don't_tie i_don't_win
print i_don't_win but we_tie or i_don't_win we_tie now

移動の後にを入力することにより、スクリプトをインタラクティブに実行できますEnter

使用例(インタープリターに名前を付けたと仮定nand.py):

$ python nand.py rps.nand
p
s
Win!

$ python nand.py rps.nand
r
r
Draw

$ python nand.py rps.nand
s
p
Lose

編集: ferNANDoがJavaと競合できることを証明するために、259バイトの「ゴルフ」バージョンがあります。ロジックは見た目が異なります。とをチェックnot winしてnot tie、いくつかのNANDゲートを節約します(そのためnot、プレーヤーの動きのバージョンのみがnot lose必要であり、出力には必要なかったため)。ただし、読むのはそれほど面白くありません。

1 _ _ _ _ _ _ A b
B 1 b
C A B
o
P 1 ?
s 1 ?
p 1 P
S 1 s
o p s
o o
o
r P S
r r
0 1 1 1 0 0 P s
0 0 0 0 1 0 1 0
t s A
u r B
v p C
W t u
W W
W v
t p A
u s B
v r C
D t u
D D
D v
w 1 W
d 1 D
l W D
l l
0 1 0 w l 1 w w
0 1 1 d D l W D
0 1 1 l w w D W
0 W 1 d 0 W d 1

2
ハハハo_shi- o_shi- o_shi-これは陽気な自己コメントでした。
jdstankosky

1
@jdstankoskyは、おそらくaをローリングすることに少し反応し過ぎてqいますが、彼は賢明なことをして、再ロールします。
プリモ

5

Python 3.x:74文字

import time
A,f="psr",time.gmtime()[5]%3
print(A[(A.find(input())+f)%3],f)

使い方

Before Machine Proceeds it determines the outcome of the game and based 
on the outcome, it determines the choice which would result in the outcome
viz Human's choice


\     Outcome
 \    0  1  2
  \_____________
H  | 
U 0|  0  1  2
M 1|  1  2  0
A 2|  2  0  1
N  |

Where Choices are represented as 
0 --> Paper
1 --> Scissor
2 --> Rock

Outcome (From Computer's Perspective)
0 --> Draw
1 --> Win
2 --> Fail

Given the sequence of choices as a string
"psr"
So its easy to see, if computer needs to win, it needs to choose the character
next to what human chooses. 
If computer needs to loose, it needs to choose the previous character to what
human chooses


MACHINE's|      CHOICES    |  Formulation
FATE     |-----------------|  For Machine's
         |  P     S      R |  Choice
---------|-----------------|-----------------------------
WIN(1)   |        H ---> M | (CHOICE+1) % 3 = (CHOICE+WIN)%3 
---------|-----------------|-----------------------------
LOSS(2)  |  M     H -----\ | (CHOICE+2)%3   = (CHOICE+LOSS)%3 
         |  ^            | |
         |  |____________| |
---------|-----------------|------------------------------       
DRAW(0)  |        H        | (CHOICE+0)%3   = (CHOICE+DRAW)%3
         |        M        |  
---------|-----------------|         

Combining all the above we have

MACHINE's CHOICE = (HUMAN CHOICE + MACHINE's FATE) % 3

運命に基づいて、式に基づいて選択すべきものを決定します

result = (User_choice + machines_fate) % no_of_choices

machine_choice = "psr"[result]

ゴルフされていないバージョン

import time
choices = "psr"
#time.gmtime() returns the time structure in gmt
#time.gmtime()[5] is the current second tick
fate = time.gmtime()[5]%3
user_choice = input()
result = (choices.find(user_choice)+fate)%len(choices)
machine_choice = choices[result]
print(machine_choice, fate)

サンプル実行

D:\temp\rivalry>rps.py
r
r 0

D:\temp\rivalry>rps.py
r
p 1

D:\temp\rivalry>rps.py
p
r 2

D:\temp\rivalry>rps.py
p
r 2

D:\temp\rivalry>rps.py
p
s 1

D:\temp\rivalry>rps.py
p
s 1

D:\temp\rivalry>rps.py
p
p 0

2
興味深いのは、その結果を得るためにどんな記号投げ、その後、事前に結果を決定する...
アコライト

1
「プログラムの選択( 'r'、 'p'、または 's')が擬似ランダムでなければならない」という条件で、秒単位の時間が適切かどうかはわかりません。しかし、ミリ秒はおそらくそうでしょう。
primo

4

ルア、87

c,n=os.time()%3+1,'rps'print(n:sub(c,c),({'Draw','Win','Defeat'})[(n:find(...)-c)%3+1])

使用法:

$ lua rps.lua p
s   Defeat

ゴルフをしていない:

names = 'rps'
comp_idx = os.time()%3 + 1                -- 1, 2 or 3 (depends on timer)
comp_move = names:sub(comp_idx, comp_idx) -- 'r', 'p' or 's'
user_move = ...                           -- input parameter: 'r', 'p' or 's'
user_idx = names:find(user_move)          -- 1, 2 or 3
delta_idx = (user_idx - comp_idx) % 3     -- 0, 1 or 2
all_results = {'Draw', 'Win', 'Defeat'}   -- [1]=='Draw', [2]=='Win', [3]=='Defeat'
game_result = all_results[delta_idx + 1]
print(comp_move, game_result)

「Defeat」の代わりに「Lose」、「Draw」の代わりに「Tie」を使用して、3文字を保存できます。;)
冷凍エンドウのロディ

4

GolfScript 62

ハワードのものよりはるかに退屈な代替のGolfScriptソリューション :)。

プログラムはランダムに動きを選択し、ユーザーの視点から結果を表示します。

コード

'rssppr'.[6rand=]''+:§@+..&,({?)§\'Lose''Win'if}{;;§'Draw'}if`

サンプル実行

> echo s | ルビーgolfscript.rb rps.gs

r「失う」

オンラインテスト

ここでプログラムを実行し、異なる入力で実験することができます http //golfscript.apphb.com/?c=OydzJwoKJ3Jzc3BwcicuWzZyYW5kPV0nJys6wqdAKy4uJiwoez8pwqdcJ0xvc2UnJ1dpJP3P31

ただし、通常はコマンドラインで渡されるパラメーター(ユーザーの移動)がコード自体のスタックに追加されることに注意してください(このオンラインツールで「実際の」コマンドラインパラメーターを提供する方法はありません)。

「Ungolfed」バージョン

Golfolfに関しては、ungolfedが何を意味するのかまったくわからないので、コメントを追加しようとしました。うまくいけば、コードがどのように機能するかが明確になり、コードが少し読みやすくなります

# initially, the input (user's move) is on the stack

'rssppr'                # push the string 'rsspr' on the stack...
.                       # ...twice.

[
    6rand               # get a pseudo-random integer in the [0-5] range
    =                   # use the random index to get 
                        # a letter from the string above

]''+                    # workaroud to get the actual letter instead of the
                        # ASCII code

:§                      # assign the randomly chosen letter (computer's move)
                        # to a nice variable called "§"

@                       # rotates last 3 elements on the stack, bringing
                        # the user input in the uppermost position
                        # So, now we have: "rssppr" <computer_move> <user_move>
                        # on the stack

+                       # concatenate the two moves, so now we have a string
                        # that contains both (ex: "rs")

..                      # copy the move string twice
&                       # do a setwise AND to get the DISTINCT elements
,(                      # get the length of the resulting string and subtract 1
                        # (now we have 0 if the letters were equal and non-zero otherwise)

{                       # beginning of block to execute when the moves are different:

                        # now we have on the stack two strings:
                        #     - the string 'rssppr'
                        #     - the string containing the moves (ex: 'rs')

    ?                   # find the second string inside the first one,
                        # and get the index at which it occurs
                        # (or -1 if it does not)

    )                   # increment that number (we now get 0 if no occurrence, 1 otherwise)

    §                   # recall the § variable (so we display the computermove)
    \                   # rotate the uppermost two stack entries

    'Lose''Win'if       # if the move pair is found in the 'rssppr' string, 
                        # then print 'Lose', otherwise print 'Win'
}

{                       # beginning of block to execute when the moves are identical:

    ;;                  # discard the latest two stack items (not needed in this case)
    §                   # display computer's move
    'Draw'              # display the text 'Draw'
}
if                      # if computer's and user's moves were NOT equal, 
                        # execute the first block.
                        # if they were, execute the second block

`                       # put the last word in quotes to separate it from computer's move

4

C、92 86文字

main(y){
    srand(time(0));
    y="rps"[rand()%3];
    printf("%c%c\n",y,"LWWTLLW"[getchar()-y+3]);
}

コンピューターの選択、およびユーザーの視点からの結果-W =勝ち、L =負け、T =ネクタイを印刷します。選択肢のASCII値が与えられると、
単純な式x-yは描画時に0を与え(明らかに)、それぞれの場合に一意の値を与えます。


4

Python 2(86 84 80 78)、Python 3-76文字

0-引き分け、1-負け、2-勝ち

from random import*
a=raw_input()
b=choice('psr')
print(a!=b)+(b+a in'rpsr'),b

from random import*
a=input()
b=choice('psr')
print((a!=b)+(b+a in'rpsr'),b)

非ゴルフ

from random import*
moves = 'psr'
inp   = raw_input()
comp  = choice(moves)
match = comp+inp
is_not_tie = inp!=comp
wins = 'r' + moves         #rpsr; rock beats scissors, scissors beats paper, paper beats rock
print is_not_tie + (match in wins), comp

実行方法: python file_name_here.py

問題:
コンピューターAI:35文字


1
いいね!Aしかし、私はあなたが必要とは思わない、とあなたは別の文字を保存することができますfrom random import*
-grc

@grc:ありがとう、私はfrom randomそれを変えないと思ったので、試していない
...-beary605

あなたは(!= B)に(== b)の* 2を変更し、 "0ネクタイ、1-勝、2 -負け"に成果を変更することで、さらに2つの文字を削除することができます
ダラ

申し訳ありませんが、「 "0ネクタイ、1敗、2勝"」という意味です
ダラ

@ダラ:ありがとう、それを理解していなかっただろう。マナトワーク:ああ!それを修正します。
beary605

4

最初に他の人を確認せずに試してください。

ゴルフ:107 85バイト

i=prompt(),c="rps"[new Date%3],w={r:"s",p:"r",s:"p"};alert(c+(i==w[c]?2:w[i]==c?1:3))

出力は[npc-choice] [1:win、2:loss、3:tie]です

なし:

var input = prompt(),
    choices = ["r","p","s"],
    computer_choice = choices[Math.floor(Math.random() * 3)],
    outcomes = {'r':'s','p':'r','s':'p'},
    winner;

    if( input == outcomes[computer_choice] ) {
        winner = 'NPC';
    } else if ( computer_choice == outcomes[input] ) {
        winner = 'You';
    } else {
        winner = 'No one, it was a Tie!';
    }

    alert('Computer chose: ' + computer_choice + '\n' +
          'The winner is: ' + winner);

4

PowerShellの:144 133 117 111 92 73

オリジナルからの変更:

私の最初の答えから長さをほぼ半分にカットしました!

ゴルフコード:

$p=($s='rps').IndexOf((read-host));$s[($c=Random 3)];"TWLLTWWLT"[$p+$c*3]

コンソールから直接実行できます。

Ungolfed、コメント付き:

# Variable $p will store the player's selection as a ternary digit by finding its position in a string containing the possible choices.
$p=(
    # Possible choices will be stored in a variable, $s, for later reuse.
    $s='rps'
# Get the position of the player's choice from $s.
).IndexOf((read-host));

# Express the computer's choice by outputting the appropriate character from $s.
$s[(
    # Computer's choice will be stored as a ternary digit in $c.
    $c=Random 3
)];

# Outcome for the player will be chosen from a string of possible outcomes by looking up the decimal repesentation of a two-digit ternary number.
# The threes digit is represented by $c, ones digit by $p.
"TWLLTWWLT"[$p+$c*3]

# Variable cleanup - do not include in golfed code.
rv p,s,c

いくつかのサンプルはコンソールで実行されます:

enter image description here


3

JAVA 259 :(

class c {public static void main(String[]a){char y=a[0].charAt(0);char m="rps".charAt(new java.util.Random().nextInt(3));if(y==m)a[0]="T";else if((y=='r'&& m=='s')||(y=='s'&& m=='p')||(y=='p'&& m=='r'))a[0]="1";else a[0]="0";System.out.println(m+":"+a[0]);}}

高度に改変されていないコード:

class c {
    public static void main(String[] a) {
        char y = a[0].charAt(0);
        char m = "rps".charAt(new java.util.Random().nextInt(3));
        if (y == m) {
            a[0] = "T";
        } else if ((y == 'r' && m == 's') || (y == 's' && m == 'p') || (y == 'p' && m == 'r')) {
            a[0] = "1";
        } else {
            a[0] = "0";
        }
        System.out.println(m + ":" + a[0]);
    }
}

サンプルの実行:

C:> java cr

s:1

C:> java cp

p:T

C:> java cs

s:T


3

Befunge:107文字

~v@,"w"<   <   <  <
v?v3.14159265@,"l"<
"""358979323846>3-|
rps26433832>:1+|
"""7950>:2+|
>>>:,-:|
28@,"t"<

少し不格好です。それは収縮可能です、問題はどれだけです。


3

JavaScript(87)

ゴルフ:

o='LDW'[2*((a=prompt())+(b='prs'[new Date%3])!='ps'&a<b|a+b=='sp')+ +(a==b)];alert(b+o)

ゴルフをしていない:

var player = prompt(), 
    computer = 'prs'[new Date%3], // Date mod 3 "pseudo-random"
    outcome = 'LDW'[2*(player+computer != 'ps' 
                    & player < computer 
                    | player + computer == 'sp') // convert boolean W/L outcome to int (0,2)
              +
              +(player == computer)]; // convert D outcome to int (0,1)
alert(computer + outcome);

ブラウザのjavascriptコンソールにコードを貼り付けるだけで実行できます。

コンピューターの選択を印刷する前に結果を印刷できる場合(83)

alert('LDW'[2*((a=prompt())+(b='prs'[new Date%3])!='ps'&a<b|a+b=='sp')+ +(a==b)]+b)

2

K、67

{-1'f:x,*1?"rps";$[f in b:("pr";"rs";"sp");"W";f in|:'b;"L";"D"]}

win / lose / drawのためにW、L、Dを印刷します。

ゴルフをしていない:

rps:{[x]
    res:x,*1?"rps";        // join user input to random selection of r,p,s
    -1'f;                  // print the user input and the program selection to stdout
    wins:("pr";"rs";"sp"); // the universe of winning combinations
    losses:|:'wins;        // reverse each win to the get losses

    $[f in wins;    
        "win";
    f in losses;
        "lose";
    "draw"]
    }

または、より読みやすいQで:

rps:{[x]
    res:x,rand["rps"];        // join user input to random selection of r,p,s
    -1 each f;                // print the user input and the program selection to stdout
    wins:("pr";"rs";"sp");    // the universe of winning combinations
    losses:reverse each wins; // reverse each win to the get losses

    $[f in wins;    
        "win";
    f in losses;
        "lose";
    "draw"]
    }

サンプル実行:

k){-1'f:x,*1?"rps";$[f in b:("pr";"rs";"sp");"W";f in|:'b;"L";"D"]}"r"
r
s
"W"
k){-1'f:x,*1?"rps";$[f in b:("pr";"rs";"sp");"W";f in|:'b;"L";"D"]}"s"
s
s
"D"
k){-1'f:x,*1?"rps";$[f in b:("pr";"rs";"sp");"W";f in|:'b;"L";"D"]}"p"
p
s
"L"

2

Javascript、117文字

問題に対するデータ駆動型のアプローチを次に示します。これはおそらく、手動でマッピングするのではなくwin / lose / drawデータを生成することで最適化できますが、それは始まりです:)

ゴルフ:

alert((r=[{v:"r",r:d="D",p:w="W",s:l="L"},{v:"p",r:l,p:d,s:w},{v:"s",r:w,p:l,s:d}][Math.random()*3|0]).v+r[prompt()])

ゴルフをしていない:

//Output the result to the user
alert(
    (
        //Store the random computer outcome data
        randomRPSData =
            //Create the data for if the computer chooses r, p, or s
            [
                {
                    value: "r",
                    r: (d = "Draw"),
                    p: (w = "Win"),
                    s: (l = "Lose")},
                {
                    value: "p",
                    r: l,
                    p: d,
                    s: w},
                {
                    value: "s",
                    r: w,
                    p: l,
                    s: d}
            ]
            //Have the computer pick a random variable
            [Math.random() * 3 | 0]

    //Output the value the computer chose
    ).value

    //Output whether the user won or not
    + r[prompt()]
);

最後に、両方のフィドルがあります。


1

Javascript:256

ゴルフ:

i=prompt(),a=['p','r','s'];a=a[Math.floor(Math.random()*(3-1+1))+1];if(i==a){alert('d');}else if(i=='p'){if(a=='s'){alert('l');}else{alert('w');}}else if(i=='r'){if(a=='s'){alert('w');}else{alert('l');}}else if(i=='s'){if(a=='r'){alert('l');}else{alert('w')}}

なし:

i=prompt(),a=['p','r','s'];
a=a[Math.floor(Math.random()*(3-1+1))+1];
if(i==a){
    alert('d');
}
else if(i=='p'){
    if(a=='s'){
        alert('l');
    }else{alert('w');}
}else if(i=='r'){
    if(a=='s'){
        alert('w');
    }else{alert('l');}
}else if(i=='s'){
    if(a=='r'){
        alert('l');
    }else{alert('w')}
} 

1

Clojure:

(def r 0) (def s 1) (def p 2)
(def object-name #(get {'p "Paper", 's "Scissors", 'r "Rock"} %))
(def result-name #(get {\d "Draw", \w "Win", \l "Lose"} %))
(defn computer-choice [] (nth ['r 's 'p] (int (rand 3))))
(defn game [a b] (get "dwlldwwld" (+ (* 3 a) b) ))
(defn print-game [user comp result] (print (format
  "User: %s\nComputer: %s\nResult: %s\n" 
  (object-name user) (object-name comp) (result-name result))))
(println "Enter 'p', 's' or 'r' and press return")
(let [comp (computer-choice),  user (read)]  (print-game user comp (game (eval user) (eval comp))))

ミニバージョン(129コード文字):

java -jar clojure.jar -e \
"(def r 0)(def s 1)(def p 2)(let[u(read),c(nth['r 's 'p](int(rand 3)))](print c)(print (get \"dwlldwwld\"(+(* 3(eval u))(eval c)))))"

1

JAVA(387)最初のコードゴルフ!

import java.util.HashMap;public class _ {public static void main(String i[]){HashMap l = new HashMap(){{put('r',0);put('p',1);put('s',2);put(0,'T');put(1,'L');put(2,'W');}};char u =i[0].charAt(0);char c ="rps".charAt((int)(Math.random()*3)%3);int[][] m =new int[][]{{0,1,2},{2,0,1},{1,2,0}};System.out.println("U"+u+"C"+c+"R"+(Character)l.get(m[(Integer)l.get(u)][(Integer)l.get(c)]));}}

非ゴルフ

import java.util.HashMap;
public class _ {
    public static void main(String[] input) {
       input = new String[] {"s"};
       HashMap lookup = new HashMap(){{
           put('r', 0);
           put('p', 1);
           put('s', 2);
           put(0, 'T');
           put(1, 'L');
           put(2, 'W');
       }};
       char user = input[0].charAt(0);
       char computer = new char[] {'r', 'p', 's'}[(int)(Math.random()*3)%3];
       int[][] matrix = new int[][] {{0,1,2}, {2,0,1}, {1,2,0}};

       Integer userChoice = (Integer) lookup.get(user);
       Integer computerChoice = (Integer) lookup.get(computer);
       Character result = (Character) lookup.get(matrix[userChoice][computerChoice]);

       System.out.println("u:" + user + ",c:" + computer + ",r:" + result);
    }
    /*
     t = 0, l = 1, w = 2
     *
        +---------------+
        | * | r | p | s |
        +---------------+
        | r | 0 | 1 | 2 |
        +---------------+
        | p | 2 | 0 | 1 |
        +---------------+
        | s | 1 | 2 | 0 |
        +---------------+
     */
}

ゴルフ(間隔/インデント)

import java.util.HashMap;
public class _ {
public static void main(String i[]) {
    HashMap l = new HashMap(){{
        put('r',0);put('p',1);put('s',2);put(0,'T');put(1,'L');put(2,'W');
    }};

    char u =i[0].charAt(0);char c = "rps".charAt((int)(Math.random()*3)%3);
    int[][] m =new int[][]{{0,1,2},{2,0,1},{1,2,0}};

    System.out.println("U"+u+"C"+c+"R:"+(Character)l.get(m[(Integer)l.get(u)][(Integer)l.get(c)]));
}}

最短のコードではありませんが、私の最初の試み


1
1)import java.util.*2)HashMap l-> Map l3)4)の(int)代わりにキャスト5)省略6)キャストを削除7)charsの代わりにintを使用。(Integer)new Random().nextInt(3)new int[][](Character)
ハワード

1

行く(169)

ゴルフ

package main
import("fmt";"os")
func main(){v:=map[uint8]int{114:0,112:1,115:2}
u:=os.Args[1][0]
c:="rps"[os.Getpid()%3]
fmt.Printf("%c\n%c\n",c,"TWL"[(3+v[c]-v[u])%3])}

Ungolfed(でフォーマットgo fmt):

package main

import (
    "fmt"
    "os"
)

func main() {
    v := map[uint8]int{114: 0, 112: 1, 115: 2}
    u := os.Args[1][0]
    c := "rps"[os.Getpid()%3]
    fmt.Printf("%c\n%c\n", c, "TWL"[(3+v[c]-v[u])%3])
}

実行:

main.go pを実行します

s

W


1

ピス、23

J"rps"K+wOJK%-XJ'KXJtK3

出力は次の形式です。

ネクタイ:0勝:1損失:2

説明:

J"rps"             J="rps"
K+wOJ              K=input()+random_choice(J)
K                  print K
  XJ'K             index of K[0] in J
      XJtK         index of K[1] in J
 -XJ'KXJtK         difference of above indexes
%-XJ'KXJtK3        above difference mod 3

次のように実行します。

$ cat rps
J"rps"K+wOJK%-XJ'KXJtK3
s
$ cat rps | python3 pyth.py
< Extraneous debug output removed>
sp
1

あと4文字だけで、Tを引き分けに、Wを勝ちに、Lを負けに使用できます。

J"rps"K+wOJKr@"TWL"-XJ'KXJtK

インデックスの違いまではすべて同じです。その時点で、文字列へのインデックスとして違いを使用します"TWL"


注:チャレンジの投稿後にこの言語を開発しましたが、今日までチャレンジを見ていませんでした。課題は言語のどの側面にも影響しませんでした。


0

グルービー、89

v='rps'
r=new Random().nextInt(3)
print"${v[r]}${'TLW'[((r-v.indexOf(this.args[0]))%3)]}"

引数としてユーザーの選択を取ります。例:

groovy rps.groovy p
sL

0

C#およびLinqPad 133

ゴルフ:

char i,c,r;i=Console.ReadLine()[0];var a="prsp";c="prs"[new Random().Next(3)];r=i==c?'T':a.Contains(""+i+c)?'W':'L';(c+">"+r).Dump();

なし:

        char i, c, r; // i for input / c for choosen by computer / r for result
        i = Console.ReadLine()[0]; //getting input in LinqPad
        var a = "prsp"; 
        c = "prs"[new Random().Next(3)]; // Computer choose a random string
        r = i == c ? 'T' : a.Contains("" + i + c) ? 'W' : 'L'; (c + ">" + r).Dump(); //check for win - dump for output in LinqPad

サンプル出力(入力はs):r> L //コンピューターはrock(r)を選択するため、失われた


0

JavaScript (79)

古いものをぶつけますが、ここに行きます...

ペグナタイト、パイロキセナイト、スコリア、ソビテ、キンバーライト、トロンジェマイト、凝灰岩などの岩を使用できるというボーナスが追加されました。唯一の制限は、あなたが使用できないということですps ;-)


入力:

r = rock      (Or , ...)
p = paper
s = scissors

出力:

[computers choice][0=Loss, 1=Win, 2=Draw]

例:

User  Computer  Result
r     r         r2
r     p         p0
r     s         s1

ゴルフコード:

u=~~{p:1,s:2}[prompt()],c=new Date%3;alert('rps'[c]+(u==c?2:!u&c>1|u&!c|u>1&c))

使用される主なトリックは次のとおりです。

1. u = ~~{}[prompt()]

       オブジェクト{}を使用し、からのユーザー入力による値を取得していますprompt()。ここまでは順調ですね。そうする代わりに、NOT演算子を使用してr : 0強制的に変換することができます。フロア番号に頻繁に使用されますが、たとえば次のように、他のオペレーターが戻ったときに戻らないという(利点)もあります。0~~NaN+{a:1, b:2}['c']

2. c = new Date%3

       日付は、たとえば+new Dateタイムスタンプに直接変換するために使用するなどして、頻繁にだまされます。そうでない場合は、文字列表現を取得します。ここでmodを使用すると、同じ効果が得られます。

3. 'rps'[c]

       コンピュータに選択肢を与える文字列のインデックス付きアクセス0 = r1 = pまたは2 = s

4. (u==c ? 2 : !u&c>1 | u&!c | u>1&c )

   IF  u == c
       Draw                    (aka 2)
   ELSE IF !u&c>1|u&!c|u>1&c 
       Win                     (aka 1)
   ELSE
       Loss                    (aka 0)
   ENDIF


...

使用されていないコードは次のようになります。

function rock_paper_scissors() {
    var choices = {
            r : 0,
            p : 1,
            s : 2,
        },
        tr_table = ['Rock','Paper','Scissors'],
        user, pc, result
    ;

    function get_input() {
        var input = prompt("Enter your choice `r', `p' or `s':")
                    .toLowerCase();

        if (!/^[rps]/.test(input)) {
            console.warn("Bad input. Please choose `r', `p' or `s'.");
            // return get_input();
            return null;
        }
        return input[0];
    }
    function report(c1, c2) {
        if (c1 === pc) {
            return 'Draw';
        } else if (
            (c1 === 0 && c2  >  1) ||
            (c2 === 0 && c1 === 1) ||
            (c1  >  1 && c2  >  0)
        ) {
            return 'Win';
        } else {
            return 'Loss';
        }
    }

    if ((user = get_input())) {
        user = choices[user];
        pc = Math.floor(Math.random() * 3);
        result  = 
            'Computers choice: ' + tr_table[pc] + ', ' +
            'Your choice: ' + tr_table[user] + ', ' +
            'Result=' +  report(user, pc);
        console.log(result);
    }
    return result;
}

rock_paper_scissors();

0

Golfscript-29

これは今回の実際の答えです(あなたを見てn"Draw":P)。

'rps'.@\?3rand.@- 3%@@[=]''+\

ゴルフをしていない:

'rps'3rand[=]''+.2$={\;'
T'}{.@'rspr'.@?@@(;\?='
L''
W'if=}if

あなたがそれを実行できるruby golfscript.rb MyCode.txt場合は、MyCode.txtプログラム・コードがあります。

サンプルが実行されます(すべてが入力 "r"で、すべてで機能します)(タイは0、勝ちは2、損失は1):

ruby golfscript.rb MyCode.txt
r0
ruby golfscript.rb MyCode.txt
p2
ruby golfscript.rb MyCode.txt
s1

いずれかのバージョンの説明が必要な場合や、改善の可能性がある場合は、教えてください。


0

Javascript、65 71 70

コンピューターの選択出力なし:65

alert('-+0+0+0'['rppssrr'.indexOf('rps'[new Date%3]+prompt())+1])

そのソリューションが正しいことをテストするだけです:

for(x in {r:0,p:0,s:0})
  for(y in {r:0,p:0,s:0})
    console.log("%s %s %s", x, y, '-+0+0+0'['rppssrr'.indexOf(x+y)+1])

コンピューターの選択出力:71

alert((c='rps'[new Date%3])+'-+0+0+0'['rppssrr'.indexOf(c+prompt())+1])

70

alert((g='rps'[new Date%3]+prompt())+-('srps'.match(g)?-1:g[0]!=g[1]))

そしてテスト:

for(x in {r:0,p:0,s:0})
  for(y in {r:0,p:0,s:0})
    console.log((g=x+y)+-('srps'.match(g)?-1:g[0]!=g[1]))
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.