| Bytes | Lang | Time | Link |
|---|---|---|---|
| 075 | Tcl | 171021T222617Z | sergiol |
| 004 | Thunno 2 | 230624T141320Z | The Thon |
| 004 | Vyxal s | 211206T185800Z | Aaroneou |
| 020 | Zsh | 211003T104415Z | pxeger |
| 040 | Mathematica | 140106T145953Z | DavidC |
| 024 | Ly | 211003T091416Z | cnamejj |
| 033 | Factor | 211003T021252Z | chunes |
| 021 | Perl 5 | 171022T032854Z | Xcali |
| 012 | ><> | 180116T112707Z | Jo King |
| 081 | C# .NET Core | 180118T125228Z | kakkarot |
| nan | Chip | 180117T155418Z | Phlarx |
| 130 | Java 8 | 170215T093249Z | Kevin Cr |
| 004 | Japt | 170523T112024Z | Shaggy |
| 083 | Javascript | 180115T204534Z | david |
| 003 | Pyt | 180115T174206Z | mudkip20 |
| 096 | LibreLogo | 171022T183719Z | Grant Mi |
| 068 | Javascript | 140118T183606Z | scribble |
| 042 | Clojure | 140107T154617Z | claj |
| 004 | 05AB1E | 170404T184515Z | P. Knops |
| 004 | √ å ı ¥ ® Ï Ø ¿ | 170320T181048Z | caird co |
| 077 | Python 2 | 170320T203204Z | sporkl |
| 097 | Sinclair ZX81/Timex TS1000/1500 BASIC | 170215T174551Z | Shaun Be |
| 066 | Lithp | 170216T082902Z | Andrakis |
| 050 | SmileBASIC | 170215T131756Z | 12Me21 |
| 144 | C | 170215T143544Z | Abel Tom |
| 145 | C# | 140106T152734Z | JMK |
| 005 | TIBASIC | 140106T154419Z | Timtech |
| 024 | Powershell | 170215T100452Z | colsw |
| 005 | CJam | 170215T095101Z | Linnea G |
| 016 | Perl 6 18 | 140106T090002Z | null |
| 063 | F# | 140106T165202Z | Rik |
| 079 | Bash | 140118T200839Z | joeytwid |
| 097 | C | 140118T204413Z | Josh |
| 006 | q/kdb [6 chars] | 140118T180337Z | nyi |
| 037 | PHP 37 Characters | 140106T102233Z | cjfaure |
| 174 | SPSS | 140109T112703Z | djhurio |
| 096 | Javascript | 140108T230042Z | brother |
| 018 | Ruby | 140106T100841Z | Darren S |
| 082 | JavaScript | 140106T155037Z | gthacode |
| nan | 140106T105518Z | vhadalgi | |
| 057 | Python 2.7 | 140106T094532Z | Joachim |
| 043 | Racket | 140106T225246Z | Sylweste |
| 064 | LOGO | 140106T222450Z | Sandman4 |
| 037 | Scala | 140106T214856Z | Bobby |
| 029 | PHP | 140106T201614Z | James S |
| 135 | This is not much smaller than JMK's answer | 140106T190117Z | Cameron |
| nan | Prolog | 140106T180310Z | Edu |
| 023 | Shell/Coreutils | 140106T163942Z | Hasturku |
| 027 | Mathematica | 140106T162326Z | Ajasja |
| 006 | K/Kona | 140106T144025Z | Kyle Kan |
| 023 | R | 140106T141751Z | djhurio |
| 004 | J | 140106T120739Z | marinus |
| 072 | Forth | 140106T105025Z | Darren S |
| 080 | JavaScript | 140106T104421Z | IQAndrea |
| 014 | Octave | 140106T100549Z | Joachim |
| 008 | J | 140106T092431Z | Howard |
| 012 | GolfScript | 140106T090635Z | Howard |
Tcl, 75 bytes
puts [join [lsort -c {try {expr rand()>.5} on 9} {1 2 3 4 5 6 7 8 9 0}] ""]
Thunno 2, 4 bytes
kDµr
Explanation
kDµr # Implicit input
kD # Push the string "0123456789"
µr # Take a random permutation
# Implicit output
Vyxal s, 4 bytes
kdÞ℅
Explanation:
kd # Digits `0123456789`
Þ℅ # Random permutation
# 's' flag - Print the sum of the top of the stack
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.
Ly, 24 bytes
9[:,]y[0f?[fsprlr,]puy]p
This adds the digits 0-9 onto the stack, then as long as the stack isn't empty, it picks a random number, rotates the stack entries that many times, then prints the top of the stack.
9[:,] - pushes 9, 8, 7, ... 0 onto the stack
y[ y]p - loops as long as the stack size>0
0f? - generate random number in 0-(stack-size) range
[ ,]p - loops for as many rotations as we want to do
fsp - flip the random digit to the top, save and delete
rlr - reverse the stack, load saved digit, reverse again
u - print the random digit we picked
The number of rotations used really should be in the range 0-(stack-size-1) but the possible extra rotation doesn't hurt anything and it saves a character to use the larger range.
Factor, 33 bytes
10 iota 10 sample [ pprint ] each
| Snippet | Comment | Data stack (top on right) |
|---|---|---|
10 iota |
A range of numbers from 0 inclusive to 10 exclusive | { 0 1 2 3 4 5 6 7 8 9 } |
10 sample |
Take 10 random samples from a sequence without replacement | { 7 3 8 4 2 5 1 9 6 0 } |
[ pprint ] each |
Prettyprint each element without a newline |
Perl 5, 21 bytes
@k{0..9}++;say keys%k
Perl's hash algorithm puts the hash keys into a a random order, so this should satisfy the requirements.
If it doesn't, here's the old method:
Perl 5, 38 bytes
@a=0..9;print splice@a,rand@a,1while@a
><>, 17 11 12 bytes
-6 bytes thanks to @Teal pelican suggesting a better way to generate the numbers 0-9. Thanks to @Not a Tree for pointing out the previous version only starts with a 9 or a 0.
<v?=9:l
{xn!
Adds all the numbers to the stack and then randomly chooses between cycling the stack or outputting the number until the stack is the empty. Biased towards larger numbers first, but the random wasn't specified to be uniform.
An 11 byte version that doesn't work on TIO due to { erroring on an empty stack, but works on other platforms such as here.
{l:b=?.!
xn
C# (.NET Core), 81 bytes
()=>string.Join("",Enumerable.Range(0,10).OrderBy(x=>new System.Random().Next()))
Chip, 75 + 17 = 92 bytes
+17 bytes for args -g0i -w -mq -c20
8 ?]v~S
?/--^]~9
A\0)0/a
B\1)1/b
C\2)2/c
D\3)3/d
,L-v-^e
)\sf
`zzzzzzzzzz*
Try it online! Try adding -vv to the args list to see the values on the queue as it runs, in the debug output.
Not the most straightforward solution... The strategy here is like this:
- fill a queue with the numbers
0through9 - pop the head of the queue, call this
x - generate a random number
0to3- if
3, printx - if not
3, appendxback onto the queue
- if
- jump to step 2 until all ten numbers have been printed
This strategy ensures that all permutations are possible, however the permutations are not evenly distributed. Also, it is theoretically possible to never finish printing.
This could potentially be slightly smaller if I generate a single random bit (0 or 1) instead of two (0 to 3), but it would have a more extreme effect on the distribution. My initial attempt, however, didn't actually save many bytes.
If there is interest, I will endeavor to explain further the actual implementation details.
Java 8, 153 150 143 139 130 bytes
import java.util.*;v->{List l=new Stack();for(int i=0;i<=9;l.add(i+++""));Collections.shuffle(l);System.out.print("".join("",l));}
-7 bytes thanks to @KritixiLithos
Explanation:
import java.util.*; // Required import for List, Stack, Collections
v->{ // Method with empty unused parameter and no return-type
List l=new Stack(); // List
for(int i=0;i<=9; // Loop from 0 to 9 (inclusive)
l.add(i+++"")); // Add these numbers to the List (as String)
Collections.shuffle(l); // Randomly shuffle the List
System.out.print("".join("",l));}// Print the List content without delimiter
Japt, 6 4 bytes
Aö¬q
Explanation
ö¬ generates a random permutation of the range [0-10) (with A being the Japt constant for 10) and q joins it to string.
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.
Pyt, 3 bytes
ɳᒆʀ
Explanation:
ɳ Push the string "0123456789" onto the stack
ᒆ Push an array containing all possible permutations (of "0123456789") onto the stack
ʀ Pick an element from the array uniformly at random
LibreLogo, 96 bytes
Code:
x=list(range 10)
c=1
z='' while c>0[ r=int(ps any) if r<c[ z+=str(x.pop(r)) ] c=count x ]print z
Explanation:
x = list(range 10) ; x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
c = 1
z = ''
while c > 0 [ ; While !empty( x )
r = int(ps any) ; r = random 10
if r < c [ ; If Random # < count( x )
z += str(x.pop(r)) ; z.append( x[random] ), x.remove( x[random] )
]
c = count x ; Keep track of leftover elements
]
print z ; Print Result
Result:
Javascript (79 78 68 characters)
Rather than creating an array with the numbers 0-9 and sorting it, I decided to generate random numbers. When it came up with a number that was not already in the array then added it. This repeats ten times and then alerts the output.
for(a="";!a[9];){~a.indexOf(b=~~(Math.random()*10))||(a+=b)}alert(a)
Clojure, 42
(println (apply str (shuffle (range 10))))
6209847315
05AB1E, 4 bytes
The language probably changed in between the exercise and my solution, so this is not really competing.
žh.r
√ å ı ¥ ® Ï Ø ¿ , 4 bytes
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
Python 2, 77 bytes
from random import*;x=range(10);shuffle(x);print ''.join([str(i) for i in x])
This creates the desired list using Python's range, then shuffles it using random.shuffle. random.shuffle just randomizes the list. Then it prints out each item in the list joined by ''.
Sinclair ZX81/Timex TS1000/1500 BASIC, 133 bytes 144 bytes 97 bytes (listing)
I started this by trying to imagine how PHP's str_shuffle() would work in Sinclair [ZX81] BASIC, and ended here (new and improved version):
1 LET A$="0987654321"
2 LET R=INT (RND* LEN A$)+1
3 PRINT A$(R);
4 LET A$=A$( TO R-1)+A$(R+1 TO )
5 GOTO 2+((A$="")*4)
This solution is based on a post by XavSnap on the Sinclair ZX World forums after I posted my solution below.
Initial entry (slower and bloated):
1 LET A$="0123456789"
2 LET B$=""
3 FOR I=0 TO 9
4 GOSUB 8
5 NEXT I
6 PRINT B$
7 STOP
8 LET A=1+INT (RND*10)
9 IF A$(A)=" " THEN GOTO 8
10 LET B$=B$+A$(A)
11 LET A$(A)=" "
12 RETURN
Some things to note
- Sinclair ZX80 and ZX81 BASIC does not accept multi-statemented lines, like
10 PRINT "HELLO":GOTO 10 - The interpreter adds in white spaces before and after most commands, so this version of BASIC is one of the most difficult to golf
- You can manipulate strings by position like a
char[]in C, although strings are indexed from 1 and not 0 - This new version will work on an unexpanded (1K/2K) machine for real
- When I've worked it out, the byte count is the listing only, it's using more system RAM. As this is 8 bit tech, I'll also work out the actual byte count (listing + variable stack)
Lithp, 66 bytes
(print(join(list-rand(permutations(list 0 1 2 3 4 5 6 7 8 9)))""))
permutations/1 generates all permutations of the given list. There will be no duplicates. We pick a random item from the generated permutations and print it.
The try it online link has a better example for printing out a number of unique entries.
This could be a little shorter if the lists module is imported, but importing it takes up more space than is saved by a (seq 0 9) call.
SmileBASIC, 50 bytes
S$="0123456789
@L
SWAP S$[RND(10)],S$[0]?S$GOSUB@L
Explained:
S$="0123456789" 'create string with digits 0-9
@LOOP 'label
SWAP S$[RND(10)],S$[0] 'swap a random character with the first character
PRINT S$ 'print the string
GOSUB @LOOP 'Loop. Using GOSUB without RETURN will eventually cause a stack overflow, ending the program.
C 144 bytes
f(){srand(time(0));j,i,a[10];for(i=0;i<=9;i++){a[i]=i;}for(i=0;i<4;i++){j=rand()%9;a[j]=9-j;a[9-j]=9-a[j];}for(i=0;i<=9;i++)printf("%d",a[i]);}
Ungolfed version:
void f()
{
srand(time(NULL));
int j, i, a[10];
for (i = 0; i <= 9; i++)
a[i] = i;
//jumble the array elements
for (i = 0; i<4; i++)
{
j = rand() % 9;
a[j] = 9 - j;
a[9 - j] = 9 - a[j];
}
for (i = 0; i <= 9; i++)
printf("%d ", a[i]);
}
Usage
Every time this binary is executed, a new random array of numbers from 0 to 9 is printed.
Explanation
srandis used so that a new seed is produced everytime forrandfunction.- Store the elements from 0 to 9 in an array.
- Jumble the array elements by generating four random values between 0-9. (I'm not sure if that step was so wise, can be done in a better way i guess.)
- Print the array elements
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);}}
TI-BASIC, 5 bytes
randIntNoRep(1,10
Powershell, 24 Bytes
-join(0..9|sort{random})
Explanation:
-join( #Join an array of
0..9 #The numbers 0-9
|sort{random} #Sorted into a random order
)
running it 10 times results in:
9184702653
7813529406
0458237691
2158604793
5391782046
4673980251
4870532196
9412576380
4816275309
1098624537
4257910683
CJam, 5 bytes
10,mr
10, e#Range 0..9 inclusive
mr e#Shuffle
Perl 6 (18 16 characters)
print pick *,^10
This generates array containing all random elements (pick *) from 0 to 9 and outputs the result (print).
Sample output:
$ perl6 -e 'print pick *,^10'
4801537269
$ perl6 -e 'print pick *,^10'
1970384265
$ perl6 -e 'print pick *,^10'
3571684902
F#, 71 63 characters
I'm new to F#, but here's what I've come up with:
{ 0..9 }
|> Seq.sortBy (fun _ -> System.Guid.NewGuid())
|> Seq.iter (printf "%d")
compacted:
{0..9}|>Seq.sortBy(fun _->Guid.NewGuid())|>Seq.iter(printf"%d")
Bash (79 characters)
seq 0 9|awk 'BEGIN{srand()}{print rand()"\t"$0}'|sort -nk1|cut -f2-|tr -d '\n'
Note that the lottery company should not run this more than once per second!
Edit: Oh rats, this answer blows mine away.
C, 97 characters
C is unrepresented...time to fix that!
d[10],i;main(j){srand(&j);while(i++<10){doj=rand()%10;while(d[j]);d[j]=putchar(j+'0');}puts("");}
Slightly more legible:
d[10],i;
main(j){
srand(&j);
while(i++<10){
do
j=rand()%10;
while(d[j]);
d[j]=putchar(j+'0');
}
puts("");
}
PHP - 37 Characters
<?=join('',array_rand(range(0,9),10))
I had an 18-character solution that should theoretically work but PHP is weird.
Or, if you want an xkcd answer:
<?="5398421706" // Chosen by program above; guaranteed to be random ?>
EDIT: Thanks xfix, it's now 5 characters shorter and complete. EDIT AGAIN: Live example.
SPSS (174 bytes)
Most of the commands in SPSS can be shortened to the first three letter. It is convenient for code golfing.
new fil.
inp pro.
loo i=0 to 9.
comp R=uni(1).
end cas.
end loo.
end fil.
end inp pro.
sor cas R.
fli i.
for var001 to var010 (f1).
wri /var001 to var010.
exe.
Javascript (96)
function x(){return s.search(r=0|Math.random()*10)<0?r:x()}for(i=0,s='';++i<=10;s+=x());alert(s)
First attempt (109)
s='';for(i=0;++i<=10;s+=(x=function(){return s.indexOf(r=(m=Math).floor(m.random()*10))<0?r:x()})())alert(s);
Ruby, 18
Run this in irb:
[*0..9].shuffle*''
If you want this to be a stand-alone program, with output to stdout (the rules don't seem to require this), then add these 4 chars at the start:
$><<
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/.
In 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))
See Demo
OR something similar (courtesy of @manatwork) using recursion and xml.
with c as(select 0i union all select i+1from c where i<9)select i+0from c order by newid()for xml path('')
Python 2.7 (64 63 57)
Not a chance here compared to the operator heavy languages and due to the lack of default loaded random :) This is the shortest I could come up with;
from random import*
print''.join(sample("0123456789",10))
It creates a range and samples 10 numbers from it without replacement.
(Thanks to @xfix for the shorter import format fix and @blkknght for pointing out my somewhat über complicated sampling range)
Python 2.7 (40)
If you run it from the interactive prompt and can read comma separated, you can shave it to 40, but it feels a bit like breaking the spirit of the rules;
from random import*
sample(range(10),10)
Racket 45 43
(map print(shuffle'(0 1 2 3 4 5 6 7 8 9)))
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.
Scala, 37
util.Random.shuffle(0 to 9).mkString
PHP, 29 chars
<?=str_shuffle('0123456789');
With PHP, the closing tag isn't required. But if that's against the rules, then you can replace ; with ?> for 1 net increase.
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).
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).
Shell/Coreutils, 23
shuf -i0-9|paste -sd ''
Mathematica, 27
Row@RandomSample@Range[0,9]

K/Kona (6)
-10?10
As with J, ? is the deal operator; the - forces the values to not repeat.
R (23 characters)
cat(sample(0:9),sep="")
Sample output:
> cat(sample(0:9),sep="")
3570984216
> cat(sample(0:9),sep="")
3820791654
> cat(sample(0:9),sep="")
0548697132
J (4 bytes)
Couldn't resist.
?~10
In J, if F is dyadic , F~ x is the same as x F x.
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.
JavaScript (80 characters)
alert("0123456789".split("").sort(function(){return .5-Math.random()}).join(""))
JS-Fiddle: http://jsfiddle.net/IQAndreas/3rmza/
Octave (14)
randperm(10)-1
randperm unfortunately creates a selection from 1..n, so have to subtract 1 at the end to get 0-9.
J, 5 characters and APL, 8 characters
J
10?10
J has the built-in deal operator (?). Thus, we can take 10 out of 10 (10?10).
APL
1-⍨10?10
APL has the same operator which unfortunately starts with one instead of zero. We are therefore subtracting one from each number (1-⍨X means X-1 due to the commute operator).
GolfScript, 12 characters
10,{;9rand}$
Simply generates the list of digits (10,) and sorts it {...}$ according to some random keys - which yields a random order of the digits.
Examples (try online):
4860972315
0137462985
