How do I shift Array to a pseudo-random number?

Asked 2 years ago, Updated 2 years ago, 32 views

I found the following logic as a way to Shuffle Array in Swift.

extension Array {
    mutating func shuffle() {
        for in 0..<(count-1){
            let j = Int(arc4 random_uniform(UInt32(count-i))))) + i
            swap(&self[i], &self[j])
        }
    }
}

For example, what should I do if I want to set the date to Seed and cause randomness?

muting func sshuffle (seed:Int)

What I'm thinking about is how to take Int as seed and shuffle it (in pseudo-random numbers) like this.

追Add
I made the following logic, but what do you think?

muting func sshuffle(seed:Int){
    sland(UInt32(seed))
    letr = land()
    for in 0..<(count-1){
        let j = Int(r%Int32(count-i))+i
        swap(&self[i], &self[j])
    }
}

swift

2022-09-30 11:56

2 Answers

import Foundation (same as import UIKit) allows Swift to use all functions in the standard library of C language, both sland() and land().

(arc4 random_uniform() also requires import Foundation...)

For 追Additions記:

Does "What do you think?" mean by evaluating the program?
arc4Random(), arc4Random_uniform() are designed to provide uniformity and higher quality than the rand() function in the C language standard library.If you don't use them and you use the rand() function, your rating will be low.


2022-09-30 11:56

muting func sshuffle(seed:Int){
    sland(UInt32(seed))
    letr = land()
    for in 0..<(count-1){
        let j = Int(r%Int32(count-i))+i
        swap(&self[i], &self[j])
    }
}

The shuffle operation algorithm uses Fisher – Yates Shuffle, so there should be no problem.However, letr=land() must move into the loop.(Quote code does not show "random number sequence")

@As Harawa pointed out, using rand()%N to generate random numbers should be avoided in terms of pseudorandom sequence quality.

If you want to do a homogeneous shuffle, you can use arc4 random_uniform().However, as far as the document is concerned, it appears that you cannot give seed values to the arc4 random function.


2022-09-30 11:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.