ロシアンルーレット


28

ロシアンルーレットをプレイするプログラムを作成してください!

プログラムが開始された場合、

  • 「私は生き残った!」を印刷した後、5分の1の確率で正常に終了するはずです。
  • プログラムがクラッシュする可能性は6分の1になります。(セグメンテーション障害など)

入力も他の出力も許可されていません。

ランダム性は公平である必要があります。均一な確率分布を持っている必要があります。つまり、初期化されていない変数(またはシードのないRNG)MOD 6では不十分です。

ソリューションが1つの専用オペレーティングシステム/プラットフォームのみで機能する場合、スコアに6バイトのペナルティが課せられます。

最初の有効な回答から10日以内に最短のコードが優先されます。


1
ドキュメントで明示的に保証されていなくても、基礎となるランタイムが公平であることを信頼できますか?たとえば、Python randrange(5)はとして実装されrandrange(MAX_INT)%6ます。
ウゴレン

創造性を刺激するために、ゼロ除算に依存しないソリューションにボーナスを付与することを検討できます。
primo

おそらく、ボーナスは2でスコアを割る関与させるべきであると述べた
ジョー・Z.

1
@JoeZeng:それは多すぎたでしょう。通常、ほんの数文字のコストで、nullポインター参照などの別のエラーにすることができます。
-vsz

そうですか。私はコードゴルフパズルのスコアリング条件を作成するのにあまり経験がないので、まだそのようなことを学んでいます。
ジョーZ.

回答:


4

05AB1E13 12 バイト

6LΩiFë“IЖd!

@Emignaのおかげで-1バイト。

05AB1Eは実際にはまったくエラーにならないはずですが、05AB1Eの新しいバージョンには従来のバージョンと比べてまだいくつかの問題があるので、この挑戦​​のためにエラーを出すためにそれを利用できます。

オンラインでお試しください。

説明:

6L          # Create the list [1,2,3,4,5,6]
  Ω         # Get a random choice from this list
   i        # If it is 1:
    F       #  Do a ranged loop, which currently results in a "(RuntimeError) Could not
            #  convert  to integer." error when no argument is given
   ë        # Else:
    IЖd!  #  Push dictionary string "I survived!" (which is output implicitly as result)

(セクション鉱山のこの05AB1Eチップを参照してください。辞書を使用する方法?理由を理解すること“IЖd!です"I survived!"


5ÝΩz“IЖd!動作するようですが、どうやら1 / 0 = 0
マジックタコop

1
@MagicOctopusUrnええ、05AB1Eはほとんどエラー.0になりません。05AB1Eの古いバージョンでSTDERRに0による除算エラーをスローする非常に古いビルトインは別として、レガシー05AB1Eでエラーを起こす方法すらまったく知りません。 。しかし、新しいバージョンにはまだかなり多くのエラーがあります。;)
Kevin Cruijssen

1
古いものが懐かしく、.0何度も誰かが「ワット...なぜそれが命令なのか?」
マジックタコop

11

PHP 38バイト

<?~$$s[rand(+$s=sssss,5)]?>I survived!

+非数値文字列の前にaを配置すると、に評価され0ます。必要がありますrand(0,5)返す5$s[rand(0,5)](以降、空の文字列になります$sのみ5文字の長さ)、およびその後に$$s[rand(0,5)]初期化されていない変数になります。反転を試みると、サポートされていないオペランドタイプで停止します。その他の値は0-4を返しs$s定義されているため、生き残ります。

注:PHPバージョン4.2.0以降、乱数ジェネレーターは自動的にシードされます


6

R 30

"I survived!"[6*runif(1)<5||Z]

6回のうち1回、エラーがスローされます。 Error: object 'Z' not found


6

ルビー、24〜28

p rand(6)<5?"I survived!":1/0

約6回ごとに、 ZeroDivisionError

24文字の短いバージョンもあります(ugorenとhistocratに感謝します)。

6/rand(6);p"I survived!"

"出力で受け入れない場合は、さらに3文字が必要です。最初のオプション(puts)は改行を追加し、2番目($><<)は改行を作成しません。

6/rand(6);puts"I survived!"
6/rand(6);$><<"I survived!"

