Skip to content

Instantly share code, notes, and snippets.

@jcockbain
Last active January 17, 2021 21:07
Show Gist options
  • Save jcockbain/e76b65fc13e4f19faf9d2ae318c7f5a6 to your computer and use it in GitHub Desktop.
Save jcockbain/e76b65fc13e4f19faf9d2ae318c7f5a6 to your computer and use it in GitHub Desktop.
A Go data structure for recording the counts of each character in a string and sorting it by character frequency, and then alphabetically in the case of a tie.
package main
import (
"fmt"
"sort"
)
type letter struct {
char rune
count int
}
type letters []letter
func (l letters) Less(i, j int) bool {
switch fd := l[i].count - l[j].count; {
case fd < 0:
return false
case fd > 0:
return true
}
return l[i].char < l[j].char
}
func (l letters) Len() int { return len(l) }
func (l letters) Swap(i, j int) {
l[i], l[j] = l[j], l[i]
}
func (l letters) Print() {
for _, letter := range l {
fmt.Printf("%s : %d ", string(letter.char), letter.count)
}
}
func countChars(s string) {
counter := make(map[rune]int)
for _, c := range s {
if c != ' ' {
counter[c] += 1
}
}
lettersSlice := letters{}
for char, freq := range counter {
lettersSlice = append(lettersSlice, letter{char, freq})
}
sort.Sort(lettersSlice)
lettersSlice.Print()
}
func main() {
countChars("hello world")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment