복권 회사는 길이가 10자인 임의의 복권 티켓 번호를 생성하려고합니다.
모든 숫자가 한 번만 나오는 숫자를 만들려면 모든 언어로 코드를 작성하십시오. 예를 들어이 숫자 9354716208에서 0에서 9까지의 모든 정수는 한 번만 나타납니다. 이 숫자는 임의의 숫자 여야합니다.
- 생성 된 번호가 화면에 표시되어야합니다.
- 허용되는 모든 문자의 모든 순열을 생성 할 수 있어야합니다.
- 코드는 가능한 한 작아야합니다 (바이트).
복권 회사는 길이가 10자인 임의의 복권 티켓 번호를 생성하려고합니다.
모든 숫자가 한 번만 나오는 숫자를 만들려면 모든 언어로 코드를 작성하십시오. 예를 들어이 숫자 9354716208에서 0에서 9까지의 모든 정수는 한 번만 나타납니다. 이 숫자는 임의의 숫자 여야합니다.
답변:
저항 할 수 없었습니다.
?~10
J에서 Fdyadic 인 F~ x경우와 같습니다 x F x.
[0..10)하므로 기본적으로 '0123456789'의 임의 순열을 의미합니다.
제이
10?10
J에는 기본 제공 거래 연산자 (? )가 있습니다. 따라서 10 (10 10?10) 중 10을 취할 수 있습니다 .
APL
1-⍨10?10
APL에는 불행히도 0 대신 1로 시작하는 동일한 연산자가 있습니다. 따라서 우리는 각 숫자에서 하나를 빼고 있습니다 ( 통근 연산자로 인해 1-⍨X의미 X-1합니다).
10#.
⎕IO←0그것을 뺄 필요 가 없다고 가정 할 수 있습니다 . 또한, J 및 APL 모두를 위해, 당신은으로 바이트를 저장하는 통근을 사용할 수 있습니다 ?~10및 ?⍨10파생 기능의 모나드 응용 프로그램이 왼쪽 인수로 또한 오른쪽 인자를 사용하기 때문이다. 그러나 이것은 J 코드 를 Marinus의 코드와 동일하게 만듭니다 .
파이썬 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)
from random import*하나의 문자를 저장 하는 데 사용할 수 있습니다 . 이것은 내 Perl 6 솔루션처럼 보이지만 더 장황하지만 더 자세한 경우에도 이와 같은 것이 Python에서 작동 할 수 있음을 보는 것이 좋습니다.
"0123456789"사용하여 range매핑 하지 않고 샘플링하여 문자를 몇 개 더 저장할 수 있습니다 str.
PHP, 29 자
<?=str_shuffle('0123456789');
PHP에서는 닫기 태그가 필요하지 않습니다. 그러나 규칙에 위배되는 경우 대체 할 수 있습니다. ?> 1 순증가.
<?=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.
<?=및 ?>. 그것들이없는 유효한 PHP 코드입니다.
echo 길이는 같고 결합 되어 <?=있으며 길이 ?>가 없으면 코드 패드에서 작동하지 않습니다. 그래도 고마워. : P
print pick *,^10
이것은 모든 임의의 요소를 포함하는 배열 (생성 pick *부터) 0로 9그 결과를 출력한다 ( print).
샘플 출력 :
$ perl6 -e 'print pick *,^10'
4801537269
$ perl6 -e 'print pick *,^10'
1970384265
$ perl6 -e 'print pick *,^10'
3571684902
pick.
[~](Perl 6 문법에 따르면 listop으로 구문 분석 됨) 인수가 포함 된 경우 공백 또는 괄호가 필요합니다. 그렇지 않으면, Perl 6 컴파일러는 "2 개의 용어가 행에 대해"불평합니다. 이전 버전의 Perl 6에서는 필요하지 않았지만 이것은 과거입니다. Perl 6은 여전히 작업 중입니다.
print대신 say [~]하고 저장 2 개 문자 :
10,{;9rand}$
단순히 자릿수 목록을 생성합니다 (10, ) {...}$을 생성하고 임의의 임의의 키에 따라 정렬하면 임의의 자릿수 순서가 생성됩니다.
예 ( 온라인 시도 ) :
4860972315
0137462985
9rand와 99rand겠습니까 (대부분) 수정이; 실제로 완벽9.?rand 할 것 입니다.
randIntNoRep(1,10
randIntNoRep(0,9:.1sum(Ans10^(cumSum(1 or Ans.
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('')
with c as(select 0i union all select i+1from c where i<9)select i+0from c order by newid()for xml path('').
(VALUES (1),(2),...)
숫자 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)
for(a="";!a[9];){~a.indexOf(b=Math.floor(Math.random()*10))||(a+=b)}alert(a)
for(a="";!a[9];){~a.indexOf(b=~~(Math.random()*10))||(a+=b)}alert(a)
shuf -i0-9|paste -sd ''
shuf -i0-9|tr -d \\n
shuf -zi0-9
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/.
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.
Math.floor(x) === 0|x.
l=11 and switch your while loop condition to while(--l)
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.
using System;
using System.Linq;
class P
{
static void Main()
{
Enumerable.Range(0,10).OrderBy(g => Guid.NewGuid()).ToList().ForEach(Console.Write);
}
}
using System;using System.Linq;class P{static void Main(){Enumerable.Range(0,10).OrderBy(g => Guid.NewGuid()).ToList().ForEach(Console.Write);}}
Enumerable.Range(0,10), and you don't need the curly brackets in the foreach loop.
alert("0123456789".split("").sort(function(){return .5-Math.random()}).join(""))
JS-Fiddle: http://jsfiddle.net/IQAndreas/3rmza/
alert("0123456789".split("").sort(n=>.5-Math.random()).join(""))
return and .5
-10?10
As with J, ? is the deal operator; the - forces the values to not repeat.
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.
util.Random.shuffle(0 to 9).mkString
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.
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).
XrśO
X › Push 10 to the stack
r › Push the range from [1...10]
ś › Shuffle the stack
O › Output the whole stack separated by spaces
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.
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).