# Random ticket code generator

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).
• 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. – Konrad Borowski 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

## J (4 bytes)

Couldn't resist.

?~10


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

• +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

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

• Oh, wow, that's nice. – Konrad Borowski 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
• You may assume that ⎕IO←0 so you don't have to subtract one. Also, for both J and APL, you can use commute to save a byte with ?~10 and ?⍨10 since monadic application of the derived function uses its right argument also as left argument. NOte however that this makes the J code identical to that of Marinus. – Adám Jan 18 '18 at 12:47

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)

• 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. – Konrad Borowski 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, 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.

• You beat me to this solution. – Shaun Bebbers Feb 15 '17 at 15:41

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

$><<  • 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 – user13426 Jan 6 '14 at 11:24 # 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. • 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. – Konrad Borowski 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 # 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

• +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. – Konrad Borowski 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 :). – Konrad Borowski Jan 22 '14 at 16:38

### 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

• 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

## 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


## TI-BASIC, 5 bytes

randIntNoRep(1,10

• 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
• I don't think this challenge requires an integer type, only that "The generated number should be shown on screen" which it is. – Timtech Feb 15 '17 at 11:47
• Hmm, I thought the question was asking for a number (as did others but it seems the intent of the challenge author was never clarified. Some other solutions output as a list (J and APL) in any case. – lirtosiast Feb 16 '17 at 5:50
• Well, I wouldn't assume that unless I was sure, because this method is shorter. – Timtech Feb 16 '17 at 11:46

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.

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

• 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
• You can simplify the cte with (VALUES (1),(2),...) – ypercubeᵀᴹ Jan 7 '14 at 17:07

# Javascript (7978 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)

• You can save 1 byte using || short-circuit evaluation instead of if like: for(a="";!a[9];){b=Math.floor(Math.random()*10);~a.indexOf(b)||(a+=b)}alert(a) – Steven Palinkas May 24 '17 at 9:58
• @StevenPalinkas Thanks, great idea! I have updated the post accordingly. – scribblemaniac May 24 '17 at 16:10
• We could also save 2 bytes with a bit of rearrangement in the code: for(a="";!a[9];){~a.indexOf(b=Math.floor(Math.random()*10))||(a+=b)}alert(a) – Steven Palinkas May 25 '17 at 16:28
• We can save an additional 8 bytes using the "shorthand" for Math.floor like: for(a="";!a[9];){~a.indexOf(b=~~(Math.random()*10))||(a+=b)}alert(a) – Steven Palinkas May 26 '17 at 10:04

## Mathematica, 27

Row@RandomSample@Range[0,9]


• Nice way to avoid strings! – DavidC Jan 6 '14 at 16:43

## Shell/Coreutils, 23

shuf -i0-9|paste -sd ''

• 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
• what about shuf -zi0-9 – marcosm May 23 '17 at 11:45
• @marcosm: That gives you lines terminated with zeroes, which is slightly strange. – Hasturkun May 23 '17 at 12:14

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


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

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

• 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

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

• 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

## JavaScript (80 characters)

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


JS-Fiddle: http://jsfiddle.net/IQAndreas/3rmza/

• 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
• 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
• @Greg It is a random distribution (assuming Math.random is sufficiently random), it just isn't a uniform one. – SuperJedi224 Mar 7 '17 at 2:47
• The original blog post is gone, adding the internet archive for posterity: web.archive.org/web/20150212083701/http://sroucheray.org/blog/… – Greg Mar 7 '17 at 17:53

## K/Kona (6)

-10?10


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

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

• 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

## Scala, 37

util.Random.shuffle(0 to 9).mkString


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

# 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


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

# q/kdb [6 chars]

-10?10


will generate 10 unique random numbers.

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


Clojure, 42

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


6209847315

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

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

• Welcome to the site! :) – DJMcMayhem Jan 15 '18 at 20:51

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

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.

# Racket 45 43

(map print(shuffle'(0 1 2 3 4 5 6 7 8 9)))
`