How to generate random lottery numbers for 6 numbers out of 37 and 1 power number out of 7 in Swift

1 Answer

0 votes
import Foundation

/*
    This program generates random lottery numbers for:
        - 6 distinct numbers out of 37
        - 1 distinct number out of 7 (power number)

    It uses:
        - Swift's built‑in shuffled() for uniform random permutation
        - Int.random(in:) for the single power number
        - clean functions and idiomatic Swift style
*/

/*
    pickDistinctNumbers(count:max:)

    Returns `count` distinct random numbers from the range 1...max.

    Algorithm:
        - Build an array of all numbers 1...max
        - Shuffle the array using shuffled()
        - Take the first `count` numbers

    This guarantees:
        - all numbers are unique
        - uniform randomness
        - no duplicate checks needed
*/
func pickDistinctNumbers(count: Int, max: Int) -> [Int] {
    Array(1...max)
        .shuffled()        // Fisher–Yates under the hood
        .prefix(count)
        .sorted()
}

/*
    pickPowerNumber(max:)

    Returns a single random number in the range 1...max.
*/
func pickPowerNumber(max: Int) -> Int {
    Int.random(in: 1...max)
}

/*
    Main program entry point
*/

let mainCount = 6
let mainMax   = 37
let powerMax  = 7

// Generate main numbers (distinct)
let mainNumbers = pickDistinctNumbers(count: mainCount, max: mainMax)

// Generate power number
let powerNumber = pickPowerNumber(max: powerMax)

// Output results
print("Main numbers (6 out of 37): \(mainNumbers.map(String.init).joined(separator: " "))")
print("Power number (1 out of 7): \(powerNumber)")


/*
run:

Main numbers (6 out of 37): 4 10 21 22 29 32
Power number (1 out of 7): 3

*/

 



answered Jul 28 by avibootz

Related questions

...