The key difference between this question and the lots of duplicated answers is that, the input array is short, only 3 elements. --
Say I have an ordered set of int
. The size of array is only 3 (or a bit more). I need to randomize their order and return a new array. Although it is a pure algorithm question, but the prefered answer language is in Go.
- With Python, How can I output a list in random order?, the answer is
random.shuffle
. - With Go, https://yourbasic.org/golang/shuffle-slice-array/, the answer should be
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] })
}
And this is one of my test run result:
[2 1 3]
[1 3 2]
[2 1 3]
[2 1 3]
[1 3 2]
[1 2 3]
[2 3 1]
which doesn't seems to be very randomized.
Any good idea to have a better randomization for a short 3-elements array?
BTW,
- How to output array elements in random order using VHDL says to use a linear feedback shift register, but I don't think it'd be a good idea for this question.
- The How to randomize (shuffle) a JavaScript array? gives a Durstenfeld shuffle algorithm, an optimized version of Fisher-Yates. But I presume that its result will be quite similiar to Go's
rand.Shuffle
. Is it?
Aucun commentaire:
Enregistrer un commentaire