DC39 DC39 - 2 months ago 15
Swift Question

How can I never repeat a already generated random number?

How do you make it so that a random generated number in an arc4random() set is never repeated. For example, in arc4random(100) in 1 is chosen, it will never be brought up again.

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var card: UIImageView!

@IBOutlet weak var nextButton: UIButton!


override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}




@IBAction func nextCardTapped(sender: UIButton) {



//Edit number of cards here for the random card to show up
var randomCard = arc4random_uniform(100)
// Edit number of cards here for the random card to show up


var randomCardString:String = String(format: "card%i", randomCard)


self.card.image = UIImage(named: randomCardString)

Answer

Xcode 8 • Swift 3

extension Array {
    var shuffled: Array {
        var elements = self
        return elements.shuffle()
    }
    @discardableResult
    mutating func shuffle() -> Array {
        indices.dropLast().forEach { a in
            guard case let b = Int(arc4random_uniform(UInt32(count - a))) + a, b != a else { return }
            swap(&self[a], &self[b])
        }
        return self
    }
}

usage

let numbers = Array(1...100)

let shuffled = numbers.shuffled   // [5, 60, 15, 13, 94, 70, 17, 80, 95, 11, 76, 55, 96, 45, 1, 4, 23, 97, 48, 21, 47, 38, 51, 64, 59, 44, 19, 79, 98, 61, 35, 67, 49, 71, 83, 82, 54, 69, 36, 100, 73, 99, 93, 6, 62, 91, 24, 32, 10, 31, 41, 84, 46, 72, 12, 87, 20, 65, 43, 22, 85, 68, 86, 89, 88, 58, 33, 18, 30, 63, 52, 90, 57, 14, 16, 81, 2, 29, 37, 8, 50, 78, 9, 66, 3, 7, 77, 53, 39, 56, 28, 42, 25, 27, 34, 92, 26, 74, 75, 40]

let get10randomNumbers = numbers.shuffled.prefix(10)   // [71, 23, 33, 48, 73, 81, 75, 18, 19, 67]