Skip to content

Commit

Permalink
make slices.Shuffle an in-place operation
Browse files Browse the repository at this point in the history
  • Loading branch information
orsinium committed Dec 21, 2021
1 parent bc0ff61 commit de813b3
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 6 deletions.
9 changes: 5 additions & 4 deletions slices/slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -437,10 +437,12 @@ func Same[S ~[]T, T comparable](items S) bool {
return true
}

// Shuffle in random order arr elements
func Shuffle[S ~[]T, T any](items S, seed int64) S {
// Shuffle in random order the given elements
//
// This is an in-place operation, it modifies the passed slice.
func Shuffle[S ~[]T, T any](items S, seed int64) {
if len(items) <= 1 {
return items
return
}
if seed == 0 {
seed = time.Now().UnixNano()
Expand All @@ -450,7 +452,6 @@ func Shuffle[S ~[]T, T any](items S, seed int64) S {
items[i], items[j] = items[j], items[i]
}
rand.Shuffle(len(items), swap)
return items
}

// Sort returns sorted slice
Expand Down
4 changes: 2 additions & 2 deletions slices/slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -376,8 +376,8 @@ func TestSame(t *testing.T) {
func TestShuffle(t *testing.T) {
is := is.New(t)
f := func(given []int, seed int64, expected []int) {
actual := slices.Shuffle(given, seed)
is.Equal(expected, actual)
slices.Shuffle(given, seed)
is.Equal(given, expected)
}
f([]int{}, 0, []int{})
f([]int{1}, 0, []int{1})
Expand Down

0 comments on commit de813b3

Please sign in to comment.