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

feat: add Frequency in slice package

This commit is contained in:
dudaodong
2024-09-06 15:06:35 +08:00
parent 90e5a0bfb2
commit c3372e18b1
5 changed files with 141 additions and 9 deletions

View File

@@ -1386,3 +1386,15 @@ func LeftPadding[T any](slice []T, paddingValue T, paddingLength int) []T {
return paddedSlice
}
// Frequency counts the frequency of each element in the slice.
// Play: todo
func Frequency[T comparable](slice []T) map[T]int {
result := make(map[T]int)
for _, v := range slice {
result[v]++
}
return result
}

View File

@@ -1251,3 +1251,13 @@ func ExampleMapConcurrent() {
// Output:
// [1 4 9 16 25 36]
}
func ExampleFrequency() {
strs := []string{"a", "b", "b", "c", "c", "c"}
result := Frequency(strs)
fmt.Println(result)
// Output:
// map[a:1 b:2 c:3]
}

View File

@@ -1764,5 +1764,55 @@ func TestFilterConcurrent(t *testing.T) {
actual := FilterConcurrent(nums, func(_, n int) bool { return n > 3 }, 4)
assert.Equal(expected, actual)
})
}
func TestFrequency(t *testing.T) {
t.Parallel()
assert := internal.NewAssert(t, "TestFrequency")
t.Run("empty slice", func(t *testing.T) {
result := Frequency([]int{})
assert.Equal(map[int]int{}, result)
})
t.Run("int slice", func(t *testing.T) {
nums := []int{1, 2, 2, 3, 3, 3}
expected := map[int]int{1: 1, 2: 2, 3: 3}
result := Frequency(nums)
assert.Equal(expected, result)
})
t.Run("string slice", func(t *testing.T) {
strs := []string{"a", "b", "b", "c", "c", "c"}
expected := map[string]int{"a": 1, "b": 2, "c": 3}
result := Frequency(strs)
assert.Equal(expected, result)
})
t.Run("struct slice", func(t *testing.T) {
type student struct {
Name string
Age int
}
students := []student{
{Name: "a", Age: 11},
{Name: "b", Age: 12},
{Name: "a", Age: 13},
{Name: "c", Age: 14},
}
expected := map[student]int{
{Name: "a", Age: 11}: 1,
{Name: "a", Age: 13}: 1,
{Name: "b", Age: 12}: 1,
{Name: "c", Age: 14}: 1,
}
result := Frequency(students)
assert.Equal(expected, result)
})
}