Go: Custom String Sorting
Date
Author
Sort a set of strings based on the following factors:
- An odd length string should precede an even length string.
- If both strings have odd lengths, the shorter of the two should precede.
- If both strings have even lengths, the longer of the two should precede.
- If the two strings have equal lengths, they should be in alphabetical order.
Example
strArr =[‘abc’, ‘ab’, ‘abcde’, ‘a’, ‘abcd’]
The result is [‘a’, ‘abc’, ‘abcde’, ‘abcd’, ‘ab’] . Odd length words are sorted in ascending order of length followed by even length words in descending order of length. There are no matching length words, so no alphabetical sorting is required.
Function Description
Complete the function customSorting in the editor below.
customSorting has the following parameter:
string strArr[n]: an array of strings
Returns
string[n]: the sorted array
Constraints
- 1 ≤ length of strArr ≤ 1000
- 1 ≤ length of strArr[i] ≤ 100
- Each strArr[i] contains uppercase and lowercase English letters only.
SOLUTION:
package main
import (
"bufio"
"fmt"
"io"
"os"
"sort"
"strconv"
"strings"
)
/*
* Complete the 'customSorting' function below.
*
* The function is expected to return a STRING_ARRAY.
* The function accepts STRING_ARRAY strArr as parameter.
*/
func customSorting(strArr []string) []string {
// Implement the custom sorting logic here
sort.Slice(strArr, func(i, j int) bool {
lenI := len(strArr[i])
lenJ := len(strArr[j])
// Case 1: Odd length string precedes even length string
if lenI%2 != lenJ%2 {
return lenI%2 == 1
}
// Case 2: Both strings have odd lengths
if lenI%2 == 1 {
// Shorter odd length string precedes
if lenI != lenJ {
return lenI < lenJ
}
}
// Case 3: Both strings have even lengths
if lenI%2 == 0 {
// Longer even length string precedes
if lenI != lenJ {
return lenI > lenJ
}
}
// Case 4: Equal lengths, sort alphabetically
return strArr[i] < strArr[j]
})
return strArr
}
func main() {
reader := bufio.NewReaderSize(os.Stdin, 16*1024*1024)
stdout, err := os.Create(os.Getenv("OUTPUT_PATH"))
checkError(err)
defer stdout.Close()
writer := bufio.NewWriterSize(stdout, 16*1024*1024)
strArrCount, err := strconv.ParseInt(strings.TrimSpace(readLine(reader)), 10, 64)
checkError(err)
var strArr []string
for i := 0; i < int(strArrCount); i++ {
strArrItem := readLine(reader)
strArr = append(strArr, strArrItem)
}
result := customSorting(strArr)
for i, resultItem := range result {
fmt.Fprintf(writer, "%s", resultItem)
if i != len(result)-1 {
fmt.Fprintf(writer, "\n")
}
}
fmt.Fprintf(writer, "\n")
writer.Flush()
}
func readLine(reader *bufio.Reader) string {
str, _, err := reader.ReadLine()
if err == io.EOF {
return ""
}
return strings.TrimRight(string(str), "\r\n")
}
func checkError(err error) {
if err != nil {
panic(err)
}
}