Skip to content

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

Closed
@yaojingguo

Description

@yaojingguo

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

randall77 commented on Nov 12, 2015

@randall77
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

minux commented on Nov 12, 2015

@minux
Member
randall77

randall77 commented on Nov 12, 2015

@randall77
Contributor

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

yaojingguo

yaojingguo commented on Nov 12, 2015

@yaojingguo
ContributorAuthor

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

randall77

randall77 commented on Nov 12, 2015

@randall77
Contributor

Yes, sounds good.

minux

minux commented on Nov 12, 2015

@minux
Member
yaojingguo

yaojingguo commented on Nov 12, 2015

@yaojingguo
ContributorAuthor

A patch is created.

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

gopherbot

gopherbot commented on Nov 13, 2015

@gopherbot
Contributor

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

gopherbot

gopherbot commented on Nov 15, 2015

@gopherbot
Contributor

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

locked and limited conversation to collaborators on Nov 16, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @minux@yaojingguo@randall77@gopherbot

        Issue actions

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