Create a gist now

Instantly share code, notes, and snippets.

@mattt /random.swift
Last active May 25, 2016

What would you like to do?
import Darwin
extension Int {
static func random() -> Int {
return Int(arc4random())
}
static func random(range: Range<Int>) -> Int {
return Int(arc4random_uniform(UInt32(range.endIndex - range.startIndex))) + range.startIndex
}
}
extension Double {
static func random() -> Double {
return drand48()
}
}

A RandomInstance (or Arbitrary) protocol would be nice, which would mean any type could implement a random method to get a random instance of the type (useful for things like quick check).

rparada commented Jan 3, 2015

Here are some you can add to shuffle array elements using your extension for random number generation.

extension Array {
    /**
     * Shuffles the array elements.
     */
    mutating func shuffle() {
        if count > 1 {
            let iLast = count - 1
            for i in 0..<iLast {
                let iRandom = Int.random(i...iLast)
                let temp = self[i]
                self[i] = self[iRandom]
                self[iRandom] = temp
            }
        }
    }

    /**
     * Returns a copy of the array with the elements shuffled.
     */
    func shuffled() -> [T] {
        var newArray = [T](self)
        newArray.shuffle()
        return newArray
    }
}

lchenay commented Jul 8, 2015

If someone use this code, replace return Int(arc4random()) by `return Int(arc4random_uniform(UInt32(Int.max)))``
arc4random() return UInt32 from 0 to UInt32.max. Not all the range are compatible with Int and will result in a EXC_BAD_INSTRUCTION

@lchenay is right

MatrixSenpai commented May 25, 2016

Note iLast can be left out in favor of ..<count.
Same in Int.random(i..<count).
Also note [T] is deprecated in favor of [Element]
For sets

extension Set {
    mutating func shuffle() {
        if count > 1 {
            for i in 0..<count {
                let r = Int.random(i..<count)
                let temp = self[self.startIndex.advancedBy(r)]
                self.removeAtIndex(self.startIndex.advancedBy(r))
                self.insert(temp)
            }
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment