Skip to content

Instantly share code, notes, and snippets.

@mmirolim
Last active April 29, 2019 16:46
Show Gist options
  • Save mmirolim/c135f309eac54e9531eec330cd1715cb to your computer and use it in GitHub Desktop.
Save mmirolim/c135f309eac54e9531eec330cd1715cb to your computer and use it in GitHub Desktop.
kiss with loops to generate []int [1,9] but excluding list []int [1,9]
package main
import "testing"
func generateBitset(vals []int) []int {
var x uint16 = 65535 >> 7
for _, v := range vals {
x = x ^ 1<<uint16(v-1)
}
r := make([]int, 0, 9-len(vals))
for i := 1; i < 10; i++ {
if x&(1<<uint16(i-1)) != 0 {
r = append(r, i)
}
}
return r
}
func generateWithMap(vals []int) []int {
m := make(map[int]bool, len(vals))
for _, v := range vals {
m[v] = true
}
r := make([]int, 0, 9-len(vals))
for i := 1; i < 10; i++ {
if !m[i] {
r = append(r, i)
}
}
return r
}
func generateWith2Loop(vals []int) []int {
r := make([]int, 0, 9-len(vals))
LOOP:
for i := 1; i < 10; i++ {
for id := range vals {
if i == vals[id] {
continue LOOP
}
}
r = append(r, i)
}
return r
}
func TestExcludeWithBitset(t *testing.T) {
in := []int{1, 2, 3, 5, 6, 7, 9}
result := []int{4, 8}
out := generateBitset(in)
if len(result) != len(out) {
t.Fatalf("expected len %v, got %v", len(result), len(out))
}
for i := range result {
if result[i] != out[i] {
t.Errorf("expected value %v, got %v", result[i], out[i])
}
}
}
func TestExcludeWithMap(t *testing.T) {
in := []int{1, 2, 3, 5, 6, 7, 9}
result := []int{4, 8}
out := generateWithMap(in)
if len(result) != len(out) {
t.Fatalf("expected len %v, got %v", len(result), len(out))
}
for i := range result {
if result[i] != out[i] {
t.Errorf("expected value %v, got %v", result[i], out[i])
}
}
}
func TestExcludeWith2Loop(t *testing.T) {
in := []int{1, 2, 3, 5, 6, 7, 9}
result := []int{4, 8}
out := generateWith2Loop(in)
if len(result) != len(out) {
t.Fatalf("expected len %v, got %v", len(result), len(out))
}
for i := range result {
if result[i] != out[i] {
t.Errorf("expected value %v, got %v", result[i], out[i])
}
}
}
func BenchmarkExcludeWithBitset(b *testing.B) {
in := []int{1, 2, 3, 4, 5, 6, 7, 9}
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_ = generateBitset(in)
}
}
func BenchmarkExcludeWithMap(b *testing.B) {
in := []int{1, 2, 3, 4, 5, 6, 7, 9}
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_ = generateWithMap(in)
}
}
func BenchmarkExcludeWith2Loop(b *testing.B) {
in := []int{1, 2, 3, 4, 5, 6, 7, 9}
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_ = generateWith2Loop(in)
}
}
/*
go test -run=XXX -bench=BenchmarkExc
goos: linux
goarch: amd64
pkg: github.com/mmirolim/maze
BenchmarkExcludeWithBitset-4 50000000 35.1 ns/op 8 B/op 1 allocs/op
BenchmarkExcludeWithMap-4 10000000 223 ns/op 8 B/op 1 allocs/op
BenchmarkExcludeWith2Loop-4 50000000 37.6 ns/op 8 B/op 1 allocs/op
PASS
ok github.com/mmirolim/maze 6.183s
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment