Skip to content

Commit

Permalink
feat: add Shuffle
Browse files Browse the repository at this point in the history
  • Loading branch information
iFurySt committed Aug 4, 2023
1 parent caa3b4f commit 9760e91
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
17 changes: 16 additions & 1 deletion slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ package lol
import (
"golang.org/x/exp/constraints"
"golang.org/x/exp/slices"
"math/rand"
"time"
)

// SortSlice sorts a slice. Just a wrapper for slices.Sort.
Expand Down Expand Up @@ -154,7 +156,7 @@ func Map[T any](list []T, fn func(v T) T) []T {
return list
}

// MapTo is same as Map, but it can return another type slice.
// MapTo is same as Map, but it can return another type of slice.
//
// Special case: when fn is nil, it returns the empty slice.
//
Expand All @@ -175,6 +177,19 @@ func MapTo[T any, R any](list []T, fn func(v T) R) []R {
return res
}

// Shuffle shuffles a slice for random order.
// Implement based on rand.Shuffle
//
// Play: https://go.dev/play/p/A2yeiJDWIHp
func Shuffle[T any](list []T) {
if len(list) == 0 {
return
}
s := rand.NewSource(time.Now().UnixNano())
rand.New(s).Shuffle(len(list), func(i, j int) { list[i], list[j] = list[j], list[i] })
return
}

// Reduce accumulates and combines elements through a fn into a single value.
//
// Special case: when fn is nil, it returns the initial value
Expand Down
6 changes: 6 additions & 0 deletions slice_example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,12 @@ func ExampleMapTo() {
// [Heisenberg Hank Saul]
}

func ExampleShuffle() {
s := []string{"a", "b", "c", "d"}
Shuffle(s)
fmt.Println(s)
}

func ExampleReduce() {
res1 := Reduce([]int{1, 7, 3, 4}, func(s float64, v, i int) float64 {
return s * float64(v)
Expand Down
10 changes: 10 additions & 0 deletions slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"fmt"
"github.com/stretchr/testify/assert"
"sort"
"strings"
"testing"
)

Expand Down Expand Up @@ -155,6 +156,15 @@ func TestMapTo(t *testing.T) {
assert.Equalf(t, []string{"Heisenberg", "Hank", "Saul"}, got, "extract struct")
}

func TestShuffle(t *testing.T) {
s := []string{"a", "b", "c", "d", "e", "a", "b", "c", "d", "e", "a", "b", "c", "d", "e", "a", "b", "c", "d", "e"}
s1 := strings.Join(s, "")
Shuffle(s)
s2 := strings.Join(s, "")
// Probabilistic problem
assert.NotEqualf(t, s1, s2, "shuffle string")
}

func TestReduce(t *testing.T) {
t.Parallel()

Expand Down

0 comments on commit 9760e91

Please sign in to comment.