Skip to content

Commit

Permalink
Implement letter frequency function for lab3
Browse files Browse the repository at this point in the history
Includes tests
  • Loading branch information
ailyntang committed Aug 27, 2019
1 parent 892953f commit fd23c15
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 0 deletions.
33 changes: 33 additions & 0 deletions 03_letters/ailyntang/letters.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package main

import (
"fmt"
"strconv"
"sort"
"strings"
"io"
"os"
)

var out io.Writer = os.Stdout

func main() {
fmt.Fprintln(out, strings.Join(sortLetters(letters("aba")), "\n"))
}

func letters(s string) map[rune]int {
count := make(map[rune]int)
for _, r := range s {
count[r]++
}
return count
}

func sortLetters(m map[rune]int) []string {
output := []string{}
for rune, count := range m {
output = append(output, string(rune) + ":" + strconv.Itoa(count))
}
sort.Strings(output)
return output
}
48 changes: 48 additions & 0 deletions 03_letters/ailyntang/letters_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package main

import (
"bytes"
"testing"

"github.com/stretchr/testify/assert"
)

func TestInputsToLetters(t *testing.T) {
assert := assert.New(t)

assert.Equal(map[rune]int{}, letters(""), "empty string")
assert.Equal(map[rune]int{'F': 1}, letters("F"), "letter")
assert.Equal(map[rune]int{'\n': 1}, letters("\n"), "new line")
assert.Equal(map[rune]int{'*': 1}, letters("*"), "symbol")
assert.Equal(map[rune]int{'✌': 1}, letters("✌"), "emoticon")
}

func TestOutputToLetters(t *testing.T) {
assert := assert.New(t)
longString := "################################################"

assert.Equal(map[rune]int{'#': 48}, letters(longString), "long string")
assert.Equal(map[rune]int{'H': 1, 'h': 1, 'e': 4, 'r': 2, ' ': 2, '!': 1, '2': 1}, letters("Here here 2!"), "mixed input")
}

func TestSortLetters(t *testing.T) {
assert := assert.New(t)

longInput := "5555555555555555bbbbbbbbbbbbbbbbbbb✌✌✌✌✌✌✌✌✌✌✌????????????"
output1 := []string{" :8", "T:1", "a:1", "b:1", "c:1", "d:1", "e:3", "f:1", "g:1", "h:2", "i:1", "j:1", "k:1", "l:1"}
output2 := []string{"m:1", "n:1", "o:4", "p:1", "q:1", "r:2", "s:1", "t:1", "u:2", "v:1", "w:1", "x:1", "y:1", "z:1"}
outputManyChars := append(output1, output2...)

assert.Equal([]string{"a:1", "b:1", "c:1", "d:1", "e:1"}, sortLetters(letters("edcba")), "unsorted input")
assert.Equal([]string{"5:16", "?:12", "b:19", "✌:11"}, sortLetters(letters(longInput)), "long input")
assert.Equal(outputManyChars, sortLetters(letters("The quick brown fox jumps over the lazy dog")), "many characters")
}

func TestMainOutput(t *testing.T) {
var buf bytes.Buffer
out = &buf

main()

assert.Equal(t, "a:2\nb:1\n", buf.String())
}

0 comments on commit fd23c15

Please sign in to comment.