Created
August 19, 2022 21:53
-
-
Save thiagozs/e5ce73fdcd7f4c7c2e58b8deba264353 to your computer and use it in GitHub Desktop.
HackerRank plusMinus
This file contains hidden or 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
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) { | |
// Write your code here | |
Truncate := func (num float32) string { | |
return fmt.Sprintf("%.6f", num) | |
} | |
var arrayLength = len(arr) | |
var positiveIntegers, negativeIntegers, zeros []int32 | |
var positiveRatios, negativeRatios, zerosRatios string | |
for i := 0; i < arrayLength; i++ { | |
if arr[i] > 0 { | |
positiveIntegers = append(positiveIntegers, arr[i]) | |
} else if arr[i] < 0 { | |
negativeIntegers = append(negativeIntegers, arr[i]) | |
} else { | |
zeros = append(zeros, arr[i]) | |
} | |
} | |
positiveRatios = Truncate(float32(len(positiveIntegers)) / float32(arrayLength)) | |
negativeRatios = Truncate(float32(len(negativeIntegers)) / float32(arrayLength)) | |
zerosRatios = Truncate(float32(len(zeros)) / float32(arrayLength)) | |
fmt.Println(positiveRatios) | |
fmt.Println(negativeRatios) | |
fmt.Println(zerosRatios) | |
} | |
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment