Skip to content

Commit

Permalink
Merge branch 'slice-shuffle'
Browse files Browse the repository at this point in the history
  • Loading branch information
kazhuravlev committed May 12, 2024
2 parents 7997693 + c8b03f3 commit 3511893
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
19 changes: 19 additions & 0 deletions slice.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package just

import (
"math/rand"
"sort"
)

Expand Down Expand Up @@ -723,3 +724,21 @@ func Slice2Iter[T any](in []T) func(func(int, T) bool) {
}
}
}

// SliceShuffle will shuffle the slice in-place.
func SliceShuffle[T any](in []T) {
for i := range in {
j := rand.Intn(i + 1)
in[i], in[j] = in[j], in[i]
}
}

// SliceShuffleCopy will make a copy and shuffle slice.
func SliceShuffleCopy[T any](in []T) []T {
res := make([]T, len(in))
copy(res, in)

SliceShuffle(res)

return res
}
15 changes: 15 additions & 0 deletions slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1801,3 +1801,18 @@ func TestSliceLastDefault(t *testing.T) {
})
}
}

func TestSliceShuffleCopy(t *testing.T) {
input := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

var res []int
for range just.SliceRange(0, 5, 1) {
t.Run("", func(t *testing.T) {
res2 := just.SliceShuffleCopy(input)
assert.NotEqual(t, input, res2)
assert.NotEqual(t, res2, res)

res = res2
})
}
}

0 comments on commit 3511893

Please sign in to comment.