Refactor rock, paper, scissors
This commit is contained in:
@ -141,3 +141,21 @@ func SplitArgs(s string, n int) (args []string) {
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func MapKeys[K comparable, V any](m map[K]V) []K {
|
||||
keys := make([]K, 0, len(m))
|
||||
for k := range m {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
func MapKey[K comparable, V comparable](m map[K]V, v V) K {
|
||||
var r K
|
||||
for k := range m {
|
||||
if m[k] == v {
|
||||
return k
|
||||
}
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
@ -123,3 +123,37 @@ func TestSplitArgs(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMapKeys(t *testing.T) {
|
||||
tables := []struct {
|
||||
m map[string]int
|
||||
want []string
|
||||
}{
|
||||
{map[string]int{"a": 0, "b": 1, "c": 3}, []string{"a", "b", "c"}},
|
||||
}
|
||||
|
||||
for _, table := range tables {
|
||||
if got, want := MapKeys(table.m), table.want; !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("got: %#v, want: %#v", got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMapKey(t *testing.T) {
|
||||
tables := []struct {
|
||||
m map[string]int
|
||||
n int
|
||||
want string
|
||||
}{
|
||||
{map[string]int{"a": 0, "b": 1, "c": 2}, 0, "a"},
|
||||
{map[string]int{"a": 0, "b": 1, "c": 2}, 1, "b"},
|
||||
{map[string]int{"a": 0, "b": 1, "c": 2}, 2, "c"},
|
||||
{map[string]int{"a": 0, "b": 1, "c": 2, "d": 0}, 0, "a"},
|
||||
}
|
||||
|
||||
for _, table := range tables {
|
||||
if got, want := MapKey(table.m, table.n), table.want; got != want {
|
||||
t.Errorf("got: %#v, want: %#v", got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
12
lib/rand.go
12
lib/rand.go
@ -37,3 +37,15 @@ func SeedMathRand() error {
|
||||
func RandInt(min int, max int) int {
|
||||
return rand.Intn(max-min+1) + min
|
||||
}
|
||||
|
||||
func MapRand[K comparable, V any](m map[K]V) V {
|
||||
n := rand.Intn(len(m))
|
||||
i := 0
|
||||
for _, v := range m {
|
||||
if i == n {
|
||||
return v
|
||||
}
|
||||
i++
|
||||
}
|
||||
panic("unreachable")
|
||||
}
|
||||
|
Reference in New Issue
Block a user