Rus ruleti


28

Rus Ruleti çalan bir program yaz!

Program başlatılırsa,

  • "Hayatta kaldım!" yazdıktan sonra normal olarak bitme şansının 5 olması gerekir.
  • Programın çökme ihtimalinin 1 / 6'sı olmalıdır. (bölümlendirme hatası vb.)

Giriş yok ve başka çıkış yok.

Rasgelelik adil olmalı: düzgün bir olasılık dağılımına sahip olmalıdır. Bu, başlatılmamış bir değişken (veya tohumsuz bir RNG) MOD 6'nın yeterli olmayacağı anlamına gelir.

Çözüm yalnızca bir işletim sistemi / platformu ile çalışırsa, puana 6 baytlık bir ceza verilir.

En kısa kod kazanır, ilk geçerli cevaptan 10 gün sonra değil.


1
Dokümantasyonda açıkça garanti edilmese bile, temel çalışma zamanının adil olmasına güvenebilir miyiz? Örneğin Python's randrange(5)olarak uygulanabilir randrange(MAX_INT)%6.
ugoren

Yaratıcılık ilham için, bu çözümlere bir prim verilmesi düşünebilirsiniz yok sıfıra bölme güvenmektedir.
primo

Belki de bahsi geçen bonus, puanı 2'ye bölmeyi içermelidir.
Joe Z.

1
@JoeZeng: Bu çok fazla olurdu. Genellikle, sadece birkaç karakterin maliyeti için boş gösterici başvurusu vb. Gibi farklı bir hata yapabilirsiniz.
vsz

Anlıyorum. Kod golf bulmacaları için puanlama koşulları oluşturma konusunda fazla tecrübeli değilim, bu yüzden hala böyle şeyler öğreniyorum.
Joe Z.

Yanıtlar:


4

05AB1E , 13 12 bayt

6LΩiFë“IЖd!

@Emigna sayesinde -1 bayt .

05AB1E aslında hiç hata yapamamalı, ancak 05AB1E'nin yeni sürümünün eski sürüme kıyasla hala bazı sorunları olduğundan, bu zorluğun üstesinden gelmek için bunu avantajım için kullanabilirim.

Çevrimiçi deneyin.

Açıklama:

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)

Bunun neden “IЖd!olduğunu anlamak için bu 05AB1E ipucumun (bkz . Sözlük nasıl kullanılır? )"I survived!" .


Görünüşe 5ÝΩz“IЖd!göre çalışması gerekir gibi görünüyor 1 / 0 = 0.
Magic Octopus Urn

1
@MagicOctopusUrn Evet, 05AB1E neredeyse hiç hata yapmaz .. .005AB1E'nin eski bir sürümünde STDERR'ye 0 hatayla bölme yapan eski güzel yapı dışında, eski 05AB1E'de nasıl hata yapılacağını bile bilmiyorum . Yeni sürümde hala oldukça fazla hata var, ancak buradaki fırsatımı değerlendirdi. ;)
Kevin Cruijssen

1
Eskiyi özlüyorum, .0birden fazla kez birisinin “Wat ... Neden bu bir emir?” Oldu.
Magic Octopus Urn

11

PHP 38 bayt

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

+Sayısal olmayan bir dizgeden önce bir harf yerleştirmek değerlendirilir 0. Meli rand(0,5)dönmek 5, $s[rand(0,5)](çünkü boş dize olacaktır $ssadece beş karakter uzunluğunda) ve daha sonra $$s[rand(0,5)]başlatılmamış değişken olacaktır. Tersine çevirmeye çalışmak Desteklenmeyen Operand Türü'nde durur. Başka bir değer, 0-4geri döner sve çünkü$s tanımlandığı için hayatta kalırsınız.

Not: 4.2.0 php sürümünden itibaren, rasgele sayı üreteci otomatik olarak ekilir .


6

R 30

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

Altıda bir kez hata yapar. Error: object 'Z' not found


6

Ruby, 24-28

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

Yaklaşık her 6 kez, bir ZeroDivisionError

24 karakterden daha kısa bir sürümü bile var (ugoren ve histokrat sayesinde):

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

"Çıktıdaki girişi kabul etmiyorsanız , 3 karaktere daha ihtiyacım var. İlk seçenek ( puts) yeni bir satır ekliyor, ikinci seçenek ( ) yeni satır eklemiyor $><<:

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

SO'da yakutta rastgele sayılarla ilgili bir soru var . Daha önce aranmamışsa srand, tohum geçerli zamandan itibaren olan tohum ile otomatik olarak çağrılır. ( Julians yorumuna bakınız )


Primo, sıfıra bölme güvenmeyen bu çözümlere fazladan bir bonus kazandıracaktı. .

İlk çözümüm bir kısaltma ile (28 karakter) kısaltılabilir. undefined local variable or method ``a' for main:Object (NameError)

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

İle daha da kısa olabilir 6/rand(6).
ugoren

Ruby otomatik olarak RNG'sini tohumlar mı?
vsz

Kontrol akışını kaldırarak üç karakter daha kırpabilirsiniz:1/rand(6);p "I survived!"
histocrat

@ugoren / histocrat İpuçlarınız için teşekkürler, çözümümü uyarladım.
23'de

Sizin için başka bir bayt: pve arasında boşluk olması gerekmez "I survived!". Benim sayıma göre, bu sadece 24 bayt.
primo

6

Dyalog APL - 25 22 21 20 Karakterler

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

DOMAIN ERRORSıfıra bölme nedeniyle hata olarak yazdırır .

Bulabildiğim en kısa sıfır olmayan çözüm yolu ile 23 karakter.

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

Bir atar INDEX ERROR

Burada dene

APL Yazı tipi burada


Kabul etmek isterdim ama işe yaramadı. Birkaç kez " I survived" yazdırıyor , ancak bir DOMAIN ERRORkez yazdırdıktan sonra, yalnızca bunu yazdırıyor. Siteyi tamamen yeniden doldursam bile, bir daha asla hayatta kalmayacak.
vsz

@vsz Ne kadar garip ... Dyalog APL WS cihazımda çalışıyor ve işim bittiğinde TryAPL ile test ettiğimi hatırlıyorum. Hala tercümanım üzerinde çalışıyor fakat web sitesinde çalışmıyor. Bu yardımcı olursa: dl.dropbox.com/u/9086539/apl.png
MrZander

1
1÷0Bir olan DOMAIN ERRORDyalog ama bu kadar ngn / apl içinde . Dan sonuç ?61..6 olduğunda ⎕IO←1(Dyalog varsayılan) ve 0..5 ⎕IO←0(ngn / apl içinde tek seçenek). Dyalog'da PRNG, ayarlayarak ekilebilir ⎕RL. Başlangıçta önceden belirlenmiş bir varsayılan değere sahiptir. Ayarladıysanız ⎕RL←0, PRNG, işletim sistemi tarafından oldukça öngörülemeyen bir şekilde yeniden ekilir. TryAPL edilir Dyalog kullanarak ve destekliyor ?işlevi .
ngn

1
O zamanlar bir şeylerin değişmesi oldukça muhtemel, ara sıra TryAPL'in arkasındaki yazılımı güncelliyoruz veya web sitesinin özelliklerini deniyoruz. Bağlı mıyım?
Söylersem

1
Bu arada, işte 18 karakterlik bir çözüm: 'Hayatta kaldım!' ⊣ ÷ ⍟? 6
ngn

5

Python, 96

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

Eğer randrange(5)getiri 0 ise, piton parçalama arızası nedeniyle kilitlenmesine.


5

vba, 27

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

acil pencerede kullanılır.
Hata durumunda: belirten bir hata penceresi:
division by zero
belirir


!Metinde eksik .
steenslag

@steenslag, düzeltildi
SeanC

@SeanCheshire Yanıtınıza bir alternatif önerdim .
Gaffi

5

Befunge - 48 karakter

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

Befunge'nin tek rastgeleliği, ?sizi dört olası yönden birine ( 1/4şans) yönlendiren operatördür . Bir veya iki yönü bloke ederek, şansınız 1/3ya da 1/2şansınız var ve bunları birleştirerek 1/6, programdan "canlı" çıkma şansına sahip olacaksınız .

