랜덤 티켓 코드 생성기


18

복권 회사는 길이가 10자인 임의의 복권 티켓 번호를 생성하려고합니다.

모든 숫자가 한 번만 나오는 숫자를 만들려면 모든 언어로 코드를 작성하십시오. 예를 들어이 숫자 9354716208에서 0에서 9까지의 모든 정수는 한 번만 나타납니다. 이 숫자는 임의의 숫자 여야합니다.

  • 생성 된 번호가 화면에 표시되어야합니다.
  • 허용되는 모든 문자의 모든 순열을 생성 할 수 있어야합니다.
  • 코드는 가능한 한 작아야합니다 (바이트).

3
왜 Java 또는 PhP 여야합니까?
Fabinout

4
일반적으로 코드 골프 설명 에 따라 모든 언어를 허용하는 것이 좋습니다 .
Konrad Borowski

10
@Howard 와 같은 사람들이 5 ~ 8 문자 답변을 할 때 문자 수조차없이 가장 길고 골프가 적은 답변 (SQL 답변) 중 하나가 코드 골프 에서 허용되는 답변으로 어떻게 작용합니까?
Darren Stone

1
예, @marinus에는 4 바이트 솔루션이 있습니다 (광산은 6 바이트)
Timtech

4
-1 이것이 코드 골프 도전이라는 점을 감안할 때 당첨자 선정이 부적절합니다.
DavidC

답변:


41

J (4 바이트)

저항 할 수 없었습니다.

?~10

J에서 Fdyadic 인 F~ x경우와 같습니다 x F x.


3
+1 나는 이것을 이기기 위해 파이썬보다 약간 더 간결한 것을 시도해야 할 수도 있다고 생각한다.
Joachim Isaksson

이것은 0으로 시작하는 암호를 허용합니까? 규칙에 따르면, 프로그램은 "허용 가능한 모든 문자의 모든 순열을 생성 할 수 있어야합니다"
DavidC

@DavidCarraher : 예. 구간에서 반복되지 않는 난수 10 개를 선택 [0..10)하므로 기본적으로 '0123456789'의 임의 순열을 의미합니다.
marinus

1
내가 참조. 대부분의 언어에서 "숫자"(0123456789)가 123456789 형식으로 자동 편집되므로 문자열 "0123456789"는 그대로 유지됩니다. 그래서 내 질문은 실제로 이것입니다 : 출력은 숫자입니까 아니면 문자열입니까?
DavidC

@DavidCarraher 배열입니다.
swish

12

J, 5 자 및 APL, 8 자

제이

10?10

J에는 기본 제공 거래 연산자 (? )가 있습니다. 따라서 10 (10 10?10) 중 10을 취할 수 있습니다 .

APL

1-⍨10?10

APL에는 불행히도 0 대신 1로 시작하는 동일한 연산자가 있습니다. 따라서 우리는 각 숫자에서 하나를 빼고 있습니다 ( 통근 연산자로 인해 1-⍨X의미 X-1합니다).


오, 그거 좋네요
Konrad Borowski

OP가 배열이 아닌 숫자를 구체적으로 요청했을 경우, 다음을 사용하여 base10 숫자로 변환해야합니다.10#.
swish

당신은 ⎕IO←0그것을 뺄 필요 가 없다고 가정 할 수 있습니다 . 또한, J 및 APL 모두를 위해, 당신은으로 바이트를 저장하는 통근을 사용할 수 있습니다 ?~10?⍨10파생 기능의 모나드 응용 프로그램이 왼쪽 인수로 또한 오른쪽 인자를 사용하기 때문이다. 그러나 이것은 J 코드 를 Marinus의 코드와 동일하게 만듭니다 .
Adám

9

파이썬 2.7 ( 64 63 57)

여기에 연산자 무거운 언어와 비교할 확률이 없으며 기본로드 된 임의의 부족으로 인해 :) 이것은 내가 얻을 수있는 가장 짧은 것입니다.

from random import*
print''.join(sample("0123456789",10))

범위를 만들고 교체하지 않고 10 개의 숫자를 샘플링합니다.

(짧은 가져 오기 형식 수정에 대해서는 @xfix와 다소 복잡한 샘플링 범위를 지적하는 데 @blkknght 감사합니다)

파이썬 2.7 (40)

대화식 프롬프트에서 실행하고 쉼표로 구분하여 읽을 수 있으면 40으로 줄일 수 있지만 규칙의 정신을 어기는 것 같습니다.

from random import*
sample(range(10),10)

1
from random import*하나의 문자를 저장 하는 데 사용할 수 있습니다 . 이것은 내 Perl 6 솔루션처럼 보이지만 더 장황하지만 더 자세한 경우에도 이와 같은 것이 Python에서 작동 할 수 있음을 보는 것이 좋습니다.
Konrad Borowski

@xfix 예, 슬프게도 파이썬의 모듈은 비교하기에 약간 장황합니다.) 가져 오기 수정으로 업데이트되었습니다.
Joachim Isaksson

문자열을 "0123456789"사용하여 range매핑 하지 않고 샘플링하여 문자를 몇 개 더 저장할 수 있습니다 str.
Blckknght

@Blckknght 감사합니다, 귀하의 제안으로 업데이트 :)
Joachim Isaksson

8

PHP, 29 자

<?=str_shuffle('0123456789');

PHP에서는 닫기 태그가 필요하지 않습니다. 그러나 규칙에 위배되는 경우 대체 할 수 있습니다. ?> 1 순증가.


이 솔루션으로 나를 이겼습니다.
Shaun Bebbers

8

루비, 18

이것을 다음에서 실행하십시오 irb.

[*0..9].shuffle*''

이것이 출력이있는 독립형 프로그램이 되길 원한다면 stdout(규칙은 이것을 요구 하지 않는 것 같습니다 ) 시작시 다음 4 문자를 추가하십시오.

$><<

당신은 단축 될 수 있습니다 (0..9).to_a[*0..9].
Howard

완료했습니다. 감사!
대런 스톤

천만에요. 그런데 왜 [*0..9].shuffle처음부터 사용하지 않습니까?
Howard

@Howard, 늦어서 바보입니다. :) 감사!
대런 스톤

숫자가 아닌이 리턴 배열

8

PHP-37 자

<?=join('',array_rand(range(0,9),10))

이론적으로 작동 해야하는 18 자 솔루션이 있었지만 PHP는 이상합니다.

또는 xkcd 답변을 원할 경우 :

<?="5398421706" // Chosen by program above; guaranteed to be random ?>

편집 : 감사 xfix, 이제 5 자 짧고 완성되었습니다. 다시 편집 : 라이브 예 .


완전한 부품 대신 완전한 프로그램을 작성하십시오. 또한, echo괄호를 필요로하지 않으며, 경우 echo프로그램의 첫 번째 문은, 당신은 대체 할 수 <?php echo와 함께 <?=. 또한 join의 별칭입니다 implode.
Konrad Borowski

@xfix 감사합니다. 고칠 것입니다. :)
cjfaure

당신도 필요하지 않습니다 <?=?>. 그것들이없는 유효한 PHP 코드입니다.
jeremy

@Jeremy 골프는 숫자가 표시되도록 요구합니다. 또한 echo 길이는 같고 결합 되어 <?=있으며 길이 ?>가 없으면 코드 패드에서 작동하지 않습니다. 그래도 고마워. : P
cjfaure

1
@Jeremy Ah, PHP. 터미널 외에 내장되지 않은 구현은 거의 없습니다. : P
cjfaure

8

펄 6 (18 16 자)

print pick *,^10

이것은 모든 임의의 요소를 포함하는 배열 (생성 pick *부터) 09그 결과를 출력한다 ( print).

샘플 출력 :

$ perl6 -e 'print pick *,^10'
4801537269
$ perl6 -e 'print pick *,^10'
1970384265
$ perl6 -e 'print pick *,^10'
3571684902

+1 전에 공백이 필요하지 않다고 생각합니다 pick.
Howard

1
@Howard : 실제로 필요합니다. [~](Perl 6 문법에 따르면 listop으로 구문 분석 됨) 인수가 포함 된 경우 공백 또는 괄호가 필요합니다. 그렇지 않으면, Perl 6 컴파일러는 "2 개의 용어가 행에 대해"불평합니다. 이전 버전의 Perl 6에서는 필요하지 않았지만 이것은 과거입니다. Perl 6은 여전히 ​​작업 중입니다.
Konrad Borowski

1
@xfix : 사용 print대신 say [~]하고 저장 2 개 문자 :
Ayiko

@Ayiko : 개선 주셔서 감사합니다 :).
Konrad Borowski

7

GolfScript, 12 자

10,{;9rand}$

단순히 자릿수 목록을 생성합니다 (10, ) {...}$을 생성하고 임의의 임의의 키에 따라 정렬하면 임의의 자릿수 순서가 생성됩니다.

예 ( 온라인 시도 ) :

4860972315

0137462985

나는 이것을 게시하려고했다 : P
Doorknob

예를 들어, 첫 번째 숫자는 교체 1보다 0이 될 가능성이 3 배에 관한 것입니다 :하지만 즉, 종류의 쓰레기 셔플의의 9rand99rand겠습니까 (대부분) 수정이; 실제로 완벽9.?rand 할 것 입니다.
Ilmari Karonen

1
@IlmariKaronen 알고 있지만 질문은 균일 분포에 대해 아무 말도하지 않았습니다.
Howard

6

R (23 자)

cat(sample(0:9),sep="")

샘플 출력 :

> cat(sample(0:9),sep="")
3570984216
> cat(sample(0:9),sep="")
3820791654
> cat(sample(0:9),sep="")
0548697132

6

TI-BASIC, 5 바이트

randIntNoRep(1,10

숫자가 아닌 목록을 표시합니다. 찾고 있습니다 randIntNoRep(0,9:.1sum(Ans10^(cumSum(1 or Ans.
lirtosiast 2016 년

2
나는이 도전에 정수형이 필요하다고 생각하지 않으며, "생성 된 숫자가 화면에 표시되어야한다"는 것만 해당합니다.
Timtech

흠, 내가 그랬던 것처럼 문제는 (다수의 요구라고 생각 다른 사람을 하지만 명확히 적이 도전 저자의 의도 보인다 목록 (J와 APL)와 같은 일부 다른 솔루션 출력을 어떤 경우에..
lirtosiast

글쎄, 확실하지 않으면이 방법이 더 짧기 때문에 가정하지 않을 것입니다.
Timtech

5

옥타브 (14)

randperm(10)-1

randperm 불행히도 1..n에서 선택을 생성하므로 0에서 9를 얻으려면 끝에 1을 빼야합니다.


5

SQL Server에서

DECLARE @RandomNo varchar(10)
SET @RandomNo = ''

;WITH num as (
SELECT 0 AS [number]
Union 
select 1
Union 
select 2
Union 
select 3
Union 
select 4
Union 
select 5
Union 
select 6
Union 
select 7
Union 
select 8
Union 
select 9
)
SELECT Top 9 @RandomNo = COALESCE(@RandomNo + '', '') + cast(n.number AS varchar(1))
FROM numbers n
ORDER BY NEWID()

SELECT cast(@RandomNo AS numeric(10,0))

데모보기

또는 재귀와 xml을 사용하는 비슷한 (@manatwork 제공).

with c as(select 0i union all select i+1from c where i<9)select i+0from c order by newid()for xml path('')

1
여러분, CTE를 좋아합니다… 그러나 이것이 코드 골프 과제이므로 가능한 한 짧게하는 것이 좋습니다. 최고는 186 자 select i+0from(select 0i union select 1union select 2union select 3union select 4union select 5union select 6union select 7union select 8union select 9)f order by newid()for xml path('')입니다. (BTW, 훌륭한 트릭입니다 newid().)
manatwork

1
그래, 맞아 CTE가 더 짧습니다. 106 자 : with c as(select 0i union all select i+1from c where i<9)select i+0from c order by newid()for xml path('').
manatwork

당신과 함께 CTE 단순화 할 수 있습니다(VALUES (1),(2),...)
ypercubeᵀᴹ

5

자바 스크립트 ( 79 78 68 자)

숫자 0-9로 배열을 만들고 정렬하는 대신 난수를 생성하기로 결정했습니다. 배열에없는 숫자가 나오면 추가하십시오. 이것은 10 번 반복 된 다음 출력을 경고합니다.

for(a="";!a[9];){~a.indexOf(b=~~(Math.random()*10))||(a+=b)}alert(a)


||단락 평가를 사용하여 다음 if과 같은 대신 1 바이트를 절약 할 수 있습니다 . for(a="";!a[9];){b=Math.floor(Math.random()*10);~a.indexOf(b)||(a+=b)}alert(a)
Steven Palinkas

1
@StevenPalinkas 감사합니다, 좋은 생각입니다! 그에 따라 게시물을 업데이트했습니다.
scribblemaniac

We could also save 2 bytes with a bit of rearrangement in the code: for(a="";!a[9];){~a.indexOf(b=Math.floor(Math.random()*10))||(a+=b)}alert(a)
Steven Palinkas

We can save an additional 8 bytes using the "shorthand" for Math.floor like: for(a="";!a[9];){~a.indexOf(b=~~(Math.random()*10))||(a+=b)}alert(a)
Steven Palinkas


4

Shell/Coreutils, 23

shuf -i0-9|paste -sd ''

If we don't need a trailing newline, you can shave this to 20 with shuf -i0-9|tr -d \\n
joeytwiddle

what about shuf -zi0-9
marcosm

@marcosm: That gives you lines terminated with zeroes, which is slightly strange.
Hasturkun

4

JavaScript, 82 characters

EDIT: Thanks to Rob W, code length is reduced to 90 characters.

EDIT: Thanks to George Reith, code length is reduced to 82 characters (using for loop).

Pretty straightforward way: pick random element of [0,1,2,3,4,5,6,7,8,9] array and append it to the output, then reduce array and replay.

Old version (106 characters):

a=[0,1,2,3,4,5,6,7,8,9],l=11,t="";while(--l){r=Math.floor(Math.random()*l);t+=a[r];a.splice(r,1);}alert(t)

Readable version:

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], l = 10,t = "";
while(l--) {
  r = Math.floor(Math.random() * l);
  t += a[r];
  a.splice(r, 1);
}
alert(t);

Better version (90 characters):

a="0123456789".split(t=""),l=11;while(--l)t+=a[r=0|Math.random()*l],a.splice(r,1);alert(t)

Last version (82 characters):

a="0123456789".split(t='');for(l=11;--l;t+=a.splice(0|Math.random()*l,1));alert(t)

JSFiddle: http://jsfiddle.net/gthacoder/qH3t9/.


1
I golfed down your method to 90 characters: a='0123456789'.split(t=''),l=10;while(l--)t+=a[r=0|Math.random()*l],a.splice(r,1);alert(t). Big savers: Math.random(x) === 0|x. Replace curly braces and semicolons with commas. Directly use the result of an assignment as a value, instead of using an intermediate variable. Finally, initialize the initial array using .split(r=''). This is shorter than creating an array using array literals and assigning the string value in a separate expression.
Rob W

@RobW Thanks for the tips. I updated my answer. P.S. I guess you meant Math.floor(x) === 0|x.
gthacoder

1
This always has 9 at the end. To fix, initialize l=11 and switch your while loop condition to while(--l)
Greg

@Greg Good point. Thank you. I updated the answer.
gthacoder

1
82 Characters: a="0123456789".split(t='');for(l=11;--l;t+=a.splice(0|Math.random()*l,1));alert(t) - Your code fits perfectly into a for loops initialisation, condition and expression arguments. The r variable is redundant.
George Reith

4

C#, 145 bytes

Ungolfed

using System;
using System.Linq;
class P
{
    static void Main()
    {
        Enumerable.Range(0,10).OrderBy(g => Guid.NewGuid()).ToList().ForEach(Console.Write);
    }
}

Golfed

using System;using System.Linq;class P{static void Main(){Enumerable.Range(0,10).OrderBy(g => Guid.NewGuid()).ToList().ForEach(Console.Write);}}

1
You can use Enumerable.Range(0,10), and you don't need the curly brackets in the foreach loop.
Rik

3

JavaScript (80 characters)

alert("0123456789".split("").sort(function(){return .5-Math.random()}).join(""))

JS-Fiddle: http://jsfiddle.net/IQAndreas/3rmza/


3
Note this can be golfed further by using an arrow function (which currently only works in FF, but is coming soon to interpreters everywhere): alert("0123456789".split("").sort(n=>.5-Math.random()).join(""))
apsillers

1
You don't need the space between return and .5
Tibos

1
@Greg Shhhh! Do you have any idea how many characters a real shuffling function takes? ;)
IQAndreas

1
@Greg It is a random distribution (assuming Math.random is sufficiently random), it just isn't a uniform one.
SuperJedi224

1
The original blog post is gone, adding the internet archive for posterity: web.archive.org/web/20150212083701/http://sroucheray.org/blog/…
Greg

3

K/Kona (6)

-10?10

As with J, ? is the deal operator; the - forces the values to not repeat.


3

Mathematica 40

The number is created as a string so as to allow zero to be displayed as the first character, when needed.

""<>RandomSample["0"~CharacterRange~"9"]

Output examples

"0568497231"
"6813029574"

Explanation

"0"~CharacterRange~"9" is infix notation for `CharacterRange["0","9"]". Either of these returns the list, {"0","1","2","3","4","5","6","7","8","9"}.

RandomSample[list] by default returns a permutation of the list. (It can also be used for other kinds of sampling, when parameters are included. E.g. RandomSample[list, 4] will return a Random sample of 4 characters, with no repeats.


But why to display 0 as the first character?
Ankush

According to the OP, the program "must be able to generate all permutations of all allowable characters".
DavidC

@Ankush That's infix notation, so "0" is not always the first char.
Ajasja

Ajasja is correct. The program can generate any permutation. I added some remarks above to clarify this.
DavidC


2

Forth, 72

needs random.fs : r ': '0 do i loop 9 for i 1+ random roll emit next ; r

Room still to golf, maybe, but Forth made this one hard. I think.


2

Prolog, 177/302 characters

I'm a beginner on Prolog, so probably this is not the most condensed code.

:- use_module(library(clpfd)).
sort(N) :-
    N = [N0,N1,N2,N3,N4,N5,N6,N7,N8,N9],
    domain([N0],1,9),
    domain([N1,N2,N3,N4,N5,N6,N7,N8,N9],0,9),
    all_different(N),
    labeling([],N).

Returns:

| ?- sort2(N).                                         
N = [1,0,2,3,4,5,6,7,8,9] ? ;
N = [1,0,2,3,4,5,6,7,9,8] ? ;
N = [1,0,2,3,4,5,6,8,7,9] ? ;
N = [1,0,2,3,4,5,6,8,9,7] ? ;
N = [1,0,2,3,4,5,6,9,7,8] ? 
yes

If you want it to return an integer:

:- use_module(library(clpfd)).
sort(M) :-
    N = [N0,N1,N2,N3,N4,N5,N6,N7,N8,N9],
    domain([N0],1,9),
    domain([N1,N2,N3,N4,N5,N6,N7,N8,N9],0,9),
    all_different(N),
    labeling([],N),
    M is (N0*1000000000)+(N1*100000000)+(N2*10000000)+(N3*1000000)+
         (N4*100000)+(N5*10000)+(N6*1000)+(N7*100)+(N8*10)+N9.

Returns:

| ?- sort(N).
N = 1023456789 ? ;
N = 1023456798 ? ;
N = 1023456879 ? ;
N = 1023456897 ? ;
N = 1023456978 ? 
yes

Using instead:

labeling([down],N)

Gives the numbers in the opposite order:

| ?- sort(N).                                        
N = 9876543210 ? n
N = 9876543201 ? n
N = 9876543120 ? n
N = 9876543102 ? n
N = 9876543021 ? 
yes

Unlike some other codes posted, this returns all possibilities (with no repetitions).


2

q/kdb [6 chars]

-10?10

will generate 10 unique random numbers.



2

Clojure, 42

(println (apply str (shuffle (range 10))))

6209847315


The generated number should be shown on screen, not it's parts.
Sylwester

2

Javascript, 83 characters

a=[];while(!a[9]){b=Math.floor(Math.random()*10);!a.includes(b)&&a.push(b)}alert(a)

While running until array has 10 elements.

Generating random number from 0 - 9 then check if array !includes this number and add it to the array.


1
Welcome to the site! :)
DJMcMayhem

1

This is not much smaller than JMK's answer, but here's a slightly smaller C# solution (135):

using System;
using System.Linq;
class P { 
    static void Main() 
    { 
        Console.Write(string.Join("", "0123456789".OrderBy(g => Guid.NewGuid()))); 
    } 
}

Compacted (134):

using System;using System.Linq;class P{static void Main(){Console.Write(string.Join("", "0123456789".OrderBy(g => Guid.NewGuid())));}}

Alternate version (135):

using System;
using System.Linq;
class P { 
    static void Main() 
    { 
        "0123456789".OrderBy(g => Guid.NewGuid()).ToList().ForEach(Console.Write); 
    } 
}

Compacted:

using System;using System.Linq;class P{static void Main(){"0123456789".OrderBy(g => Guid.NewGuid()).ToList().ForEach(Console.Write);}}

They're equal in length, but it really just depends on whether you want to use Linq's ForEach function or String's Join function. I was able to remove 10 characters in length by spelling out the range "0123456789" in a string instead of using Enumerable.Range(0, 10).


1

LOGO, 64 characters

make "d 1234567890
repeat 10 [
    make "n pick d
    show n
    make "d butmember n d
]

pick returns random item of the supplied list. butmember returns list with all occurrences of the specified item removed. Note: Not all Logo implementations support butmember command.


당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.