Any type with Len, Less and Swap can be sorted by the standard library.
What to build
A program that sorts words by length, then alphabetically, and then in the opposite order.
Requirements
- Define a type
byLengthof[]stringthat implementssort.Interface: shorter words first, and words of equal length in alphabetical order. - Read n, then n words.
- Print the words sorted with
sort.Sorton the first line, and sorted in the opposite order withsort.Reverseon the second line. Separate words by single spaces.
Input
Line 1: n. Then n words.
Output
Two lines.
Constraints
1 ≤ n ≤ 50; words are lower case letters, 1 to 12 long.
Example
Input:
5
banana fig apple kiwi date
Output:
fig date kiwi apple banana
banana apple kiwi date fig
Why it works
sort.Sort only needs the three methods of sort.Interface, so it can sort any type that has them, with any rule you write in Less. sort.Reverse wraps your type and flips the answer of Less.
Examples
Example 1 · Input
5 banana fig apple kiwi date
Expected output
fig date kiwi apple banana banana apple kiwi date fig
Example 2 · Input
3 b a c
Expected output
a b c c b a
Hints
Hint 1
Define type byLength []string with Len, Swap and Less; Less compares lengths first, then the words.
Hint 2
Use sort.Sort(byLength(words)) and then sort.Sort(sort.Reverse(byLength(words))).
Solution
Show one correct solution (try it yourself first)
package main
import (
"fmt"
"sort"
"strings"
)
type byLength []string
func (b byLength) Len() int { return len(b) }
func (b byLength) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
func (b byLength) Less(i, j int) bool {
if len(b[i]) != len(b[j]) {
return len(b[i]) < len(b[j])
}
return b[i] < b[j]
}
func main() {
var n int
fmt.Scan(&n)
words := make([]string, n)
for i := range words {
fmt.Scan(&words[i])
}
sort.Sort(byLength(words))
fmt.Println(strings.Join(words, " "))
sort.Sort(sort.Reverse(byLength(words)))
fmt.Println(strings.Join(words, " "))
}