Golang solution rand.Perm


  • 0
    M
    type Solution struct {
        original []int
        random *rand.Rand
    }
    
    
    func Constructor(nums []int) Solution {
        return Solution{original:nums,random:rand.New(rand.NewSource(time.Now().UnixNano()))}
    }
    
    
    /** Resets the array to its original configuration and return it. */
    func (this *Solution) Reset() []int {
        return this.original
    }
    
    
    /** Returns a random shuffling of the array. */
    func (this *Solution) Shuffle() []int {
        shuffled:=make([]int,len(this.original))
        perm:=this.random.Perm(len(this.original))
        for key , value := range perm{
            shuffled[key] = this.original[value]
        }
        return shuffled
    }
    

    Using math/rand and the Perm method to shuffle the array. The source of the Rand object is set in the constructor of the Solution object. Propably not the best solution but beats 100%.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.