Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,569 questions

56,787 answers

573 users

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

...