# 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

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


compacted:

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


# SmileBASIC, 50 bytes

S$="0123456789 @L SWAP S$[RND(10)],S$?S$GOSUB@L


Explained:

S$="0123456789" 'create string with digits 0-9 @LOOP 'label SWAP S$[RND(10)],S$ '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.

• what stops this having duplicate numbers? – colsw Feb 15 '17 at 13:46
• Wow it seems like a lot of people made the same mistake. It should work correctly now. – 12Me21 Feb 15 '17 at 19:07

# Sinclair ZX81/Timex TS1000/1500 BASIC, 133 bytes144 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) # Java 8, 153150143139 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  • String.join("",l) is shorter than replacement. Try it online! – Kritixi Lithos Feb 16 '17 at 9:45 • But in order for ^ to work, you need only int elements, so you can do l.add(i+++"") in the for-loop – Kritixi Lithos 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. <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  • If you change the 0-9 code you can reduce it a bit; 11 bytes – Teal pelican Jan 18 '18 at 9:50 • @Tealpelican Thanks! – Jo King Jan 18 '18 at 12:27 • 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. – Teal pelican Jan 18 '18 at 13:52 • 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 – Teal pelican Jan 18 '18 at 13:57 • 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. – 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. exe.  ## C, 97 characters C is unrepresented...time to fix that! d,i;main(j){srand(&j);while(i++<10){doj=rand()%10;while(d[j]);d[j]=putchar(j+'0');}puts("");}  Slightly more legible: d,i; main(j){ srand(&j); while(i++<10){ do j=rand()%10; while(d[j]); d[j]=putchar(j+'0'); } puts(""); }  # 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,mr
10,    e#Range 0..9 inclusive
mr  e#Shuffle


# 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


## C 144 bytes

f(){srand(time(0));j,i,a;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;

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

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

• (space)''.join([str(i) for i in x]) -> x[1::3] – 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.

žh.r

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!

• [split 1234567890 ""] renders the same byte extent as {1 2 3 4 5 6 7 8 9 0} – sergiol Oct 21 '17 at 22:28
• – sergiol Oct 21 '17 at 22:36

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


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

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

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