Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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).
share|improve this question
Why should it be in Java or PhP? – Fabinout Jan 6 '14 at 8:54
Generally, it's good idea to allow any language, according to code-golf description. – xfix Jan 6 '14 at 8:58
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? – Darren Stone Jan 6 '14 at 22:05
Yes, @marinus has a 4 byte solution (mine is 6 bytes) – Timtech Jan 6 '14 at 22:23
-1 The selection of the winner is improper, given that this was a code-golf challenge. – DavidC Jan 7 '14 at 0:19

34 Answers 34

up vote 35 down vote accepted

J (4 bytes)

Couldn't resist.


In J, if F is dyadic , F~ x is the same as x F x.

share|improve this answer
+1 I think I may have to try something slightly more terse than Python to beat this. – Joachim Isaksson Jan 6 '14 at 14:32
Does this allow for a password that begins with zero? According to the rules, the program "must be able to generate all permutations of all allowable characters" – DavidC Jan 6 '14 at 15:10
@DavidCarraher: yes. It selects 10 non-repeating random numbers from the interval [0..10), so that basically means a random permutation of '0123456789'. – marinus Jan 6 '14 at 15:58
I see. I raised this because in most languages, the "number", 0123456789, will automatically be edited to the form 123456789. The string, "0123456789", remains untouched. So my question is really this: is your output a number or a string? – DavidC Jan 6 '14 at 16:40
@DavidCarraher It's an array. – swish Jan 6 '14 at 20:16

J, 5 characters and APL, 8 characters



J has the built-in deal operator (?). Thus, we can take 10 out of 10 (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).

share|improve this answer
Oh, wow, that's nice. – xfix Jan 6 '14 at 9:53
If OP would have asked specifically for the number not an array, you should convert it to base10 number also, with 10#. – swish Jan 6 '14 at 14:11

Ruby, 18

Run this in irb:


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:

share|improve this answer
You may shorten (0..9).to_a to [*0..9]. – Howard Jan 6 '14 at 10:12
Done and done, sir. Thanks! – Darren Stone Jan 6 '14 at 10:14
You're welcome. But why do you not use [*0..9].shuffle in the first place? – Howard Jan 6 '14 at 10:15
@Howard, because it's late and I'm dumb. :) Thanks! – Darren Stone Jan 6 '14 at 10:20
this return array with number not number – Зелёный Jan 6 '14 at 11:24

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'
$ perl6 -e 'print pick *,^10'
$ perl6 -e 'print pick *,^10'
share|improve this answer
+1 I think you don't need the whitespace before pick. – Howard Jan 6 '14 at 9:11
@Howard: I actually need it. [~] (which is parsed as a listop, according to Perl 6 grammar) requires a whitespace (or paren) after it if it contains any arguments. Otherwise, Perl 6 compiler complains about "two terms in row". It wasn't needed in older versions of Perl 6, but this is the past. The Perl 6 is still being worked on. – xfix Jan 6 '14 at 9:13
@xfix: use print instead of say [~] and save 2 characters :) – Ayiko Jan 22 '14 at 16:16
@Ayiko: Thanks for an improvement :). – xfix Jan 22 '14 at 16:38

GolfScript, 12 characters


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


share|improve this answer
I was about to post this :P – Doorknob Jan 6 '14 at 22:58
That's kind of a crap shuffle, though: for example, the first digit is about three times as likely to be 0 than 1. Replacing 9rand with 99rand would (mostly) fix that; 9.?rand would be practically perfect. – Ilmari Karonen Jan 7 '14 at 1:07
@IlmariKaronen I know, but the question didn't say anything about uniform distribution. – Howard Jan 7 '14 at 8:41

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*

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*
share|improve this answer
You can use from random import* to save one character. This looks like my Perl 6 solution, but more verbose, but it's great to see that something like this can work in Python, even if more verbose. – xfix Jan 6 '14 at 9:50
@xfix Yes, sadly the modules in Python are a bit verbose to get to in comparison :) Updated with your import fix, quite new to the golfing thing so not up to "par" on my idioms. – Joachim Isaksson Jan 6 '14 at 9:59
You can save a few more characters by sampling from the string "0123456789" rather than using range and them mapping str. – Blckknght Jan 6 '14 at 23:09
@Blckknght Thanks, updated with your suggestion :) – Joachim Isaksson Jan 6 '14 at 23:34

PHP - 37 Characters


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.

share|improve this answer
Write a complete program, instead of just complete parts. Also, echo doesn't need parens, and if echo is the first statement in the program, you can replace <?php echo with <?=. Also, join is an alias for implode. – xfix Jan 6 '14 at 10:24
@xfix Thanks, I'll fix. :) – cjfaure Jan 6 '14 at 10:27
You don't even need the <?= and ?>. It's valid PHP code without those. – Jeremy Jan 6 '14 at 18:56
@Jeremy The golf requires that the number be displayed; besides, echo is the same length as <?= and ?> combined, and without those, it doesn't work in Codepad. Thanks though. :P – cjfaure Jan 6 '14 at 19:02
@Jeremy Ah, PHP, where non-embedded implementations besides a terminal are scarce. :P – cjfaure Jan 6 '14 at 19:17

