1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-09 07:02:29 +08:00

feat: add ShuffleCopy

This commit is contained in:
dudaodong
2025-02-14 16:33:22 +08:00
parent 2e619e48a3
commit 0e7297cb97
5 changed files with 113 additions and 1 deletions

View File

@@ -1026,6 +1026,20 @@ func Shuffle[T any](slice []T) []T {
return slice
}
// ShuffleCopy return a new slice with elements shuffled.
// Play: todo
func ShuffleCopy[T any](slice []T) []T {
result := make([]T, len(slice))
copy(result, slice)
rand.Seed(time.Now().UnixNano())
rand.Shuffle(len(result), func(i, j int) {
result[i], result[j] = result[j], result[i]
})
return result
}
// IsAscending checks if a slice is ascending order.
// Play: https://go.dev/play/p/9CtsFjet4SH
func IsAscending[T constraints.Ordered](slice []T) bool {

View File

@@ -950,6 +950,28 @@ func ExampleReverseCopy() {
// [a b c d]
}
func ExampleShuffle() {
strs := []string{"a", "b", "c", "d"}
Shuffle(strs)
fmt.Println(len(strs))
// Output:
// 4
}
func ExampleShuffleCopy() {
strs := []string{"a", "b", "c", "d"}
shuffledStrs := ShuffleCopy(strs)
fmt.Println(len(shuffledStrs))
fmt.Println(strs)
// Output:
// 4
// [a b c d]
}
func ExampleIsAscending() {
result1 := IsAscending([]int{1, 2, 3, 4, 5})

View File

@@ -1340,6 +1340,18 @@ func TestShuffle(t *testing.T) {
assert.Equal(5, len(result))
}
func TestShuffleCopy(t *testing.T) {
t.Parallel()
assert := internal.NewAssert(t, "TestShuffleCopy")
numbers := []int{1, 2, 3, 4, 5}
result := ShuffleCopy(numbers)
assert.Equal(5, len(result))
assert.Equal([]int{1, 2, 3, 4, 5}, numbers)
}
func TestIndexOf(t *testing.T) {
t.Parallel()