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 secretmessage, test multibyte unicode #33

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
45 changes: 43 additions & 2 deletions secretmessage/secretmessage.go
@@ -1,6 +1,47 @@
package secretmessage

// Decode func
import (
"sort"
"strings"
)

// pair tracks frequency of a character
type pair struct {
c string
n int
}

// Decode sorts encoded by descending rune frequency, discards all but one of each rune, then returns everything before "_"
func Decode(encoded string) string {
return ""
var (
chars = strings.Split(encoded, "")
m = make(map[string]int)
s = make([]pair, 1)
out = ""
i = -1
)

// count frequencies:
for _, c := range chars {
m[c]++
}

// Order the runes by descending frequency:
for k, v := range m {
s = append(s, pair{c: k, n: v})
}
sort.Slice(s, func(i, j int) bool {
return s[i].n > s[j].n
})

// Append each character to `out` until we reach _:
for {
i++
if s[i].c == "_" {
break
}
out += s[i].c
}

return out
}
14 changes: 14 additions & 0 deletions secretmessage/secretmessage_test.go
Expand Up @@ -19,3 +19,17 @@ func BenchmarkDecode(b *testing.B) {
Decode(encoded)
}
}

func TestDecodeSimple(t *testing.T) {
actual := Decode("b_bcb_")
if actual != "b" {
t.Fatalf("Expected %s, got %s", "b", actual)
}
}

func TestDecodeSimpleMultibyteUnicode(t *testing.T) {
actual := Decode("Ƃ_ƂcƂ_")
if actual != "Ƃ" {
t.Fatalf("Expected %s, got %s", "Ƃ", actual)
}
}