# Choose The Powerball Numbers!

Powerball is an American lottery that has recently gained attention because the current jackpot (as of January 11, 2016) is the largest lotto prize in history, at about \$1.5 billion (USD).

Powerball players choose 5 distinct numbers from 69 numbered white balls, and 1 one "Powerball" number from 26 numbered red balls. They win the jackpot if their five white ball choices match what was drawn in any order, and if they chose the correct "Powerball" number.

So the chances of winning the jackpot are 1 in `(69 choose 5)*(26 choose 1)` or `((69*68*67*66*65)/(5*4*3*2*1))*26`, which is 1 in 292,201,338

No one won the jackpot in the most recent drawing on January 9, 2016, but perhaps someone will win the next drawing on January 13, 2016, 10:59 pm ET.

# Challenge

Write a program or function that simulates a Powerball drawing, taking no input but outputting 5 distinct random numbers from 1 to 69 inclusive, and then one random "Powerball" number from 1 to 26 inclusive (which could be a repeat of one of the 5 initial numbers).

The "Powerball" number should always be the last number in the output, but otherwise the order of the first 5 numbers does not matter.

The 6 numbers should be output in decimal, either space separated or newline separated, with an optional single trailing newline. Commas, brackets, and other characters are not allowed in the output.

So these would be valid outputs (using the numbers from the last drawing):

``32 16 19 57 34 13``
``````32
16
19
57
34
13``````

All 292201338 possible outcomes should be possible with uniform probability. You may use built-in pseudo-random number generators and assume they meet this standard.

Here is an ungolfed reference implementation that works in Python 2 or 3:

``````import random
print(' '.join(map(str, random.sample(range(1,70), 5) + [random.randint(1, 26)])))
``````

The shortest code in bytes wins.

Note that I have no affiliation with Powerball and don't really suggest that you play. But if you win anything from numbers generated by one of the programs here, I'm sure we'd love to hear about it. :D

-
Missed opportunity to demand a share of the winnings should someone here get the jackpot. – Alex A. Jan 12 at 3:07
Do the 5 numbers have to be in order? – Neil Jan 12 at 13:37
@Neil "The "Powerball" number should always be the last number in the output, but otherwise the order of the first 5 numbers does not matter." – Helka Homba Jan 12 at 13:39
I'm sure no one is confused, but you actually mean integers in the challenge. – jpmc26 Jan 12 at 14:40
@CanadianLuke The order of the first 5 numbers does not matter. There are `5! = 5*4*3*2*1` ways to arrange 5 things, so you factor that out. – Helka Homba Jan 14 at 0:09

## Dyalog APL, 10 bytes

``````(5?69),?26
``````

Dyadic `?` is ⍺ distinct random numbers in [1,⍵], and monadic `?` is a single random number.

Try it here.

-
Almost identical in J except you have to add 1 because of the 0 based indexing: `1+(5?69),?26`. – randomra Jan 12 at 13:30

## CJam, 16 bytes

``````69,mr5<26mr+:)S*
``````
``````69,   range(69)
mr    shuffle the generated array
5<    first 5 elements
26mr  random number 0..25
+     concat to array
:)    increment each array element
S*    join with spaces
``````

Try it online.

-
I like how `:)` makes things just a little bigger, like how a stranger's smile can make you just a little happier. – QPaysTaxes Jan 12 at 17:30
I think I'd be pretty `:)` if I won the lottery. +1 – A Nerd - I Jan 12 at 19:59

# MATL, 10 bytes

``````69 5Zr26Yr
``````

Uses current version (9.2.0) of the language/compiler.

### Example

With compiler run on Matlab:

``````>> matl
> 69 5Zr26Yr
>
66
59
64
56
29
12
``````

With compiler run on Octave:

``````>> matl
> 69 5Zr26Yr
>
2 69 41 44 23
22
``````

The first five numbers are separated by space, not by newline. This is due to Octave's underlying `randsample` function behaving differently from Matlab's (and has been corrected in a new version of the compiler). Anyway, newline and space are both allowed by the challenge.

Edit (April 4, 2016): Try it online!

### Explanation

``````69 5Zr    % randsample(69,5), without replacement by default. Gives a 5x1 column vector
26Yr      % randi(26). Gives single number
% implicit display
``````

See relevant Matlab functions: `randsample` and `randi`.

-

# Ruby, 33 32

``````p *[*1..69].sample(5),rand(26)+1
``````

Ruby happens to have a built-in method, sample, that selects random values from an array without replacement. Thanks to QPaysTaxes for pointing out that I don't need the parens.

