Take the 2-minute tour ×
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.

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

34 Answers

up vote 35 down vote accepted

J (4 bytes)

Couldn't resist.

?~10

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

share|improve this answer
2  
+1 I think I may have to try something slightly more terse than Python to beat this. –  Joachim Isaksson Jan 6 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" –  David Carraher Jan 6 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 at 15:58
1  
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? –  David Carraher Jan 6 at 16:40
    
@DavidCarraher It's an array. –  swish Jan 6 at 20:16
show 2 more comments

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

share|improve this answer
    
Oh, wow, that's nice. –  xfix Jan 6 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 at 14:11
add comment

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:

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

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)
share|improve this answer
1  
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 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 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 at 23:09
    
@Blckknght Thanks, updated with your suggestion :) –  Joachim Isaksson Jan 6 at 23:34
add comment

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
share|improve this answer
    
+1 I think you don't need the whitespace before pick. –  Howard Jan 6 at 9:11
1  
@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 at 9:13
1  
@xfix: use print instead of say [~] and save 2 characters :) –  Ayiko Jan 22 at 16:16
    
@Ayiko: Thanks for an improvement :). –  xfix Jan 22 at 16:38
add comment

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
share|improve this answer
    
I was about to post this :P –  Doorknob Jan 6 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 at 1:07
    
@IlmariKaronen I know, but the question didn't say anything about uniform distribution. –  Howard Jan 7 at 8:41
add comment

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.

share|improve this answer
add comment

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
share|improve this answer
add comment

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.

share|improve this answer
add comment

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('')
share|improve this answer
1  
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 at 17:17
1  
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 at 17:31
    
Thanks for the head's up... @manatwork :) –  Anonymous Jan 7 at 4:07
    
You can simplify the cte with (VALUES (1),(2),...) –  ypercube Jan 7 at 17:07
add comment

Mathematica, 27

Row@RandomSample@Range[0,9]

enter image description here

share|improve this answer
    
Nice way to avoid strings! –  David Carraher Jan 6 at 16:43
add comment

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.

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 at 10:24
    
@xfix Thanks, I'll fix. :) –  Trimsty Jan 6 at 10:27
    
You don't even need the <?= and ?>. It's valid PHP code without those. –  Jeremy Jan 6 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 –  Trimsty Jan 6 at 19:02
1  
@Jeremy Ah, PHP, where non-embedded implementations besides a terminal are scarce. :P –  Trimsty Jan 6 at 19:17
show 5 more comments

JavaScript (80 characters)

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

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

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

C# - 145

using System;
using System.Linq;
class P
{
    static void Main()
    {
        Enumerable.Range(0,10).OrderBy(g => Guid.NewGuid()).ToList().ForEach(Console.Write);
    }
}

Condensed:

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

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

share|improve this answer
1  
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 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 at 18:58
1  
This always has 9 at the end. To fix, initialize l=11 and switch your while loop condition to while(--l) –  Greg Jan 6 at 18:59
    
@Greg Good point. Thank you. I updated the answer. –  gthacoder Jan 6 at 19:06
1  
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 at 3:09
show 3 more comments

K/Kona (6)

-10?10

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

share|improve this answer
add comment

TI-BASIC, 6 bytes

:Disp randIntNoRep(1,10
share|improve this answer
add comment

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.

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

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 at 16:02
add comment

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

share|improve this answer
add comment

q/kdb [6 chars]

-10?10

will generate 10 unique random numbers.

share|improve this answer
add comment

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.

for(a="";!a[9];){b=Math.floor(Math.random()*10);if(!~a.indexOf(b))a+=b}alert(a)
share|improve this answer
add comment

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
add comment

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

share|improve this answer
add comment

Scala, 37

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

Racket 45 43

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

Clojure

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

6209847315

42 bytes

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

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

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
add comment

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);
share|improve this answer
add comment

Your Answer

 
discard

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.