ios - I want multiple non-random numbers in swift -
i using swift , want have number of duplicatable patterns throughout game.
ideally have sort of shared class worked sort of (this sort of pseudo-swift code):
class randomnumberutility { static var sharedinstance = randomnumberutility() var random1 : random() var random2 : random() func seedrandom1(seed : int){ random1 = random(seed) } func seedrandom2(seed : int){ random2 = random(seed) } func getrandom1() -> int { return random1.next(1,10) } func getrandom2() -> int { return random2.next(1,100) } }
then, begin series, anywhere in program go this:
randomnumberutility.sharedinstance.seednumber1(7) randomnumberutility.sharedinstance.seednumber2(12)
and know (for example) first 4 times called
randomnumberutility.sharedinstance.getrandom1()
i same values (for example: 6, 1, 2, 6) continue until @ point seeded number again, , either exact same series (if used same seed), or different series (if used different seed).
and want have multiple series of numbers (random1 & random2) @ same time.
i not sure how begin turn actual swift class.
here possible implementation. uses jrand48
pseudo random number generator, produces 32-bit numbers. prng not arc4random()
, has advantage state stored in user-supplied array, multiple instances can run independently.
struct randomnumbergenerator { // 48 bit internal state jrand48() private var state : [uint16] = [0, 0, 0] // return pseudo-random number in range 0 ... upper_bound-1: mutating func next(upper_bound: uint32) -> uint32 { // implementation avoiding "module bias" problem, // taken from: http://stackoverflow.com/a/10989061/1187415, // swift translation here: http://stackoverflow.com/a/26550169/1187415 let range = uint32.max - uint32.max % upper_bound var rnd : uint32 { rnd = uint32(truncatingbitpattern: jrand48(&state)) } while rnd >= range return rnd % upper_bound } mutating func seed(newseed : int) { state[0] = uint16(truncatingbitpattern: newseed) state[1] = uint16(truncatingbitpattern: (newseed >> 16)) state[2] = uint16(truncatingbitpattern: (newseed >> 32)) } }
example:
var rnd1 = randomnumbergenerator() rnd1.seed(7) var rnd2 = randomnumbergenerator() rnd2.seed(12) println(rnd1.next(10)) // 2 println(rnd1.next(10)) // 8 println(rnd1.next(10)) // 1 println(rnd2.next(10)) // 6 println(rnd2.next(10)) // 0 println(rnd2.next(10)) // 5
if rnd1
seeded same value above produces same numbers again:
rnd1.seed(7) println(rnd1.next(10)) // 2 println(rnd1.next(10)) // 8 println(rnd1.next(10)) // 1
Comments
Post a Comment