php editor Xiaoxin brings you an article about the algorithm for randomizing the output order of short arrays in the Go language. In Go language, the output order of short arrays is undefined, which is due to the concurrency characteristics of Go language. This article will introduce an algorithm based on a random number generator, which can randomize the output order of short arrays, so that the order of output is different every time the program is executed, increasing the flexibility and variability of the program. By reading this article, readers can learn how to randomize the output order of short arrays in the Go language and apply it to their own projects.
The main difference between this question and the numerous duplicate answers is that the input array is short, only 3 elements. --
Suppose I have an ordered set of int
. The size of the array is only 3 (or more). I need to randomize their order and return a new array. Although it is a pure algorithm question, the preferred answer language is go.
random.shuffle
. rand.shuffle
. However, this is my code:
https://go.dev/play/p/cvu8_q96-9f
func randshuffle(a []int) { rand.seed(time.now().unixnano()) rand.shuffle(len(a), func(i, j int) { a[i], a[j] = a[j], a[i] }) }
This is one of the results of my test run:
[2 1 3] [1 3 2] [2 1 3] [2 1 3] [1 3 2] [1 2 3] [2 3 1]
This doesn't seem very random.
Any good ideas for better randomization for short three-element arrays?
by the way,
rand.shuffle
. Yeah? Move random.seed
from the random play function to the main function. A prng can only be seeded once per program, and successful imitation of randomness is accomplished through state transitions of the generator rather than the seed. Don't reseed unless you really understand how prng works and try to explicitly control the process for reasons like reproducibility.
Make the following simple modifications to the code to meet your needs:
package main import ( "fmt" "math/rand" "time" ) func main() { rand.seed(time.now().unixnano()) a := []int{1, 2, 3} for i := 0; i < 10; i++ { randshuffle(a) fmt.println(a) } } func randshuffle(a []int) { rand.shuffle(len(a), func(i, j int) { a[i], a[j] = a[j], a[i] }) }
This will produce the following results:
[2 3 1] [3 1 2] [2 1 3] [2 3 1] [1 2 3] [1 3 2] [1 2 3] [3 1 2] [3 2 1] [2 3 1]
The above is the detailed content of Algorithm for randomizing the output order of short arrays in Go. For more information, please follow other related articles on the PHP Chinese website!