Skip to content

Commit

Permalink
Merge pull request #779 from vaskoz/day386
Browse files Browse the repository at this point in the history
Day386
  • Loading branch information
vaskoz committed Dec 10, 2019
2 parents 189c8e3 + eba8e34 commit 75e50be
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -381,4 +381,5 @@ problems from
* [Day 383](https://github.com/vaskoz/dailycodingproblem-go/issues/772)
* [Day 384](https://github.com/vaskoz/dailycodingproblem-go/issues/776)
* [Day 385](https://github.com/vaskoz/dailycodingproblem-go/issues/774)
* [Day 386](https://github.com/vaskoz/dailycodingproblem-go/issues/778)

28 changes: 28 additions & 0 deletions day386/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package day386

import "sort"

// SortStringByCharFreq sorts the string by character
// frequency with the most frequent letters first.
// For a tie-breaker, they're sorted in reverse alphabetical
// order.
func SortStringByCharFreq(s string) string {
freq := make(map[rune]int)
runes := []rune(s)

for _, r := range runes {
freq[r]++
}

sort.Slice(runes, func(i, j int) bool {
if f1, f2 := freq[runes[i]], freq[runes[j]]; f1 > f2 {
return true
} else if f1 == f2 {
return runes[i] > runes[j]
}

return false
})

return string(runes)
}
29 changes: 29 additions & 0 deletions day386/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package day386

import "testing"

// nolint
var testcases = []struct {
input, expected string
}{
{"tweet", "tteew"},
{"happiness", "ssppnihea"},
}

func TestSortStringByCharFreq(t *testing.T) {
t.Parallel()

for _, tc := range testcases {
if res := SortStringByCharFreq(tc.input); res != tc.expected {
t.Errorf("Expected %v, got %v", tc.expected, res)
}
}
}

func BenchmarkSortStringByCharFreq(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
SortStringByCharFreq(tc.input)
}
}
}

0 comments on commit 75e50be

Please sign in to comment.