Skip to content

a iteration can be saved for "func (r *Rand) Perm(n int) []int" #13215

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
yaojingguo opened this issue Nov 12, 2015 · 9 comments
Closed

a iteration can be saved for "func (r *Rand) Perm(n int) []int" #13215

yaojingguo opened this issue Nov 12, 2015 · 9 comments

Comments

@yaojingguo
Copy link
Contributor

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.

@randall77
Copy link
Contributor

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
Copy link
Member

minux commented Nov 12, 2015 via email

@randall77
Copy link
Contributor

Yeah, it's not a big win.
Comment sounds fine. Bonus: that can go in during the freeze.

@yaojingguo
Copy link
Contributor Author

@randall77, so the conclusion is for me to make a patch which adds a comment, right?

@randall77
Copy link
Contributor

Yes, sounds good.

@minux
Copy link
Member

minux commented Nov 12, 2015 via email

@yaojingguo
Copy link
Contributor Author

A patch is created.

CL link: https://go-review.googlesource.com/16852

@gopherbot
Copy link
Contributor

CL https://golang.org/cl/16803 mentions this issue.

@gopherbot
Copy link
Contributor

CL https://golang.org/cl/16852 mentions this issue.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants