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

[feature]<slice>: support random item (#146)

Signed-off-by: o98k-ok <hggend@gmail.com>
This commit is contained in:
o98k
2023-11-22 16:51:37 +08:00
committed by GitHub
parent 31c618c187
commit 3802c715c3
5 changed files with 109 additions and 0 deletions

View File

@@ -12,6 +12,7 @@ import (
"strings"
"time"
"github.com/duke-git/lancet/v2/random"
"golang.org/x/exp/constraints"
)
@@ -1229,3 +1230,14 @@ func Partition[T any](slice []T, predicates ...func(item T) bool) [][]T {
return result
}
// Random get a random item of slice, return idx=-1 when slice is empty
// Play: todo
func Random[T any](slice []T) (val T, idx int) {
if len(slice) == 0 {
return val, -1
}
idx = random.RandInt(0, len(slice))
return slice[idx], idx
}

View File

@@ -1063,3 +1063,14 @@ func ExamplePartition() {
// [[2 4] [1 3 5]]
// [[1 2] [3 4] [5]]
}
func ExampleRandom() {
nums := []int{1, 2, 3, 4, 5}
val, idx := Random(nums)
if idx >= 0 && idx < len(nums) && Contain(nums, val) {
fmt.Println("okk")
}
// Output:
// okk
}

View File

@@ -1185,3 +1185,28 @@ func TestPartition(t *testing.T) {
assert.Equal([][]int{{2, 4}, {1, 3, 5}}, Partition([]int{1, 2, 3, 4, 5}, func(n int) bool { return n%2 == 0 }))
assert.Equal([][]int{{1, 2}, {3, 4}, {5}}, Partition([]int{1, 2, 3, 4, 5}, func(n int) bool { return n == 1 || n == 2 }, func(n int) bool { return n == 2 || n == 3 || n == 4 }))
}
func TestRandom(t *testing.T) {
t.Parallel()
assert := internal.NewAssert(t, "TestRandom")
var arr []int
var val, idx int
_, idx = Random(arr)
assert.Equal(-1, idx)
arr = []int{}
_, idx = Random(arr)
assert.Equal(-1, idx)
arr = []int{1}
val, idx = Random(arr)
assert.Equal(0, idx)
assert.Equal(arr[idx], val)
arr = []int{1, 2, 3}
val, idx = Random(arr)
assert.Greater(len(arr), idx)
assert.Equal(arr[idx], val)
}