ruby - One-liner to generate Powerball picks in Swift? -
with u.s.'s large $1.5 billion lottery week, wrote function in ruby make powerball picks. in powerball, choose 5 numbers range 1..69 (with no duplicates) , 1 number range 1..26.
this came with:
def pball array(1..69).shuffle[0..4].sort + [rand(1..26)] end it works creating array of integers 1 69, shuffling array, choosing first 5 numbers, sorting those, , adding on number 1 26.
to in swift takes bit more work since swift doesn't have built-in shuffle method on array.
this 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 no shuffle method, works creating [int] values in range 1...69. uses map create [(int, double)], array of tuple pairs contain numbers , random double in range 0.0 ..< 1.0. sorts array using double values , uses second map return [int] , uses slice [0...4] extract first 5 numbers , sort() sort them.
in second line, appends number in range 1...26. tried adding first line, swift gave error:
expression complex solved in reasonable time; consider breaking expression distinct sub-expressions.
can suggest how turn 1-line function? perhaps there better way choose 5 numbers 1...69.
for fun of it, non-gameplaykit (long) one-liner swift 3, using global sequence(state:next:) function generate random elements mutable state array rather shuffling array (although mutating value array 5 times, copy operations here...)
let powerballnumbers = array(sequence(state: array(1...69), next: { (s: inout [int]) -> int? in s.remove(at: int(arc4random_uniform(uint32(s.count))))}) .prefix(5).sorted()) + [int(arc4random_uniform(26) + 1)] ... broken down readability.
(possible in future swift version)
if type inference weren't broken inout closure parameters (as arguments closures), reduce above to:
let powerballnumbers = array(sequence(state: array(1...69), next: { $0.remove(at: int(arc4random_uniform(uint32($0.count)))) }) .prefix(5).sorted()) + [int(arc4random_uniform(26) + 1)] if we'd allow following extension
extension int { var rand: int { return int(arc4random_uniform(uint32(exactly: self) ?? 0)) } } then, go on reduce one-line to:
let powerballnumbers = array(sequence(state: array(1...69), next: { $0.remove(at: $0.count.rand) }).prefix(5).sorted()) + [26.rand + 1]
Comments
Post a Comment