A lottery company wants to generate a random lottery ticket number of length 10 characters.

Write a code in any language to create such a number in which every digit comes only once for example 9354716208 in this number all integers from 0 to 9 comes only once. This number should be a random number.

  • The generated number should be shown on screen.
  • It must be able to generate all permutations of all allowable characters.
  • The code is required to be as small as possible (in bytes).
  • 3
    \$\begingroup\$ Why should it be in Java or PhP? \$\endgroup\$ – Fabinout Jan 6 '14 at 8:54
  • 4
    \$\begingroup\$ Generally, it's good idea to allow any language, according to code-golf description. \$\endgroup\$ – Konrad Borowski Jan 6 '14 at 8:58
  • 10
    \$\begingroup\$ How is it that one of the longest and least golfed answers (the SQL answer), without even a char count, stand as the accepted answer in code-golf when folks like @Howard have 5 or 8 character answers? \$\endgroup\$ – Darren Stone Jan 6 '14 at 22:05
  • 1
    \$\begingroup\$ Yes, @marinus has a 4 byte solution (mine is 6 bytes) \$\endgroup\$ – Timtech Jan 6 '14 at 22:23
  • 4
    \$\begingroup\$ -1 The selection of the winner is improper, given that this was a code-golf challenge. \$\endgroup\$ – DavidC Jan 7 '14 at 0:19

52 Answers 52

1 2

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

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


{0..9}|>Seq.sortBy(fun _->Guid.NewGuid())|>Seq.iter(printf"%d")

SmileBASIC, 50 bytes

SWAP S$[RND(10)],S$[0]?S$GOSUB@L


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.
  • \$\begingroup\$ what stops this having duplicate numbers? \$\endgroup\$ – colsw Feb 15 '17 at 13:46
  • \$\begingroup\$ Wow it seems like a lot of people made the same mistake. It should work correctly now. \$\endgroup\$ – 12Me21 Feb 15 '17 at 19:07

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"
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
8 LET A=1+INT (RND*10)
9 IF A$(A)=" " THEN GOTO 8
10 LET B$=B$+A$(A)
11 LET A$(A)=" "

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)

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


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
  • 1
    \$\begingroup\$ String.join("",l) is shorter than replacement. Try it online! \$\endgroup\$ – user41805 Feb 16 '17 at 9:45
  • \$\begingroup\$ But in order for ^ to work, you need only int elements, so you can do l.add(i+++"") in the for-loop \$\endgroup\$ – user41805 Feb 16 '17 at 10:35

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


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.

  • \$\begingroup\$ If you change the 0-9 code you can reduce it a bit; 11 bytes \$\endgroup\$ – Teal pelican Jan 18 '18 at 9:50
  • \$\begingroup\$ @Tealpelican Thanks! \$\endgroup\$ – Jo King Jan 18 '18 at 12:27
  • \$\begingroup\$ I think for the 10 byte version you meant } not { as { will remove 5 from the output but } will remove 0 from the output so none would work. A note :- TIO errors on trying to move right or left on an empty stack because it tries to pop then push from an empty stack. The ><> esolang page doesn't express what should or should not happen in this instance but as the "official" interpreter was written in python with the pop instruction used in both move right and left then TIO is acting correctly. \$\endgroup\$ – Teal pelican Jan 18 '18 at 13:52
  • \$\begingroup\$ This kind of question is why I wish we had single way angled mirrors in ><> something like this; ◣ where going up or right reverse the direction but down and right change it axis \$\endgroup\$ – Teal pelican Jan 18 '18 at 13:57
  • \$\begingroup\$ Are you sure this can produce every permutation? It always seems to return a number starting with 0 or 9. I think you can fix it by adding ! to the end of the second line, though. \$\endgroup\$ – Not a tree Jan 22 '18 at 8:38

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.

C, 97 characters

C is unrepresented...time to fix that!


Slightly more legible:


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.


CJam, 5 bytes

10,    e#Range 0..9 inclusive
   mr  e#Shuffle

Powershell, 24 Bytes



-join( #Join an array of
0..9 #The numbers 0-9
|sort{random} #Sorted into a random order

running it 10 times results in:


C 144 bytes


Ungolfed version:

void f()
   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]);



Every time this binary is executed, a new random array of numbers from 0 to 9 is printed.


  • srand is used so that a new seed is produced everytime for rand function.
  • 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

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.


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 ''.

  • \$\begingroup\$ (space)''.join([str(i) for i in x]) -> `x`[1::3] \$\endgroup\$ – Erik the Outgolfer Oct 22 '17 at 7:36

05AB1E, 4 bytes

The language probably changed in between the exercise and my solution, so this is not really competing.


Try online


Tcl, 84 bytes

proc f a\ b {expr rand()>.5}
puts [join [lsort -command f {1 2 3 4 5 6 7 8 9 0}] ""]

Try it online!


LibreLogo, 96 bytes


x=list(range 10)
z='' while c>0[ r=int(ps any) if r<c[ z+=str(x.pop(r)) ] c=count x ]print z


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


enter image description here


Pyt, 3 bytes



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


Japt, 6 4 bytes


Try it online


ö¬ generates a random permutation of the range [0-10) (with A being the Japt constant for 10) and q joins it to string.


Chip, 75 + 17 = 92 bytes

+17 bytes for args -g0i -w -mq -c20

 8 ?]v~S

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.


C# (.NET Core), 81 bytes

()=>string.Join("",Enumerable.Range(0,10).OrderBy(x=>new System.Random().Next()))

Try it online!


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!

1 2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.