With the U.S.'s large $1.5 Billion lottery this week, I wrote a function in Ruby to make Powerball picks. In Powerball, you choose 5 numbers from the range 1..69
(with no duplicates) and 1 number from the range 1..26
.
This is what I came up with:
def pball
Array(1..69).shuffle[0..4].sort + [rand(1..26)]
end
It works by creating an array of integers from 1 to 69, shuffling that array, choosing the first 5 numbers, sorting those, and finally adding on a number from 1 to 26.
To do this in Swift takes a bit more work since Swift doesn't have the built-in shuffle
method on Array
.
This was my attempt:
func pball() -> [Int] {
let arr = Array(1...69).map{($0, drand48())}.sort{$0.1 < $1.1}.map{$0.0}[0...4].sort()
return arr + [Int(arc4random_uniform(26) + 1)]
}
Since there is no shuffle
method, it works by creating an [Int]
with values in the range 1...69
. It then uses map
to create [(Int, Double)]
, an array of tuple pairs that contain the numbers and a random Double
in the range 0.0 ..< 1.0
. It then sorts this array using the Double
values and uses a second map
to return to [Int]
and then uses the slice [0...4]
to extract the first 5 numbers and sort()
to sort them.
In the second line, it appends a number in the range 1...26
. I tried adding this to the first line, but Swift gave the error:
Expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions.
Can anyone suggest how to turn this into a 1-line function? Perhaps there is a better way to choose the 5 numbers from 1...69
.