Last active
August 29, 2015 14:19
-
-
Save methane/ff65135764556996989b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ go test -bench=. -benchmem | |
PASS | |
BenchmarkAnswer3 1000000 1248 ns/op 344 B/op 6 allocs/op | |
BenchmarkAnswer4 2000000 836 ns/op 128 B/op 1 allocs/op |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"reflect" | |
"testing" | |
) | |
var sentence string = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics." | |
var expect = []int{3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9} | |
func answer3(sentence string) []int { | |
var pi []int | |
var prev, i int | |
b := []byte(sentence) | |
l := len(b) | |
for i < l { | |
for ; i < l; i++ { | |
if ('a' <= b[i] && b[i] <= 'z') || ('A' <= b[i] && b[i] <= 'Z') { | |
break | |
} | |
} | |
if i < l { | |
prev = i | |
for ; i < l; i++ { | |
if !(('a' <= b[i] && b[i] <= 'z') || ('A' <= b[i] && b[i] <= 'Z')) { | |
break | |
} | |
} | |
pi = append(pi, i-prev) | |
} | |
i++ | |
} | |
return pi | |
} | |
func answer4(s string) []int { | |
res := make([]int, 0, len(s)/6) | |
cnt := 0 | |
for _, c := range s { | |
switch { | |
case 'a' <= c && c <= 'z', 'A' <= c && c <= 'Z': | |
cnt++ | |
default: | |
if cnt != 0 { | |
res = append(res, cnt) | |
cnt = 0 | |
} | |
} | |
} | |
if cnt != 0 { | |
res = append(res, cnt) | |
cnt = 0 | |
} | |
return res | |
} | |
func TestAnswer3(t *testing.T) { | |
ans := answer3(sentence) | |
if !reflect.DeepEqual(ans, expect) { | |
t.Errorf("%+v", ans) | |
} | |
} | |
func BenchmarkAnswer3(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
answer3(sentence) | |
} | |
} | |
func TestAnswer4(t *testing.T) { | |
ans := answer4(sentence) | |
if !reflect.DeepEqual(ans, expect) { | |
t.Errorf("%+v", ans) | |
} | |
} | |
func BenchmarkAnswer4(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
answer4(sentence) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment