Closed
Description
In src/math/rand/rand.go
, there is the following code:
func (r *Rand) Perm(n int) []int {
m := make([]int, n)
for i := 0; i < n; i++ {
j := r.Intn(i + 1)
m[i] = m[j]
m[j] = i
}
return m
}
i
can start from 1
instead of 0
since the iteration for i=0
always swap m[0]
with m[0]
. A fix is to change i := 0
to i := 1
.
Activity
randall77 commentedon Nov 12, 2015
Indeed. Unfortunately, this is tricky. Perm also side-effects r, and making this change will affect the final state of r. I don't think we can do that for compatibility reasons.
You could start the loop at 1 and call r.Intn(1) (or Int63()) before the loop. Then add a big comment as to why that call is there and that we should remove it for Go 2.
Too bad Intn(1) wasn't originally coded to do the n==1 shortcut.
Care to make a patch?
minux commentedon Nov 12, 2015
randall77 commentedon Nov 12, 2015
Yeah, it's not a big win.
Comment sounds fine. Bonus: that can go in during the freeze.
yaojingguo commentedon Nov 12, 2015
@randall77, so the conclusion is for me to make a patch which adds a comment, right?
randall77 commentedon Nov 12, 2015
Yes, sounds good.
minux commentedon Nov 12, 2015
yaojingguo commentedon Nov 12, 2015
A patch is created.
CL link: https://go-review.googlesource.com/16852
gopherbot commentedon Nov 13, 2015
CL https://golang.org/cl/16803 mentions this issue.
gopherbot commentedon Nov 15, 2015
CL https://golang.org/cl/16852 mentions this issue.