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 yesterday
2  
Generally, it's good idea to allow any language, according to code-golf description. –  xfix yesterday
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 11 hours ago
1  
Yes, @marinus has a 4 byte solution (mine is 6 bytes) –  Timtech 10 hours ago
2  
-1 The selection of the winner is improper, given that this was a code-golf challenge. –  David Carraher 9 hours ago
show 7 more comments

27 Answers

up vote 23 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
1  
+1 I think I may have to try something slightly more terse than Python to beat this. –  Joachim Isaksson 18 hours ago
 
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 18 hours ago
 
@DavidCarraher: yes. It selects 10 non-repeating random numbers from the interval [0..10), so that basically means a random permutation of '0123456789'. –  marinus 17 hours ago
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 16 hours ago
 
@DavidCarraher It's an array. –  swish 13 hours ago
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 23 hours ago
 
If OP would have asked specifically for the number not an array, you should convert it to base10 number also, with 10#. –  swish 19 hours ago
add comment

Ruby, 22

$><<[*0..9].shuffle*''
share|improve this answer
 
You may shorten (0..9).to_a to [*0..9]. –  Howard 23 hours ago
 
Done and done, sir. Thanks! –  Darren Stone 23 hours ago
 
You're welcome. But why do you not use [*0..9].shuffle in the first place? –  Howard 23 hours ago
 
@Howard, because it's late and I'm dumb. :) Thanks! –  Darren Stone 23 hours ago
 
this return array with number not number –  Monk_Code 21 hours ago
show 2 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 23 hours ago
 
@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 23 hours ago
 
You can save a few more characters by sampling from the string "0123456789" rather than using range and them mapping str. –  Blckknght 10 hours ago
 
@Blckknght Thanks, updated with your suggestion :) –  Joachim Isaksson 9 hours ago
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 of Snow 10 hours ago
 
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 8 hours ago
 
@IlmariKaronen I know, but the question didn't say anything about uniform distribution. –  Howard 41 mins ago
add comment

Perl 6 (18 characters)

say [~] pick *,^10

This generates array containing all random elements (pick *) from 0 to 9 (^10), concatenates them ([~] is reduce concatenation operator), and outputs the result (say).

Sample output:

$ perl6 -e 'say [~] pick *,^10'
4801537269
$ perl6 -e 'say [~] pick *,^10'
1970384265
$ perl6 -e 'say [~] pick *,^10'
3571684902
share|improve this answer
 
+1 I think you don't need the whitespace before pick. –  Howard yesterday
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 yesterday
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

PHP - 39 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 22 hours ago
 
@xfix Thanks, I'll fix. :) –  Trimsty 22 hours ago
 
You don't even need the <?= and ?>. It's valid PHP code without those. –  Jeremy 14 hours ago
 
@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 14 hours ago
1  
@Jeremy Ah, PHP, where non-embedded implementations besides a terminal are scarce. :P –  Trimsty 14 hours ago
show 3 more comments

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

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 16 hours ago
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 15 hours ago
 
Thanks for the head's up... @manatwork :) –  Vijaykumar Hadalgi 5 hours ago
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 17 hours ago
 
@Rik Thanks updated! –  JMK 17 hours ago
add comment

Mathematica, 27

Row@RandomSample@Range[0,9]

enter image description here

share|improve this answer
 
Nice way to avoid strings! –  David Carraher 16 hours ago
add comment

JavaScript, 90 characters

EDIT: Thanks to Rob W, code length is reduced to to 90 characters.

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

New version (90 characters):

a="0123456789".split(t=""),l=11;while(--l)t+=a[r=0|Math.random()*l],a.splice(r,1);alert(t)

JSFiddle: http://jsfiddle.net/gthacoder/ZAJsT/.

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 15 hours ago
 
@RobW Thanks for the tips. I updated my answer. P.S. I guess you meant Math.floor(x) === 0|x. –  gthacoder 14 hours ago
1  
This always has 9 at the end. To fix, initialize l=11 and switch your while loop condition to while(--l) –  Greg 14 hours ago
 
@Greg Good point. Thank you. I updated the answer. –  gthacoder 14 hours ago
 
I like how you took an in-place (fisher-yates) shuffle algorithm and made it shorter by creating a new string to hold the shuffled data. –  Greg 14 hours ago
show 2 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 16 hours ago
 
"0123456789".split("") vs [0,1,2,3,4,5,6,7,8,9] saves one characters. –  Prinzhorn 16 hours ago
 
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 14 hours ago
add comment

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 18 hours ago
 
According to the OP, the program "must be able to generate all permutations of all allowable characters". –  David Carraher 18 hours ago
 
@Ankush That's infix notation, so "0" is not always the first char. –  Ajasja 16 hours ago
 
Ajasja is correct. The program can generate any permutation. I added some remarks above to clarify this. –  David Carraher 16 hours ago
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

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

Shell/Coreutils, 23

shuf -i0-9|paste -sd ''
share|improve this answer
add comment

F#, 71 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 _->System.Guid.NewGuid())|>Seq.iter(printf "%d")
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

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

Scala, 37

util.Random.shuffle(0 to 9).mkString
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

Racket 45 43

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

php

function gen_uid() {
$random_id_length = 10;
$rnd_id = crypt(uniqid(rand(),1));
$rnd_id = strip_tags(stripslashes($rnd_id));
$rnd_id = str_replace(".","",$rnd_id);
$rnd_id = strrev(str_replace("/","",$rnd_id));
$rnd_id = substr($rnd_id,0,$random_id_length);
$rnd_id = strtoupper($rnd_id);
return $rnd_id;
}
$file_uid = gen_uid();

this will make you get 10 characters like tah

1UOOPDIQBA

you can increase the number of charckrs by changeing his value

$random_id_length = 10;
share|improve this answer
1  
This does not print a random 10 character number consisting of all the digits from 0-9 eg "0956327148". Since this is code-golf number of bytes should be mentioned in the post. –  Sylwester 10 hours ago
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.