-
Are you sure you need the parentheses? I think you could trim off a byte by dropping ten and having a space between p and *. I'm checking now. EDIT: tested and AFAICT it works. – QPaysTaxes Jan 13 at 4:32
Ha, it does, thank you. I'd been testing in an irb instance where I'd assigned to `p` at some point, which actually breaks the syntax parsing for that version. – histocrat Jan 13 at 13:31

# R, 30 29 bytes

``````cat((s=sample)(69,5),s(26,1))
``````

The `sample` function performs simple random sampling from the input. If a single integer is given as the first argument, sampling is done from 1 to the argument. The sample size is the second argument. We're employing the default option of sampling without replacement.

Try it online

-
you can save two whole bytes by using `c` instead of `cat` – Dean MacGregor Jan 13 at 18:01
@DeanMacGregor Thanks for the suggestion, but submissions here must be either full programs that write to STDOUT or functions that return a value. In this case I've opted for the former. If I were to use `c`, this would only be a snippet, which isn't allowed by default. – Alex A. Jan 13 at 18:12
Ahh I see. I'm not an avid golfer so I wasn't familiar with that. – Dean MacGregor Jan 13 at 18:14
@DeanMacGregor No problem. Thanks anyway for the suggestion. :) – Alex A. Jan 13 at 18:28

## Python 3.5, 63 bytes

``````from random import*
print(*sample(range(1,70),5),randint(1,26))
``````

It's basically the reference implementation golfed. Note that 3.5 is necessary to splat in a non-last argument.

-

# Octave, 35 32 bytes

Calvin's Hobbies confirmed that `ans =` was OK when using a function, so:

``````@()[randperm(69)(1:5),randi(26)]
``````

It has similarities to Memming's answer, but it uses direct indexing that's only possible in Octave, and it's 5 7 bytes shorter, so I figured it was worth posting anyway.

`randperm(69)` creates a list with a random permutation of the numbers 1-69. It's possible to directly index the list (not possible in MATLAB) to only get the first 5 numbers like this `(1;5)`. The list is followed by `randi(26)` which returns a single number between 1 and 26.

Old:

``````disp([randperm(69)(1:5),randi(26)])
``````

The resulting list is displayed using `disp`.

-

## PowerShell v2+, 31 27 bytes

``````1..69|Random -c 5;Random 27
``````

Requires version 2 or newer, as `Get-Random` wasn't present in v1 (the `Get-` is implied, and `-Maximum` is positional). Output is newline separated.

### Ungolfed:

``````Get-Random -InputObject (1..69) -Count 5
Get-Random -Maximum 27
``````
-
+1 for Powershell. – BigHomie Jan 13 at 16:48
`Random -ma 27` can just be `Random 27` as `-Maximum` is matched by position 0 – Matt Mar 18 at 15:37
@Matt Thanks - I forgot that. – TimmyD Mar 18 at 15:44

# Shell + coreutils, 31

``````shuf -i1-69 -n5
shuf -i1-26 -n1
``````
-

## MATLAB, 40

``````x=randperm(69);disp([x(1:5) randi(26)])
``````

I know. It's the boring solution.

-

## PHP, 69 bytes

``````<?foreach(array_rand(range(1,69),5)as\$k)echo\$k+1," ";echo rand(1,26);
``````

Pretty straight forward answer. Generate a 1-69 `range`, then use `array_rand` to grab 5 random keys from the array, and echo out the `\$k+1` value (0-indexed), then echo a random int from 1-26.

-

## C#, 153 bytes 140 bytes

Thanks to "McKay":

``````string.Join(" ",Enumerable.Range(1,69).OrderBy(e=>Guid.NewGuid()).Take(5).Concat(Enumerable.Range(1,26).OrderBy(e=>Guid.NewGuid()).Take(1)))
``````

153 bytes solution:

``````string.Join(" ",Enumerable.Range(1,69).OrderBy(e=>Guid.NewGuid()).Take(5))+" "+string.Join(" ",Enumerable.Range(1,26).OrderBy(e=>Guid.NewGuid()).Take(1))
``````

Simple solution using Linq and shuffling using GUID.

-
Don't need the string join in the powerball number portion and you'd save bytes either caching the order by delegate or a lot more by using random for the powerball number – pinkfloydx33 Jan 12 at 17:50
And if you concat the sequences instead of string concatenation, you don't need to specify the space3 times, it would be more efficient as well. e.g. `string.Join(" ", ....take(5).Concat(....Take(1)))` – McKay Jan 12 at 18:49

# Pyth - 1314 13 bytes

Major golfing possible, this was just a FGITW.

``````jb>5.SS69hO26
``````
-
Could you explain the code so it can be checked that it's really uniform? – Albert Masclans Jan 12 at 8:07
You can change the `<... 5` to `>5...`. Final code `jb>5.SS69hO26` – muddyfish Jan 13 at 19:54
@muddyfish thanks! – Maltysen Jan 13 at 19:59

# Brachylog, 40 bytes

``````1:5e,68{I`random(I)+1=Z`Z=w,"
"w}\;25:1&
``````

### Explanation

Brachylog doesn't have a built-in for random numbers (yet...) so we have to use an SWI-Prolog predicate for that: `random/1`. We can input SWI-Prolog code in Brachylog using backquotes.

``````1:5e,                             \  § Enumerate from 1 to 5 using \ (backtrack), which
§ evaluates to false and thus constructs a loop

68{                         }   § Declare sub-predicate 1 and call it with 68 as input

I`random(I)+1=Z`             § Z is the arithmetic expression 'random(I) + 1' where
§ I is the input of the sub-predicate

Z=w,         § Evaluate Z and write it
"\n"w    § Write a new line

;                                    § Else (we will reach this after the 5th iteration of
§ the enumeration, since \ is always false)

25:1&                                § Call the sub-predicate 1 with 25 as input
``````
-

# JavaScript (ES6), 10686 84 bytes

``````F=(s=new Set,r=Math.random)=>s.size<5?F(s.add(r()*69+1|0)):[...s,r()*26|0+1].join` `
``````

Since we can't uniquely sample randoms in JavaScript, this works by creating a Set (which only holds unique values), recursively adding randoms (1-69) until there are 5 unique ones, appending a random number (1-26), then joining and returning it all out.

-

# Elixir, 83 Bytes

``````Enum.reduce Enum.take_random(1..69,5)++[Enum.random(1..26)],fn(x,a)->"#{a} #{x}"end
``````

When just `IO.puts`ing an array of integers, Elixir will interpret the integers as characters and therefore output some string instead of the desired powerball numbers. So, we have to reduce the integer array down to a string.

-

### Ruby, 4743 39 bytes

``````puts *(1..69).to_a.sample(5),rand(26)+1
``````

I think it can be golfed more, but I'll work on that once I'm done admiring how pretty this code looks, considering.

It works pretty much the same way as everything else: Take an array of the numbers 1 to 69, shuffle them, get the first five, output those, then output a random number between 1 and 26.

I went through a few iterations before posting this:

``````puts (1..69).to_a.shuffle.first(5).join(' ')+" #{rand(26)+1}"  #61
puts (1..69).to_a.shuffle[0..5].join(' ')+" #{rand(26)+1}"     #58
puts (1..69).to_a.shuffle[0..5].join('<newline>'),rand(26)+1   #52
puts *('1'..'69').to_a.shuffle[0..5],rand(26)+1                #47
puts *('1'..'69').to_a.sample(5),rand(26)+1                    #43
``````

(where `<newline>` is replaced with an actual newline)

EDIT: Whoops, didn't see the preexisting Ruby answer. I stumbled on `sample` and was scrolling down to edit my answer, but then I saw it... Oh well. My final score is 43 bytes, but I'll keep golfing a little to see how well I can do.

-

# Mathematica, 64 bytes

``````StringRiffle@Append[Range@69~RandomSample~5,RandomInteger@25+1]&
``````

Quite simple.

-
The output has braces and commas. – Charles Jan 12 at 16:35
-1 invalid for above reason – CalculatorFeline Apr 16 at 20:01
`StringJoin`=`""<>##&` – CalculatorFeline Apr 18 at 2:44
@CatsAreFluffy Actually fixed this time. Just mixed up my functions... – LegionMammal978 Apr 18 at 10:09
I think you could shorten it if you only use Range/RandomSample and transposed it over two lists instead of using RandomInteger. Something like RandomSample[Range[#1],#2]&@@@{{69,5},{26,1}}] – Xanderhall Apr 19 at 11:29

# Perl 5, 59 bytes

``````{say for(sort{-1+2*int rand 2}1..69)[0..5];say\$==1+rand 25}
``````

It's a subroutine; use it as:

``````perl -M5.010 -e'sub f{...}f'
``````
-
You can use `-E` instead of `-M5.010 -e` – andlrc Jan 13 at 1:05
Cant you can replace `-1+2*int rand 2` with `rand>.5?1:-1`? – andlrc Jan 13 at 1:07
And shouldn't you be able to save another few by replacing `;say\$==` with `,\$==` – andlrc Jan 13 at 1:12
@dev-null Thanks! The `-M5.010` doesn't count anyway so I didn't bother abbreviating it. I think I tried a comma instead of another `say` and it didn't work. But the new sort rule is a good idea, thanks. I'll test it when I have a chance and edit it in. – msh210 Jan 13 at 3:31

## PHP, 65 bytes

``````<?=join(' ',array_rand(array_flip(range(1,69)),5))." ".rand()%26;
``````

Thanks to the other PHP answer on this page. I wrote up a program on my own, and it turned out to be the exact same answer as the one written by Samsquanch, which drove me to take it a step further to save a few bytes.

If anyone can figure out a way to append one array to another in here that's less than the 5 bytes it takes me to join the powerball number on after, I would greatly appreciate it, cause it's driving me nuts! The best I could come up with would be after `array_rand` and before `join`, having a statement something like `+[5=>rand()%25]`, but that's an extra byte over just concatenating it on after.

``````<?=                                                              // This represents an inline 'echo' statement
range(1,69)                    // Get an array of all numbers from 1 to 69 inclusive
array_flip(           )                   // Swap the keys and values.
array_rand(                       ,5)                // Get a random subset of five keys.
join(' ',                                     ).rand()%26     // Concatenate the array with spaces, along with the powerball number
``````

Run it through the command line. Sample:

``````C:\(filepath)>php powerball.php
``````

Output:

`````` 12 24 33 67 69 4
``````
-

## PARI/GP, 71 70 bytes

``````apply(n->print(n),numtoperm(69,random(69!))[1..5]);print(random(26)+1)
``````

It generates a random permutation of [1..69], then takes the first 5.

Unfortunately this is an inefficient user of randomness, consuming an average of 87 bytes of entropy compared to the information-theoretic ideal of 3.5. This is mainly because the entire permutation is generated instead of just the first 5 members, and also because the perms are ordered (losing lg 5! =~ 7 bits). Further, `random` uses a rejection strategy rather than using arithmetic coding. (This is because PARI uses Brent's xorgen, which is fast enough that the overhead from more complicated strategies is rarely worthwhile.)

There are three 'obvious' changes which do not work under the current (2.8.0) version of gp. `random` and `print` could be stored in variables, and `print` could be called directly rather than via the anonymous `->` function:

``````r=random;apply(p=print,numtoperm(69,r(69!))[1..5]);p(r(26)+1)
``````

Together these would save 9 bytes. Unfortunately both functions are valid without arguments, and hence are evaluated immediately rather than stored, so these do not compute the desired output.

-

## Intel x86 Machine code, 85 bytes

``````¿I ±‰ø1Ò»E ÷óB‰Ðè+ ‰þÑç÷ƒÇþÉ„Éuâ‰ø1Ò» ÷óB‰Ðè
0äÍ¸ Í±ëÆÔ
00†Äˆã´ÍˆØÍ° ÍÃ
``````

Well it does sometimes print the same numbers if so, just try again by pressing a key.

Compile with:

``````nasm file.asm -o file.bin
``````

Make sure to align it to a floppy size (add zeros at the end) in order to mount it to a vm (it does not need any operating system).

Disassembly:

``````BITS 16
ORG 0x7c00

mov di,73 ;starting seed
mov cl,5 ;we need five numbers

loop:

mov ax,di

xor dx,dx
mov bx,69
div bx
inc dx
mov ax,dx

call print_rnd_number

mov si,di
shl di,1

dec cl

test cl,cl
jne loop

mov ax,di

xor dx,dx
mov bx,26
div bx
inc dx
mov ax,dx

call print_rnd_number

xor ah,ah
int 0x16
mov ax,0x0002
int 0x10
mov cl,5
jmp loop

print_rnd_number:
aam
xchg al,ah
mov bl,ah
mov ah,0x0E
int 0x10
mov al,bl
int 0x10
mov al,' '
int 0x10
ret
``````
-
Welcome to Programming Puzzles & Code Golf! Seeing machine code is always impressive, but if it prints repeated numbers on occasions, I'm afraid your submission is invalid. – Dennis Jan 12 at 19:21
Yes it is but I just wanted to share this :) – ByteBit Jan 12 at 20:00
I understand, but we recently discussed this, and the community's consensus was that invalid answers should either be fixed or removed. – Dennis Jan 12 at 20:24
I'll undownvote if you fix; please ping me. – lirtosiast Jan 13 at 23:33

# C, 142 bytes

``````i,x[6],n;main(j){for(srand(time(0));i<6;n-i?0:printf("%d ",x[i]),i++)for(x[n=j=i]=(69-i/5*43)*(rand()/2147483647.)+1;i<6&&j--;)i-=x[i]==x[j];}
``````

Not terribly happy with this solution as it feels like there should be more golfing opportunity. I'll look at it again tomorrow with fresh eyes. Try it here.

-

# Swift, 165 bytes

``````import UIKit;var a=[Int]();for i in 0...5{func z()->Int{return Int(arc4random_uniform(i<5 ?68:25)+1)};var n=z();while i<5&&a.contains(n){n=z()};a.append(n);print(n)}
``````

Can quickly be run in an Xcode Playground.

EDIT: Current problem here is that it's theoretically possible for this to run forever in the while loop if arc4random_uniform somehow keeps pulling the same number. The odds of that happening, for any significant length of time, are probably better than the odds of winning the Powerball.

-
How does it guarantee that there won't be any duplicated values? – supercat Jan 13 at 21:29
@supercat, it didn't before, but now it does. – timgcarlson Jan 13 at 23:17

# Perl 6,  32  31 bytes

``````# space is necessary so that the parens denote a list
# rather than being part of the call to `put`
put (pick(5,1..69),(1..26).pick) # 32 bytes
# 25 35 57 67 62 24␤
``````

Turning it into a function that returns a string, I can remove 4 bytes (`put␠`) while only adding 3 (`{~` `}`)

``````{~(pick(5,1..69),(1..26).pick)} # 31 bytes
``````

Usage:

``````say {...}().perl; # use .perl to prove it returns a string
# "25 35 57 67 62 24"
``````

### If a function were allowed to return a list of the values, the following would also work.

( Otherwise it would be the same as above but within `{ }` )

• function that returns a single flat list

``````{|pick(5,1..69),(1..26).pick} # 29 bytes
# (25,35,57,67,62,24)
``````
• function that returns a list with the first 5 numbers in a sub list

``````{pick(5,1..69),(1..26).pick} # 28 bytes
# ((25,35,57,67,62),24)
``````
• function that returns a list with the first 5 in a sub list, and the Powerball in another sub list

``````{pick(5,1..69),pick 1,1..26} # 28 bytes
# ((25,35,57,67,62),(24,))
``````
-

# Seriously, 35 bytes

My first attempt at an answer in a golfing language.

Feels longer than it should have to be.
The repetition could likely be removed with W, but it seems to be broken in the online interpreter and I don't want to post untested code.

Too bad { doesn't work on lists.

Code:

``````:70:1xi J{. J{. J{. J{. J{.:26:Ju.
``````

Hex dump:

``````3a37303a317869204a7b2e204a7b2e204a7b2e204a7b2e204a7b2e3a32363a4a752e7f
``````

Explanation:

``````:70:1x                       # Push a list of the numbers 1-69
i                            # Explode list
J{.                         # rotate stack random(len(stack)) times and pop/print
J{. J{. J{. J{.             # same thing 4 more times
:26:Ju.                      # print random number in 1-26
# (7F) unprintable, terminate without explicit printing
``````

Online interpreter

-

# Lua, 96 Bytes

A simple solution, using a table as a set by putting the value inside it as `table[value]=truthy/falsy`to be able to check if they are inside it or not.

I lose 5 bytes because I have to set the first value of my table, else I won't go inside the `while(o[n])`loop and will simply output `n` before using the random function. As Lua uses 1-based tables, I also have to force it to put its first value to the cell `[0]`, otherwise I couldn't output a `1`.

``````m,n,o=math.random,0,{[0]=0}for i=1,5 do while(o[n])do n=m(69)end o[n]=0 print(n)end print(m(26))
``````

### Ungolfed:

``````m,n,o=math.random,0,{[0]=0}
for i=1,5
do
while(o[n])
do
n=m(69)
end
o[n]=0
print(n)
end
print(m(26))
``````
-

## C++, 252 bytes

### Golfed:

``````#include<iostream>
#include <random>

int main(){std::random_device rd;std::mt19937 gen(rd());std::uniform_int_distribution<> dis(1,69);for(int c=0;c<=5;c++){std::cout<<dis(gen)<<" ";}int x=dis(gen);while(x>26||x<1){x=dis(gen);}std::cout<<x;return 0;}
``````

### Ungolfed:

``````#include<iostream>
#include <random>

int main()
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 69);
for(int c = 0; c <= 5; c++){
std::cout<<dis(gen)<<" ";
}
int x = dis(gen);
while (x > 26 || x < 1){
x = dis(gen);
}
std::cout<<x;
return 0;
}
``````
-