-
Notifications
You must be signed in to change notification settings - Fork 32
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #779 from vaskoz/day386
Day386
- Loading branch information
Showing
3 changed files
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} | ||
} |