あります SOのルビーには乱数に関する質問ます。シードsrandは、まだ呼び出されていない場合は、現在の時刻からシードとともに自動的に呼び出されます。(ジュリアンのコメントを参照


Primoは、ゼロ除算に依存しないソリューションに追加のボーナス提供するというアイデアを持ちました。

私の最初の解決策は、 undefined local variable or method ``a' for main:Object (NameError)

p rand(6)<5?"I survived!":a

でさらに短くすることができます6/rand(6)
ウゴレン

RubyはRNGを自動的にシードしますか?
vsz

制御フローを削除することで、さらに3つの文字をトリミングできます1/rand(6);p "I survived!"
。– histocrat

@ugoren / histocratあなたのヒントをありがとう、私は自分の解決策を採用しました。
knut

あなたのための別のバイト:なし、ホワイトスペースが間に必要とされないp"I survived!"。私のカウントでは、それはわずか24バイトです。
プリモ

6

Dyalog APL- 25 22 21 20文字

'I Survived!'⊣1÷6⊤?6

プリントDOMAIN ERRORゼロによる除算に起因する誤差として、。

私が思いついたゼロ解による最短の非除算は23文字です。

('I Survived!'1)[~6⍷?6]

投げる INDEX ERROR

ここで試してみてください

APLフォントはこちら


私はそれを受け入れたいのですが、うまくいかないようです。何度か「I survived」を印刷しますDOMAIN ERRORが、一度印刷すると、それだけを印刷し続けます。サイトを完全にリロードしても、二度と生き残ることはありません。
-vsz

@vszなんて奇妙なの...それは私のDyalog APL WSで機能します。インタープリターでも動作しますが、ウェブサイトでは動作しません。これが役立つ場合:dl.dropbox.com/u/9086539/apl.png-MrZander
1

1
1÷0DOMAIN ERRORDyalogにありますが、ngn / aplではです。結果?6は1..6の場合⎕IO←1(Dyalogのデフォルト)および0..5の場合⎕IO←0(ngn / aplのオプションのみ)です。Dyalogでは、を設定することでPRNGをシードできます⎕RL。最初は、事前に決められたデフォルト値があります。を設定⎕RL←0すると、OSによってPRNGがかなり予測不能に再シードされます。TryAPL Dyalogを使用しており、?機能をサポートしています
ngn 14

1
何かが変更された可能性は十分にあります。TryAPLの背後にあるソフトウェアを時々更新したり、Webサイトの機能を試したりしています。提携していますか?私があなたに言ったら、私はあなたを殺さなければなりません...まあ、1÷6の確率で:)
ngn 14

1
ちなみに、ここに18文字の解決策があります。「私は生き残った!」⊣÷⍟?6
ngn

5

Python、96

from ctypes import*
from random import*
randrange(5)or pointer(c_int())[9**9]
print'I survived!'

randrange(5)0を返した場合、セグメンテーションフォールトによりpythonがクラッシュします。


5

vba、27

?1/int(6*rnd),"I Survived!"

イミディエイトウィンドウで使用されます。
失敗すると、次を示すエラーウィンドウが
division by zero
表示されます。


!テキストにありません。
-steenslag

@steenslag、修正済み
SeanC

@SeanCheshire あなたの答えに代わるものを提供しまし
ガフィ

5

Befunge-48文字

 v >91+"!devi"v
/?>?<v"I surv"<
 / / :
   :,_@#

Befungeの唯一のランダム性は?演算子であり、4つの1/4可能な方向(チャンス)の1つに見出しを送ります。一つまたは二つの方向を遮断することによって、あなたが持っている1/3か、1/2偶然、およびこれらを組み合わせることにより、あなたが得ます1/6プログラム「生きている」から抜け出すチャンスを。

ゼロ除算を実行すると、プログラムがクラッシュします。私はそれが実装固有のものになると思います(ウィキペディアでは、プログラムは望ましい答えを尋ねるべきだと言っています)が、befungee.pyはクラッシュするか、怒って終了します:

$ for i in {1..6} ; do ./befungee.py roulette.befunge ; done
Error (1,2): integer division or modulo by zero
Error (3,2): integer division or modulo by zero
Error (1,2): integer division or modulo by zero
I survived!
Error (0,1): integer division or modulo by zero
I survived!

5

J、18

