Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

alec apter
alec apter
929 Points

Help with Custom Random Number Generator

Hey guys, I was wondering if anyone could help me create a random # generator in swift that doesn't repeat the number it just generated n times. Thanks in advance.

1 Answer

Chris Stromberg
PLUS
Chris Stromberg
Courses Plus Student 13,389 Points
import UIKit
import GameKit

enum randomRepeatError : Error {
    case invalidRepeatNumber(description: String)
}

class NumberGenerator {

    var numbersGeneratedArray: [Int] = [Int]()

    func randomNumberNotRepeated(_ times: Int) throws -> Int {

        guard  times >= 1 && times <= 100 else {
            print("!!!ERROR!!! Enter a number greater than 1 and less than 100")
            throw
                randomRepeatError.invalidRepeatNumber(description: "Enter a number greater than 1.")
                        }


        var randomNumberToReturn : Int = 0

        func makeRandomNumber() -> Int {
            return GKRandomSource.sharedRandom().nextInt(upperBound: 100)
        }

        var randomNumber: Int = 0

        var arrayContainsRandomNumber: Bool {
            return numbersGeneratedArray.contains(randomNumber)
        }

         randomNumber = makeRandomNumber()

        if numbersGeneratedArray.count >= times {
            numbersGeneratedArray.remove(at: 0)
            }


        if arrayContainsRandomNumber == true {
            randomNumber = makeRandomNumber()

                repeat { randomNumber = makeRandomNumber() }
                while numbersGeneratedArray.contains(randomNumber)

                numbersGeneratedArray.append(randomNumber)
                randomNumberToReturn = randomNumber
            }

        if arrayContainsRandomNumber == false {
            numbersGeneratedArray.append(randomNumber)
            randomNumberToReturn = randomNumber
            randomNumber = makeRandomNumber()

      }


        print("********************************************)")
        print(numbersGeneratedArray)
        print("The random number is: \(randomNumberToReturn)")


        return randomNumberToReturn

    }

}

Using the randomNumberNotRepeated function...

var number = NumberGenerator()


for i in 1...20 {
   try number.randomNumberNotRepeated(15)
}