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
Will Seith
2,742 PointsNon-repeating random number from GameKit
Hi,
I just completed "Build a Simple iPhone App with Swift 2.0" course and am trying to play around with the color model in that tutorial:
import UIKit import GameKit
struct ColorModel { let colors = [ UIColor(red: 90/255.0, green: 187/255.0, blue: 181/255.0, alpha: 1.0), //teal color
UIColor(red: 222/255.0, green: 171/255.0, blue: 66/255.0, alpha: 1.0), //yellow color
UIColor(red: 223/255.0, green: 86/255.0, blue: 94/255.0, alpha: 1.0), //red color
UIColor(red: 239/255.0, green: 130/255.0, blue: 100/255.0, alpha: 1.0), //orange color
UIColor(red: 77/255.0, green: 75/255.0, blue: 82/255.0, alpha: 1.0), //dark color
UIColor(red: 105/255.0, green: 94/255.0, blue: 133/255.0, alpha: 1.0), //purple color
UIColor(red: 85/255.0, green: 176/255.0, blue: 112/255.0, alpha: 1.0), //green color ]
func getRandomColor() -> UIColor {
let randomNumber = GKRandomSource.sharedRandom().nextIntWithUpperBound(colors.count)
return colors[randomNumber]
}
}
Can anyone tell me how I can replace GKRandomSource in the ColorModel and in the ViewController so that random, non-repeating colors come up? Seeing colors repeat when you press the button multiple times just feels off.
Thanks
1 Answer
ianhan3
4,263 PointsIf you still want it infinite you can basically make sure it won't repeat until you reset the array. You could call arc4random w/ the array.count value and remove the index of the random number forcing the count down until it was empty then just in your function check if array.isEmpty == true you reset the color values.
Something like this:
let resetColorArray = [UIColor.whiteColor(), UIColor.blueColor(), UIColor.blackColor()]
var colorArray = resetColorArray
func randomColorNonRepeating() -> UIColor {
if colorArray.isEmpty {
colorArray = resetColorArray
}
let number = Int(arc4random_uniform(UInt32(colorArray.count)))
let color = colorArray[number]
colorArray.removeAtIndex(number)
return color
}
You could add more to, when the array is empty, check the last returned color (you could save it in a class level variable) and make sure it is not the same color to further prevent any repeating colors but this will get you a guarantee it won't repeat in however many colors you have in your array.