advent-of-code/hacker-rank/counting-sort/main.go
xuu 04bbac8559
Some checks failed
Go Bump / bump (push) Failing after 6s
Go Test / build (push) Successful in 47s
chore: add hackerrank solutions
2024-10-26 12:03:06 -06:00

81 lines
1.5 KiB
Go

package main
import (
"bufio"
"fmt"
"io"
"os"
"strconv"
"strings"
)
/*
* Complete the 'countingSort' function below.
*
* The function is expected to return an INTEGER_ARRAY.
* The function accepts INTEGER_ARRAY arr as parameter.
*/
func countingSort(arr []int32) []int32 {
freq := make([]int32, 100)
for _, i := range arr {
freq[i]++
}
return freq
}
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)
nTemp, err := strconv.ParseInt(strings.TrimSpace(readLine(reader)), 10, 64)
checkError(err)
n := int32(nTemp)
arrTemp := strings.Split(strings.TrimSpace(readLine(reader)), " ")
var arr []int32
for i := 0; i < int(n); i++ {
arrItemTemp, err := strconv.ParseInt(arrTemp[i], 10, 64)
checkError(err)
arrItem := int32(arrItemTemp)
arr = append(arr, arrItem)
}
result := countingSort(arr)
for i, resultItem := range result {
fmt.Fprintf(writer, "%d", resultItem)
if i != len(result) - 1 {
fmt.Fprintf(writer, " ")
}
}
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)
}
}