Skip to content

Commit

Permalink
18x speed boost to secretmessage (#63)
Browse files Browse the repository at this point in the history
before:
```
$ go test -bench .
goos: linux
goarch: amd64
BenchmarkDecode-12         21541             55585 ns/op
```
after
```
BenchmarkDecode-12        389108              2950 ns/op
```
  • Loading branch information
fastcat committed May 12, 2020
1 parent 63002f7 commit a1ff899
Showing 1 changed file with 9 additions and 5 deletions.
14 changes: 9 additions & 5 deletions secretmessage/secretmessage.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,25 @@ import "sort"
// Decode func
func Decode(encoded string) string {
// count: size 27 for main case of alpha+_
counts := make(map[rune]int, 27)
counts := make([]int, 27)
for _, r := range encoded {
counts[r]++
if r == '_' {
counts[26]++
} else {
counts[r-'a']++
}
}
// only get runes with count >= counts[_]
// cap 26 for base case of alpha chars
runes := make([]rune, 0, 26)
for k, v := range counts {
if k != '_' && v >= counts['_'] {
runes = append(runes, k)
if k != 26 && v >= counts[26] {
runes = append(runes, rune('a'+k))
}
}
// sort runes by count desc
sort.Slice(runes, func(i, j int) bool {
return counts[runes[i]] > counts[runes[j]]
return counts[runes[i]-'a'] > counts[runes[j]-'a']
})
// return string
return string(runes)
Expand Down

0 comments on commit a1ff899

Please sign in to comment.