Russisches Roulette

28

Schreiben Sie ein Programm, das russisches Roulette spielt!

Wenn das Programm gestartet wird,

  • Es sollte eine 5 zu 6 Chance geben, dass es normal endet, nachdem "Ich habe überlebt!" gedruckt wurde.
  • Es sollte eine 1 zu 6 Chance geben, dass das Programm abstürzt. (Segmentierungsfehler usw.)

Keine Eingabe und keine anderen Ausgaben sind zulässig.

Die Zufälligkeit muss fair sein: Sie muss eine gleichmäßige Wahrscheinlichkeitsverteilung haben. Dies bedeutet, dass eine nicht initialisierte Variable (oder ein RNG ohne Startwert) MOD 6 nicht ausreicht.

Wenn die Lösung nur mit einem dedizierten Betriebssystem / einer dedizierten Plattform funktioniert, erhalten Sie eine 6-Byte-Strafe für die Bewertung.

Der kürzeste Code gewinnt, frühestens 10 Tage nach der ersten gültigen Antwort.

vsz
quelle
1
Können wir uns darauf verlassen, dass die zugrunde liegende Laufzeit angemessen ist, auch wenn dies in der Dokumentation nicht ausdrücklich garantiert wird? ZB randrange(5)könnte Python als implementiert werden randrange(MAX_INT)%6.
Ugoren
Um die Kreativität anzuregen, sollten Sie in Betracht ziehen, denjenigen Lösungen einen Bonus zu gewähren, die nicht auf einer Division durch Null beruhen.
Primo
Vielleicht sollte der Bonus das Teilen der Punktzahl durch 2 beinhalten.
Joe Z.
1
@ JoeZeng: das wäre zu viel gewesen. Normalerweise können Sie einen anderen Fehler angeben, z. B. eine Nullzeigerreferenz usw., und das zu einem Preis von nur wenigen Zeichen.
vsz
Aha. Ich habe nicht allzu viel Erfahrung damit, Bedingungen für Codegolf-Rätsel zu schaffen, deshalb lerne ich immer noch solche Dinge.
Joe Z.

Antworten:

4

05AB1E , 13 12 Bytes

6LΩiFë“IЖd!

-1 Byte dank @Emigna .

05AB1E sollte eigentlich überhaupt nicht fehleranfällig sein, aber da die neue Version von 05AB1E im Vergleich zur Vorgängerversion noch einige Probleme aufweist, kann ich das zu meinem Vorteil nutzen, um bei dieser Herausforderung Fehler zu machen.

Probieren Sie es online aus.

Erläuterung:

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)

Sehen Sie diese 05AB1E Spitze von mir (Abschnitt Wie das Wörterbuch benutzen? ) Zu verstehen , warum “IЖd!ist "I survived!".

Kevin Cruijssen
quelle
Scheint 5ÝΩz“IЖd!aber anscheinend so zu funktionieren 1 / 0 = 0.
Magic Octopus Urn
1
@MagicOctopusUrn Ja, 05AB1E fast nie Fehler. Abgesehen von dem hübschen alten Buildin, .0das in einer alten Version von 05AB1E eine Division durch 0-Fehler an STDERR warf, weiß ich nicht einmal, wie man Fehler in der alten 05AB1E macht . Die neue Version hat aber immer noch einige Fehler, die ich hier zu meiner Gelegenheit genutzt habe. ;)
Kevin Cruijssen
1
Ich vermisse das alte .0, bei mehr als einer Gelegenheit brachte es jemanden dazu zu sagen: "Wat ... Warum ist das ein Befehl?"
Magic Octopus Urn
11

PHP 38 Bytes

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

Das Platzieren von +vor einer nicht numerischen Zeichenfolge wird zu ausgewertet 0. Sollte rand(0,5)zurückkehren 5, $s[rand(0,5)]ist dies die leere Zeichenfolge (da sie $snur fünf Zeichen lang ist) und anschließend $$s[rand(0,5)]eine nicht initialisierte Variable. Der Versuch, die Inversion durchzuführen, wird bei nicht unterstütztem Operandentyp angehalten. Jeder andere Wert 0-4wird zurückgegebens und $sSie werden überleben , da er definiert ist.

Hinweis: Ab der PHP-Version 4.2.0 wird der Zufallszahlengenerator automatisch gesetzt .

primo
quelle
6

R 30

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

Einmal von sechs wird ein Fehler ausgegeben: Error: object 'Z' not found

Flodel
quelle
6

Ruby, 24-28

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

Ca. alle 6 mal gibt es eine ZeroDivisionError

Es gibt sogar eine kürzere Version mit 24 Zeichen (Dank an ugoren und histocrat):

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

Wenn Sie das "in der Ausgabe nicht akzeptieren , dann brauche ich noch 3 Zeichen. Die erste Option ( puts) fügt eine neue Zeile hinzu, die zweite ( $><<) macht keine neue Zeile:

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

Es gibt eine Frage zu Zufallszahlen in Ruby bei SO . Der Startwert mit srandwird automatisch mit dem Startwert aus der aktuellen Zeit aufgerufen, wenn er nicht bereits aufgerufen wurde. (siehe Julians Kommentar )


Primo hatte die Idee für einen zusätzlichen Bonus für solche Lösungen zu erhalten, die nicht auf einer Division durch Null beruhen .

Meine erste Lösung kann mit a (28 Zeichen) gekürzt werden undefined local variable or method ``a' for main:Object (NameError)

p rand(6)<5?"I survived!":a
knut
quelle
Kann mit noch kürzer sein 6/rand(6).
Ugoren
Sät Ruby seinen RNG automatisch?
vsz
Sie können weitere drei Zeichen 1/rand(6);p "I survived!"
kürzen,
@ugoren / histocrat Danke für deine Hinweise, ich habe meine Lösung angepasst.
Knut
Ein weiteres Byte für Sie: Zwischen pund ist kein Leerzeichen erforderlich "I survived!". Nach meiner Zählung sind das nur 24 Bytes.
Primo
6

Dyalog APL - 25 22 21 20 Charachters

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

Druckt DOMAIN ERRORaufgrund der Division durch Null als Fehler.

Die kürzeste Lösung, die ich ohne Division durch Null finden konnte, sind 23 Zeichen.

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

Es wirft ein INDEX ERROR

Probieren Sie es hier aus

APL-Schriftart hier

MrZander
quelle
Ich würde es gerne akzeptieren, aber es scheint nicht zu funktionieren. Einige Male wird " I survived" gedruckt, aber nach dem DOMAIN ERROReinmaligen Drucken wird immer nur das gedruckt. Selbst wenn ich die Seite komplett neu lade, wird sie nie wieder überleben.
vsz
@vsz Wie seltsam ... Es funktioniert in meinem Dyalog APL WS und ich erinnere mich, es mit TryAPL getestet zu haben, als ich fertig war. Es funktioniert immer noch mit meinem Dolmetscher, aber nicht mit der Website. Wenn dies hilft: dl.dropbox.com/u/9086539/apl.png
MrZander
1
1÷0 is a DOMAIN ERROR in Dyalog but in ngn/apl it's . The result from ?6 is 1..6 when ⎕IO←1 (default in Dyalog) and 0..5 when ⎕IO←0 (only option in ngn/apl). In Dyalog, the PRNG can be seeded by setting ⎕RL. Initially it has some pre-determined default value. If you set ⎕RL←0, the PRNG is re-seeded fairly unpredictably by the OS. TryAPL is using Dyalog and does support the ? function.
ngn
1
It's quite possible that something was changed back then, we are occasionally updating the software behind TryAPL or experimenting with features of the website. Am I affiliated? If I tell you, I'll have to kill you... well, with a probability of 1÷6 :)
ngn
1
By the way, here's an 18-character solution: 'I survived!'⊣÷⍟?6
ngn
5

Python, 96

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

If randrange(5) returns 0, then python will crash due to a segmentation fault.

grc
quelle
5

vba, 27

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

used in immediate window.
On failure, an error window stating:
division by zero
appears

SeanC
quelle
Missing the ! in the text.
steenslag
@steenslag , fixed
SeanC
@SeanCheshire I've offered an alternative to your answer.
Gaffi
5

Befunge - 48 chars

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

Befunge's only randomness is the ? operator, which sends you heading in one of four posible directions (1/4 chance). By blocking one or two directions, you have 1/3 or 1/2 chance, and by combining these, you get 1/6 chance to get out of the program "alive".

The program crashes by doing a divive-by-zero. I guess it's implementation-specific what will happen (on Wikipedia it says the program should ask for the desired answer), but befungee.py sort of crashes, or exits angrily:

$ 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!
daniero
quelle
5

J, 18

'I survived!'[q:?6

Failing with domain error when trying to factorise 0.

randomra
quelle
Does J seed its RNG automatically?
vsz
@vsz Yes, with ?. You can use ?. for fixed seed.
randomra
4

C, 67 65 62 chars

rand()%8 doesn't lose fairness. Division crashes for t=0, gives true for 1 and 2 (retry), gives false for 3..7 (survived).
EDIT: The previous version used a temporary variable, which ended up completely unneeded. 2/(rand()%8) implements both needed conditions.

main(){
        for(srand(time(0));2/(rand()%8););
        puts("I survived!");
}
ugoren
quelle
It does. "no other outputs are allowed"
vsz
@vsz, somehow missed it. But anyway, with gcc/Linux it doesn't print anything. Also, strictly adhering to the standard, this requirement is impossible, because undefined behavior might print anything.
ugoren
@vsz, fixed now - no extra output in any case. Also works with optimization, and 2 characters shorter.
ugoren
4

T-SQL 56 44 40 + 6

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

Credit Sean Cheshire for calling out cast as unnecessary

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

Credit personal message from Sean Cheshire for suggestion to change ceiling to floor.

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

Death Err Msg: Msg 8134, Level 16, State 1, Line 3 Divide by zero error encountered.

freewary
quelle
1
-1 and ceiling are not needed. cast will truncate
SeanC
I'm testing if ceiling can be removed without violating the requirement for uniform distribution, the docs say that rand() returns float values 0 through 1.
freewary
I wanted to know if ceiling could be removed from my first entry. I was unable to determine from T-SQL documentation if the rand() function would ever return a 1 or not. So I ran a loop about 50 million times testing the rand() function, never once did it return a 1. But, removing ceiling from my first entry would still be 47 bytes, so my second entry is still shorter. Keep ceiling and remove cast.
freewary
I doubt you have tested this script more than 20 times. This doesn't always return the expected result always. 1 in 6 this will fail and not return an output. This syntax will work: 0/floor(rand()*6)=0
t-clausen.dk
3

Javascript, 42

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

The bitwise or floors the result of the multiplication thus a value between 0 and 5 results. 0 gets implictly casted to false, so in 5 of 6 cases the alert appears in the 6th case a certain b is referenced, crashing the process.

zaphod1984
quelle
3

Using the usual divide by zero method:

Perl 5.8 Version

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

Perl 5.10 Version

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

On failure, these will display:

Illegal division by zero at -e line 1.

Using the bless function which is used for creating objects in perl.

Perl 5.8 Version

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

Perl 5.10 Version

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

On failure, these will display:

Can't bless non-reference value at -e line 1.
xxfelixxx
quelle
3
a few suggestions: get rid of parentheses, the logical &&, and the extra space. use ~~ instead of int to force integral values. the result is this: 1/~~rand 6;print"I survived!"
ardnew
3

GolfScript, 21 chars

,6rand/;'I survived!'

Like most of the answers, this one has a one in six chance of crashing with a ZeroDivisionError. The shortest solution I could manage without using division by zero is 23 chars:

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

which has a 1/6 chance of crashing with undefined method `+' for nil:NilClass (NoMethodError).

(Ps. While developing this, I found what might be a bug in the GolfScript interpreter: code like 0,1> appears to leave a nil value on the stack, which will later crash the program if you try to do anything with that value except pop it off and throw it away with ;. Unfortunately, the fact that I do need to use the value somehow to trigger a crash means that even exploiting this bug didn't help me get below 23 chars.)

Ilmari Karonen
quelle
That definitely seems like a bug. 5,5> leaves [] on the stack, which is probably what it should do, but 4,5> leaves nil. If you don't remove it, the interpreter will actually crash while trying to output it. An interesting side-effect is that 4,6rand>+;'I survived!' becomes a valid solution. Someone should probably inform Flagitious.
primo
1
I reported this, and it has been fixed (along with another bug I stumbled across) in the latest version of the GolfScript interpreter.
Ilmari Karonen
3

Python, 70 characters

With inspiration from grc's answer.

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.

Joshua Sleeper
quelle
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.

Leigh
quelle
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.

Joe K
quelle
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.

SeanC
quelle
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

freewary
quelle
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!")
    )
dualinity
quelle
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 :)

tomsmeding
quelle
2

PowerShell, 40 Chars

IF(6/(Get-Random -Max 6)){'I Survived!'}

On Failure: "Attempted to divide by zero."

DBADon
quelle
Welcome to PPCG!
Laikoni
1
32 bytes
mazzy
31 bytes
Veskah
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.

Tau
quelle
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!")
Alexander Wahlsten
quelle
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).

Noah
quelle
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.

Will Lp
quelle
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)
Lambda Fairy
quelle
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

Raufio
quelle
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.

Gaffi
quelle
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.

dana
quelle
1
17 bytes
Shaggy
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