github.com/kazu/loncha@v0.6.3/shuffle.go (about)

     1  // Copyright 2019 Kazuhisa TAKEI<xtakei@rytr.jp>. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package loncha
     6  
     7  import (
     8  	"math/rand"
     9  	"reflect"
    10  
    11  	"github.com/seehuhn/mt19937"
    12  )
    13  
    14  // Shuffle is shuffing slice order. if slice is not pointer of slice or not slice, return error
    15  func Shuffle(slice interface{}, seeds ...int64) (e error) {
    16  
    17  	rv, err := sliceElm2Reflect(slice)
    18  	if err != nil {
    19  		return err
    20  	}
    21  
    22  	length := rv.Len()
    23  	if length == 0 {
    24  		return
    25  	}
    26  	randMt := rand.New(mt19937.New())
    27  
    28  	if len(seeds) > 0 {
    29  		randMt.Seed(seeds[0])
    30  	}
    31  
    32  	swap := reflect.Swapper(rv.Interface())
    33  
    34  	for i := 0; i < length; i++ {
    35  		r := i + randMt.Intn(length-i)
    36  		swap(r, i)
    37  	}
    38  	return
    39  }