g | x | w | all
Bytes Lang Time Link
075Tcl171021T222617Zsergiol
004Thunno 2230624T141320ZThe Thon
004Vyxal s211206T185800ZAaroneou
020Zsh211003T104415Zpxeger
040Mathematica140106T145953ZDavidC
024Ly211003T091416Zcnamejj
033Factor211003T021252Zchunes
021Perl 5171022T032854ZXcali
012><>180116T112707ZJo King
081C# .NET Core180118T125228Zkakkarot
nanChip180117T155418ZPhlarx
130Java 8170215T093249ZKevin Cr
004Japt170523T112024ZShaggy
083Javascript180115T204534Zdavid
003Pyt180115T174206Zmudkip20
096LibreLogo171022T183719ZGrant Mi
068Javascript140118T183606Zscribble
042Clojure140107T154617Zclaj
00405AB1E170404T184515ZP. Knops
004√ å ı ¥ ® Ï Ø ¿170320T181048Zcaird co
077Python 2170320T203204Zsporkl
097Sinclair ZX81/Timex TS1000/1500 BASIC170215T174551ZShaun Be
066Lithp170216T082902ZAndrakis
050SmileBASIC170215T131756Z12Me21
144C170215T143544ZAbel Tom
145C#140106T152734ZJMK
005TIBASIC140106T154419ZTimtech
024Powershell170215T100452Zcolsw
005CJam170215T095101ZLinnea G
016Perl 6 18140106T090002Znull
063F#140106T165202ZRik
079Bash140118T200839Zjoeytwid
097C140118T204413ZJosh
006q/kdb [6 chars]140118T180337Znyi
037PHP 37 Characters140106T102233Zcjfaure
174SPSS140109T112703Zdjhurio
096Javascript140108T230042Zbrother
018Ruby140106T100841ZDarren S
082JavaScript140106T155037Zgthacode
nan140106T105518Zvhadalgi
057Python 2.7140106T094532ZJoachim
043Racket140106T225246ZSylweste
064LOGO140106T222450ZSandman4
037Scala140106T214856ZBobby
029PHP140106T201614ZJames S
135This is not much smaller than JMK's answer140106T190117ZCameron
nanProlog140106T180310ZEdu
023Shell/Coreutils140106T163942ZHasturku
027Mathematica140106T162326ZAjasja
006K/Kona140106T144025ZKyle Kan
023R140106T141751Zdjhurio
004 J140106T120739Zmarinus
072Forth140106T105025ZDarren S
080JavaScript140106T104421ZIQAndrea
014Octave140106T100549ZJoachim
008J140106T092431ZHoward
012GolfScript140106T090635ZHoward

Tcl, 75 bytes

puts [join [lsort -c {try {expr rand()>.5} on 9} {1 2 3 4 5 6 7 8 9 0}] ""]

Try it online!

Thunno 2, 4 bytes

kDµr

Attempt This Online!

Explanation

kDµr  # Implicit input
kD    # Push the string "0123456789"
  µr  # Take a random permutation
      # Implicit output

Vyxal s, 4 bytes

kdÞ℅

Try it Online!

Explanation:

kd   # Digits `0123456789`
  Þ℅ # Random permutation
     # 's' flag - Print the sum of the top of the stack

Zsh, 20 bytes

shuf -i0-9|tr -d \\n

Attempt This Online!

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

Try it online!

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

Try it online!

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

Try it online!

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

Try it online!

><>, 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!

Try It Online!

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()))

Try it online!

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:

  1. fill a queue with the numbers 0 through 9
  2. pop the head of the queue, call this x
  3. generate a random number 0 to 3
    • if 3, print x
    • if not 3, append x back onto the queue
  4. 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:

Try it here.

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

Try it online


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


Try it online!

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:

enter image description here

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

Try online

√ å ı ¥ ® Ï Ø ¿ , 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])

Try it online!

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

  1. Sinclair ZX80 and ZX81 BASIC does not accept multi-statemented lines, like 10 PRINT "HELLO":GOTO 10
  2. The interpreter adds in white spaces before and after most commands, so this version of BASIC is one of the most difficult to golf
  3. You can manipulate strings by position like a char[] in C, although strings are indexed from 1 and not 0
  4. This new version will work on an unexpanded (1K/2K) machine for real
  5. 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)))""))

Try it online!

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

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("");
}

q/kdb [6 chars]

-10?10

will generate 10 unique random numbers.

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]

enter image description here

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