create a function that takes a string as a parameter that returns a seeded random number between 1 and 10 and will always be the same for the seed in swift

Here's how you can create a function in Swift that takes a string as a parameter and returns a seeded random number between 1 and 10:

main.swift
func seededRandomNumberFromString(input: String) -> Int {
    // Set the seed based on the input string
    srand48(input.hashValue)
    
    // Generate a random double between 0 and 1
    let randomNumber = drand48()
    
    // Multiply by 10 and round up to get a number between 1 and 10
    let result = Int(ceil(randomNumber * 10))
    
    return result
}
363 chars
13 lines

Explanation:

  1. srand48 sets the seed based on the hash value of the input string. This ensures that the same input string will always produce the same random number.
  2. drand48 generates a random double between 0 and 1.
  3. ceil rounds up the result of randomNumber * 10 to get a number between 1 and 10.
  4. Finally, the function returns the result.

gistlibby LogSnag