Octave (14)


randperm unfortunately creates a selection from 1..n, so have to subtract 1 at the end to get 0-9.

share|improve this answer

R (23 characters)


Sample output:

> cat(sample(0:9),sep="")
> cat(sample(0:9),sep="")
> cat(sample(0:9),sep="")
share|improve this answer

PHP, 29 chars


With PHP, the closing tag isn't required. But if that's against the rules, then you can replace ; with ?> for 1 net increase.

share|improve this answer

In sql server

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

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

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('')
share|improve this answer
Man, you love CTEs… But as this is a code-golf challenge, better shorten it as much as possible. My best is 186 characters: 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, great trick that newid().) – manatwork Jan 6 '14 at 17:17
Ok, you'r right. Is shorter with CTE. 106 characters: 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 Jan 6 '14 at 17:31
Thanks for the head's up... @manatwork :) – Vijaykumar Hadalgi Jan 7 '14 at 4:07
You can simplify the cte with (VALUES (1),(2),...) – ypercubeᵀᴹ Jan 7 '14 at 17:07

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


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

Better version (90 characters):


Last version (82 characters):



share|improve this answer
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 Jan 6 '14 at 18:11
@RobW Thanks for the tips. I updated my answer. P.S. I guess you meant Math.floor(x) === 0|x. – gthacoder Jan 6 '14 at 18:58
This always has 9 at the end. To fix, initialize l=11 and switch your while loop condition to while(--l) – Greg Jan 6 '14 at 18:59
@Greg Good point. Thank you. I updated the answer. – gthacoder Jan 6 '14 at 19:06
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 Jan 7 '14 at 3:09

JavaScript (80 characters)

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


share|improve this answer
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 Jan 6 '14 at 16:45
"0123456789".split("") vs [0,1,2,3,4,5,6,7,8,9] saves one characters. – Prinzhorn Jan 6 '14 at 17:05
This doesn't really guarantee a random distribution. See…. Nevertheless, that was not stipulated in the rules so good abuse. – Greg Jan 6 '14 at 19:14
You don't need the space between return and .5 – Tibos Jan 7 '14 at 17:02
@Greg Shhhh! Do you have any idea how many characters a real shuffling function takes? ;) – IQAndreas Jan 7 '14 at 17:16

K/Kona (6)


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

share|improve this answer

C# - 145

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);}}
share|improve this answer
You can use Enumerable.Range(0,10), and you don't need the curly brackets in the foreach loop. – Rik Jan 6 '14 at 15:32
@Rik Thanks updated! – JMK Jan 6 '14 at 15:38

Mathematica, 27


enter image description here

share|improve this answer
Nice way to avoid strings! – DavidC Jan 6 '14 at 16:43

TI-BASIC, 6 bytes

:Disp randIntNoRep(1,10
share|improve this answer
Displays a list rather than a number. You're looking for randIntNoRep(0,9:.1sum(Ans10^(cumSum(1 or Ans. – lirtosiast Jun 8 '15 at 1:38

Mathematica 40

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


Output examples



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

share|improve this answer
But why to display 0 as the first character? – Ankush Jan 6 '14 at 15:06
According to the OP, the program "must be able to generate all permutations of all allowable characters". – DavidC Jan 6 '14 at 15:08
@Ankush That's infix notation, so "0" is not always the first char. – Ajasja Jan 6 '14 at 16:24
Ajasja is correct. The program can generate any permutation. I added some remarks above to clarify this. – DavidC Jan 6 '14 at 16:37

Shell/Coreutils, 23

shuf -i0-9|paste -sd ''
share|improve this answer
If we don't need a trailing newline, you can shave this to 20 with shuf -i0-9|tr -d \\n – joeytwiddle Jan 22 '14 at 16:02

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


| ?- 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] ? 

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],
    M is (N0*1000000000)+(N1*100000000)+(N2*10000000)+(N3*1000000)+


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

Using instead:


Gives the numbers in the opposite order:

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

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

share|improve this answer

q/kdb [6 chars]


will generate 10 unique random numbers.

share|improve this answer

Javascript (79 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.

share|improve this answer

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.

share|improve this answer

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


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

share|improve this answer

Scala, 37

util.Random.shuffle(0 to 9).mkString
share|improve this answer

Racket 45 43

(map print(shuffle'(0 1 2 3 4 5 6 7 8 9)))
share|improve this answer


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


42 bytes

share|improve this answer
The generated number should be shown on screen, not it's parts. – Sylwester Jan 7 '14 at 18:46

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")
share|improve this answer

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.

share|improve this answer

Javascript (96)

function x(){return|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);
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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