Skip to content

Commit

Permalink
Merge pull request #124 from icey-yu/shuffle-slice
Browse files Browse the repository at this point in the history
feat: shuffleSlice
  • Loading branch information
icey-yu authored Aug 14, 2024
2 parents 6a2acc8 + c710f04 commit 6b57840
Showing 1 changed file with 11 additions and 0 deletions.
11 changes: 11 additions & 0 deletions utils/datautil/datautil.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,10 @@ import (
"github.com/openimsdk/tools/db/pagination"
"github.com/openimsdk/tools/errs"
"github.com/openimsdk/tools/utils/jsonutil"
"math/rand"
"reflect"
"sort"
"time"
)

// SliceSubFuncs returns elements in slice a that are not present in slice b (a - b) and remove duplicates.
Expand Down Expand Up @@ -697,6 +699,15 @@ func CopySlice[T any](a []T) []T {
return ns
}

func ShuffleSlice[T any](a []T) []T {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
shuffled := CopySlice(a)
r.Shuffle(len(shuffled), func(i, j int) {
shuffled[i], shuffled[j] = shuffled[j], shuffled[i]
})
return shuffled
}

func GetElemByIndex(array []int, index int) (int, error) {
if index < 0 || index >= len(array) {
return 0, errs.New("index out of range", "index", index, "array", array).Wrap()
Expand Down

0 comments on commit 6b57840

Please sign in to comment.