Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Lab3 Letter frequency #515

Merged
merged 5 commits into from
Jul 25, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions 03_letters/sirigithub/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package main

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

var out io.Writer = os.Stdout

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

// sortLetters returns a sorted slice of strings with elements {key}:{val} from the input map m
func sortLetters(m map[rune]int) []string {
sortedStrings := make([]string, 0, len(m))
for key, value := range m {
frequency := string(key) + ":" + strconv.Itoa(value)
sortedStrings = append(sortedStrings, frequency)
}
sort.Strings(sortedStrings)
return sortedStrings
}

func main() {
fmt.Fprintln(out, strings.Join(sortLetters(letters("aba")), "\n"))
}
49 changes: 49 additions & 0 deletions 03_letters/sirigithub/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package main

import (
"bytes"
"testing"

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

func TestLetterFrequency(t *testing.T) {
tests := []struct {
description string
input string
expected []string
}{
{description: "Simple string", input: "thisisasimplestring",
expected: []string{"a:1", "e:1", "g:1", "h:1", "i:4", "l:1", "m:1", "n:1", "p:1", "r:1", "s:4", "t:2"}},

{description: "String with spaces", input: " 223 ", expected: []string{" :5", "2:2", "3:1"}},

{description: "Empty String", input: "", expected: []string{}},

{description: "German Umlauts", input: "äö߀’üüüöäßß", expected: []string{"ß:3", "ä:2", "ö:2", "ü:3", "’:1", "€:1"}},

{description: "String with Back slashes", input: "a\\c\\b", expected: []string{"\\:2", "a:1", "b:1", "c:1"}},

{description: "String with Emojis", input: "😄🐷🙈🐷🏃😄", expected: []string{"🏃:1", "🐷:2", "😄:2", "🙈:1"}},
}

for _, test := range tests {
actual := sortLetters(letters(test.input))
expected := test.expected
t.Run(test.description, func(t *testing.T) {
assert.Equal(t, actual, expected, "actual %v but expected %v", actual, expected)
})
}
}

func TestMainOutput(t *testing.T) {
var buf bytes.Buffer
out = &buf
main()
expected := "a:2\nb:1\n"
actual := buf.String()

if expected != actual {
t.Errorf("Unexpected output in main(). Expected = %v Actual = %v", expected, actual)
}
}