Skip to content

Instantly share code, notes, and snippets.

@lamg
Last active January 11, 2022 15:55
Show Gist options
  • Save lamg/c31f1fb20ef9ed6feaa0284cbc46e762 to your computer and use it in GitHub Desktop.
Save lamg/c31f1fb20ef9ed6feaa0284cbc46e762 to your computer and use it in GitHub Desktop.
Check if two string slices are equal by checking if they are a permutation of the other
package main
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestIsPerm(t *testing.T) {
ts := []struct {
xs, ys []string
ok bool
rs []int
}{
{
xs: []string{"a", "b"},
ys: []string{},
ok: false,
},
{
xs: []string{"a"},
ys: []string{"b"},
ok: false,
},
{
xs: []string{"a", "b"},
ys: []string{"b", "a"},
rs: []int{1, 0},
ok: true,
},
}
for _, j := range ts {
ok, rs := isPerm(j.xs, j.ys)
require.Equal(t, j.ok, ok)
if ok {
require.Equal(t, j.rs, rs)
}
}
}
func isPerm(xs, ys []string) (ok bool, rs []int) {
ok = len(xs) == len(ys)
rs = make([]int, 0, len(xs))
for ok && len(xs) != 0 {
var i int
ok, i = exists(ys, xs[0])
if ok {
rs = append(rs, i)
xs, ys = removeAt(xs, 0), removeAt(ys, i)
}
}
return
}
func exists(xs []string, x string) (ok bool, i int) {
for !ok && i < len(xs) {
ok = xs[i] == x
if !ok {
i++
}
}
return
}
func removeAt(xs []string, i int) (rs []string) {
if len(xs) == i-1 {
rs = xs[:i]
} else {
rs = append(xs[:i], xs[i+1:]...)
}
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment