create a seeded random number generator in swift

To create a seeded random number generator in Swift, you can use the arc4random function along with a seed value.

Here's an example of how to create a seeded random number generator:

main.swift
func seededRandom(seed: UInt32) -> CGFloat {
    srand48(Int64(seed))
    return CGFloat(drand48())
}

// Usage:
let random1 = seededRandom(seed: 123)
let random2 = seededRandom(seed: 123)
let random3 = seededRandom(seed: 456)

print(random1) // 0.28771346272508
print(random2) // 0.28771346272508
print(random3) // 0.783604173762871
334 chars
14 lines

In this function, we use the srand48 function to seed the random number generator with the given seed value. Then, we use drand48 to generate a random number between 0 and 1. Finally, we return the random number as a CGFloat.

You can use this function to generate consistent and predictable random numbers based on a seed value, which can be useful for testing, debugging, or generating procedural content.

gistlibby LogSnag