advent-of-code/hacker-rank/plus-minus/main.go

70 lines
1.3 KiB
Go
Raw Permalink Normal View History

2024-10-26 12:03:06 -06:00
package main
import (
"bufio"
"fmt"
"io"
"os"
"strconv"
"strings"
)
/*
* Complete the 'plusMinus' function below.
*
* The function accepts INTEGER_ARRAY arr as parameter.
*/
func plusMinus(arr []int32) {
n := float64(len(arr))
var pos, neg, zero float64
for _, v := range arr {
switch {
case v == 0:
zero++
case v > 0:
pos++
case v < 0:
neg++
}
}
fmt.Printf("%0.6f\n%0.6f\n%0.6f\n", pos/n, neg/n, zero/n)
}
func main() {
reader := bufio.NewReaderSize(os.Stdin, 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)
}
plusMinus(arr)
}
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)
}
}