'I survived!'[q:?6

domain error0を因数分解しようとすると失敗します。


JはそのRNGを自動的にシードしますか?
vsz

@vszはい、で??.固定シードに使用できます。
ランダラ

4

C、67 65 62文字

rand()%8公平性を失わない。部門のクラッシュt=0、1と2でtrue(再試行)、3..7(生存)でfalseになります。
編集:以前のバージョンでは一時変数を使用していましたが、これは完全に不要になりました。2/(rand()%8)必要な両方の条件を実装します。

main(){
        for(srand(time(0));2/(rand()%8););
        puts("I survived!");
}

します。「他の出力は許可されていません」
-vsz

@vsz、どういうわけかそれを見逃した。とにかく、gcc / Linuxでは何も出力しません。また、標準に厳密に準拠しているため、この要件は不可能です。未定義の動作が何かを出力する可能性があるためです。
-ugoren

@vsz、現在修正済み-いかなる場合でも余分な出力はありません。最適化でも機能し、2文字短くなります。
ウゴレン

4

T-SQL 56 44 40 + 6

 if 1/cast(ceiling(rand()*6)-1as int)<2print'I Survived!'

キャストを不必要に呼び出すことに対するクレジットSean Cheshire

 if 1/ceiling(rand()*6-1)<2print'I Survived!'

天井を床に変える提案をしてくれたショーン・チェシャーからの個人的なメッセージを信用してください。

 if 1/floor(rand()*6)<1print'I Survived!'

Death Err Msg:メッセージ8134、レベル16、状態1、行3ゼロエラーによる除算が発生しました。


1
-1そしてceiling必要ありません。cast切り捨てられます
SeanC

均一な分布の要件に違反することなく天井を削除できるかどうかをテストしています。ドキュメントでは、rand()はfloat値0〜1を返すと述べています。
freewary

最初のエントリから天井を削除できるかどうかを知りたかった。rand()関数が1を返すかどうかをT-SQLドキュメントから判断できませんでした。そのため、rand()関数をテストして約5,000万回ループを実行しましたが、1を返すことは一度もありませんでした。天井を保ち、ギプスを取り除きます。
-freewary

このスクリプトを20回以上テストしたことはないでしょう。これは常に期待される結果を常に返すとは限りません。6分の1は失敗し、出力を返しません。この構文は機能します:0 / floor(rand()* 6)= 0
t-clausen.dk

3

Javascript、42

(Math.random()*6|0)?alert('i survived!'):b

乗算の結果をビット単位またはフロア化するため、0〜5の値が得られます。0は暗黙的にfalseにキャストされるため、6つのケースのうち5つでは、特定のケースbが参照される6番目のケースでアラートが表示され、プロセスがクラッシュします。


3

通常のゼロ除算方法の使用:

Perl 5.8バージョン

1/(int rand 6)&&print "I survived!"

Perl 5.10バージョン

1/(int rand 6)&&say "I survived!"

失敗すると、これらが表示されます:

Illegal division by zero at -e line 1.

perlでオブジェクトを作成するために使用されるbless関数を使用します。

Perl 5.8バージョン

print (int rand 6?"I survived!":bless me);

Perl 5.10バージョン

say (int rand 6?"I survived!":bless me);

失敗すると、これらが表示されます:

Can't bless non-reference value at -e line 1.

3
いくつかの提案:括弧、論理的な&&、余分なスペースを取り除きます。~~代わりにintを使用して、積分値を強制します。結果は次のとおりです1/~~rand 6;print"I survived!"
。– ardnew

3

GolfScript、21文字

,6rand/;'I survived!'

ほとんどの回答と同様に、これにはZeroDivisionErrorでクラッシュする確率が6分の1あります。ゼロによる除算使用せずに管理できる最短のソリューションは23文字です。

5,6rand=+;'I survived!'

でクラッシュする確率は1/6 undefined method `+' for nil:NilClass (NoMethodError)です。

(Ps。これを開発しているときに、GolfScriptインタープリターのバグの可能性を発見しました:コードのようなコードはスタックに値0,1>を残しているように見えnilます。それを捨てる;私もこのバグを悪用すると、私は23文字未満に得るのを助けるしませんでしたクラッシュの手段をトリガするために何らかの形で値を使用する必要が行うこと。残念ながら、実際に。)


それは間違いなくバグのようです。5,5>[]、それが何をすべきか、おそらくですが、スタック、上の4,5>nil。削除しないと、インタープリターは実際に出力しようとしてクラッシュします。興味深い副作用は4,6rand>+;'I survived!'、有効なソリューションになることです。誰かがおそらくFlagitiousに通知すべきです。
プリモ

1
これを報告しましたが、最新バージョンのGolfScriptインタープリターで(偶然見つけた別のバグとともに)修正されました。
イルマリカロネン

3

Python、70文字

grcの答えからインスピレーションを得て。

from random import*
if randrange(5)<1:exec'()'*9**5
print'I survived!'

randrange(5) returns a value between 0 and 5.
If it returns a 0, Python crashes while attempting to exec(ute) a string of code that contains 9^5 sets of parentheses.


3

PHP - 30 bytes

<?rand(0,5)?:~[]?>I survived!

Requires PHP 5.4+ for the short array syntax, invalid operator idea shamelessly stolen from @primo.

As stated, rand() is automatically seeded on first use.


Division by zero does not halt, it only produces a warning, as well as the text 'I survived!'. Also, rand()%6 is not a uniform distribution, as 32768 = 2 (mod 6). However, rand(0,5)||~$a for 30 bytes is, and will additionally work with all PHP versions (the second expression in a ternary is only optional in 5.3.0+).
primo

@primo Guess I was only looking for the stack trace when I was checking the divide by zero one, didn't notice it still printed. I know the ternary shorthand is 5.3+, but I really have no interest in supporting long out of date versions :)
Leigh

That I agree with. There's no valid argument for continuing to use less than 5.3 at this point. 5.4, I'm still holding out for a double-digit revision number.
primo

1
I count 29 bytes.
Titus

3

Befunge, 38

v>25*"!devivrus I",,,,,,,,,,,@
?^
v
?^
<1

Pretty straight-forward. Crashing is done by pushing 1s onto the stack until it overflows. I made a few attempts at cutting out those 11 commas and replacing them with some more efficient loop to print everything, but couldn't get it under 11 characters.

Note that counting characters in Befunge is a little tricky... For instance there's only one character on the third line, but I'm counting an extra one there since execution could travel through that location.


I believe that's the record for the most consecutive commas I've ever seen in a program.
Joe Z.

And then I look up how Befunge actually works and palm my face.
Joe Z.

2

CMD Shell (Win XP or later), 40 +6

I'm only doing this one because DOS is not something that should even be thought of for code golf, and the whitespace is important

set/a1/(%RANDOM% %% 6)&&echo I Survived!

On failure, it will print

Divide by zero error.


2

R, 50 44 42 36

ifelse(!is.na(sample(c(NA,1:5),1)),'I Survived!',)

ifelse(floor(runif(1,0,5))>0,'I Survived!',)

ifelse(floor(runif(1,0,5)),'I Survived!',)

ifelse(sample(0:5,1),'I Survived!',)

Death Err Message:

Error in ifelse(!is.na(1/sample(c(NA, 1:5), 1)), "I Survived!", ) : argument "no" is missing, with no default


I tried R, and couldn't get it to fail - if(1/0)"I Survived!" still printed I Survived
SeanC

Unlike other languages, R doesn't consider 1/0 to be a math error and doesn't stop execution, it just returns inf for 1/0. I think @vsz wants a breaking error for this round. But supposing vsz counted NA as the death error, I could get my program down to 41 characters: ifelse(sample(c(NA,1:5),1),'I Survived',)
freewary

2

Emacs-Lisp, 42 characters

(if (= (random 6) 5) 
    z (message "I survived!")
    )

2

Javascript, 40 chars

In Javascript the divide-by-zero trick doesn't even work: it just returns Infinity. Therefore, referencing a non-existing variable:

alert(6*Math.random()|0?"I survived!":f)

Not so short, though fun :)



2

TI-BASIC (TI-84+/SE), 36 bytes

startTmr→rand:1/(1<randInt(1,6:"I survived!

There is no input, as the challenge specifies.
Output is I survived! if successful, a DIVIDE BY 0 error otherwise.

The DIVIDE BY 0 error screen looks like the following:

ERR:DIVIDE BY 0
1:Quit
2:Goto

Selecting either option (and returning to home screen if 2 is selected) shows Error after the program call.

Examples:

prgmCDGFE
           Error
prgmCDGFE
I survived!
prgmCDGFE
I survived!
prgmCDGFE
           Error

Explanation:

startTmr→rand:1/(1<randInt(1,6:"I survived!   ;full program

startTmr→rand                                 ;store the current time into "rand"
                                              ; this is necessary because "rand" is 0 after
                                              ; factory reset, the default state for TI-BASIC
                                              ; submissions
                   randInt(1,6                ;get a random integer in [1,6]
                 1<                           ;is greater than 1?  1 if true, 0 if false
              1/(                             ;divide 1 by the result
                                              ; throws "DIVIDE BY 0" error if result was
                                              ; false
                               "I survived!   ;leave this string in "Ans"
                                              ;implicitly print "Ans"

Notes:

  • TI-BASIC is a tokenized language. Byte count does not equal character count.

  • Lowercase letters are two bytes each.

    • Lowercase letters can be enabled using this assembly program.
  • startTmr is a command only on the TI-84+ and TI-84+ SE calculators. Said calculators have different operating systems.


2

Python, 53 bytes

Here's a short 53 byte python index out of range program:

import time
[0][time.time()%6<1]
print("I survived!")

Hi and welcome. Please note that in the rules for this challenge, it states "MOD 6 will not be sufficient." Although I'm not familiar with Python, it looks to me like you are using Modulo here.
Shaun Bebbers

1
@ShaunBebbers The quote is "This means an uninitialized variable (or a RNG without seed) MOD 6 will not be sufficient," but this meta post says that current time modulo is enough for a PRNG for code-golf
Stephen

My misunderstanding then.
Shaun Bebbers

1

Java, 149

public class R{public static void main(String[]s){int[]a={1,1,1,1,1};System.out.println(a[new java.util.Random().nextInt(7)]>0?"I survived!":"");}}

Fails with an "Array out of bounds" error. Managed to shave a few characters by using anonymous Random object (no imports).


1

Groovy, 39

1/new Random().next(6);print"I survived!"

Picks a random number between 0 and 5 inclusive. If 0, throws a divide by zero exception.


1

Python (56), Haskell (77)

This crashes with an IndexError when the generated number is 1:

from random import*
print['I survived!'][1/randint(1,7)]

The Haskell solution has the same idea:

import System.Random
main=putStrLn.(["I survived!"]!!).div 1=<<randomRIO(1,6)

1

Python, 59 55 53, 65 59 56

import os
1/(ord(os.urandom(1))%6)
print"I survived!"

ZeroDivisionError when ord(os.urandom(1))%6 evaluates to 0

import os
print(["I survived!"]*5)[ord(os.urandom(1))%6]

IndexError when ord(os.urandom(1))%6 evaluates to 5


Save 5 characters by changing the import: import random as r then use r.randint
Steven Rumbalski

1
Or save 8 characters by changing import to import os, then use ord(os.urandom(1))%6 as your random int.
Steven Rumbalski

Save 1 character by removing the space after print.
Steven Rumbalski

1

VBA - 39/46

I don't love Sean Cheshire's numeric output (though still a good answer, it technically fails the No input, and no other outputs are allowed. from the spec...), plus he uses /0, so here are my alternatives:

?Mid("I Survived!",IIf(Int(6*Rnd),1,0))

This resolves to a Run-time error '5': Invalid procedure when trying to reach character 0 (VBA is 1-based indexing).

n="I Survived!":If Int(6*Rnd) Then ?n Else ?-n

This resolves to a Run-time error '13': Type mismatch when applying a negative switch to a string.


1

Japt v1.4.5, 16 bytes

6ö
ªí
`I s¨viv!

Try it

-1 byte thanks to @Shaggy!

Throws TypeError: U.í is not a function when a random number in the range [0,6) is 0.



Actually, it might be an idea to use v1.4.5 for this, just in case ETH adds an N.í() method to v1.4.6.
Shaggy

Updated - Japt tries hard not to crash on weird programs. I was trying to figure out how to reference a variable that didn't exist (A-Z is defined), but didn't consider calling a method that didn't exist.
dana

Yeah, N.í() is my "go to" for throwing an error (it used to be N.y()). There are a few other ways of getting an error but they're rarely useful.
Shaggy

Now, why didn't I think of using a 3rd line?! :\
Shaggy
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.