Program bir sıfıra bölünerek çöküyor. Ben, ancak (o programın istenilen cevap için sormalısınız diyor Wikipedia'da) ne olacağını 's gerçeklenime özel tahmin befungee.py sıralama öfkeyle çöker veya çıkışların:

$ 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'ı çarpanlara ayırmaya çalışırken başarısız olmak .


J, RNG'sini otomatik olarak tohumlar mı?
vsz

@vsz Evet, ile ?. ?.Sabit tohum için kullanabilirsiniz .
randomra

4

C, 67 65 62 karakter

rand()%8adalet kaybetmez. Bölünme için çöküyor t=0, 1 ve 2 için doğru veriyor (yeniden dene), 3.7 için yanlış veriyor (hayatta kalmış).
EDIT: Önceki sürüm tamamen gereksiz bir şekilde sona eren geçici bir değişken kullandı. 2/(rand()%8)Hem gerekli koşulları uygular.

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

Öyle. "başka çıktı yok"
vsz

@vsz, bir şekilde kaçırdı. Ama yine de, gcc / Linux ile hiçbir şey yazdırmıyor. Ayrıca, kesinlikle standarda bağlı kalarak, bu gereksinim de imkansızdır, çünkü tanımsız davranış her şeyi basabilir.
ugoren

@vsz, şimdi düzeltildi - hiçbir durumda ekstra çıkış yok. Ayrıca optimizasyon ile çalışır ve 2 karakter daha kısadır.
ugoren

4

T-SQL 56 44 40 + 6

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

Sean Cheshire'ı gereksiz yere oyuncu olarak çağırdığı için teşekkür ederiz.

 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.


1
-1 and ceiling are not needed. cast will truncate
SeanC

Tek tip dağıtım gereksinimini ihlal etmeden tavanın kaldırılıp kaldırılamayacağını test ediyorum, doktorlar rand () 'nin 0' dan 1 '
lik

Tavanın ilk girişten kaldırılıp kaldırılamayacağını bilmek istedim. Rand () işlevinin 1 döndürüp döndürmeyeceğini T-SQL belgelerinden belirleyemedim. Bu yüzden rand () işlevini test eden yaklaşık 50 milyon kez bir döngü yaptım, bir kez hiç 1 döndürmedi. Ancak, ilk girişimden tavanı kaldırmak 47 bayt olurdu, bu yüzden ikinci girişim hala daha kısa. Tavana tutun ve alçıyı çıkarın.
özgür

Bu betiği 20 defadan fazla test ettiğinizden şüpheliyim. Bu her zaman beklenen sonucu her zaman döndürmez. 6'da 1, başarısız olur ve bir çıktı döndürmez. Bu sözdizimi çalışacak: 0 / floor (rand () * 6) = 0
t-clausen.dk

3

Javascript, 42

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

Bitsel olarak veya çarpımın sonucunu kaplar, böylece 0 ile 5 arasında bir değer elde edilir. 0 dolaylı olarak yanlış duruma getirilir, bu nedenle 6 vakanın 5'inde uyarı, 6. örnekte belirli bbir referansa başvurulur ve işlemi düzeltir .


3

Normal bölmeyi sıfır yöntemiyle kullanmak:

Perl 5.8 Sürümü

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

Perl 5.10 Sürümü

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

Arıza durumunda, bunlar gösterecektir:

Illegal division by zero at -e line 1.

Perl'de nesne oluşturmak için kullanılan korusun işlevini kullanma.

Perl 5.8 Sürümü

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

Perl 5.10 Sürümü

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

Arıza durumunda, bunlar gösterecektir:

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

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. Bunu geliştirirken, GolfScript yorumlayıcısında ne hata olabileceğini öğrendim: kod gibi , yığında 0,1>bir nildeğer bırakıyor gibi görünüyor , bu açılır pencere dışındaki bir değer yapmayı denerseniz daha sonra programı çökertecek ve uzakta olan atmak ;. ne yazık ki, aslında ben bile beni 23 karakter altına almak yardımcı olmadı bu hatayı istismar bir çarpışma aracı tetiklemek için bir türlü değerini kullanma ihtiyacı yapmak.)


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.


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
Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.