📜  hackerrank golang plus minus (1)

📅  最后修改于: 2023-12-03 15:31:05.632000             🧑  作者: Mango

HackerRank Go: Plus Minus

HackerRank is a platform that offers coding challenges and contests. One of the popular challenges is the "Plus Minus" challenge using GoLang. In this challenge, you are given an array of integers and your task is to calculate the fractions of its elements that are positive, negative, and zero.

Problem Statement

Given an array of integers, calculate the fractions of its elements that are positive, negative, and zero. Print the decimal value of each fraction on a new line.

Example

For example, given the array arr = [-4, 3, -9, 0, 4, 1], the output should be:

0.500000
0.333333
0.166667
Solution

The solution to this problem can be achieved by simply iterating through the array, keeping track of the count of positive, negative, and zero elements. Once the iteration is complete, the fractions can be calculated by dividing the respective counts by the total number of elements.

Here is the Go code to solve the Plus Minus problem:

package main

import (
    "bufio"
    "fmt"
    "os"
    "strconv"
    "strings"
)

func main() {
    reader := bufio.NewReader(os.Stdin)
    nInput, _ := reader.ReadString('\n')
    n, _ := strconv.Atoi(strings.TrimSpace(nInput))

    arrInput, _ := reader.ReadString('\n')
    arr := strings.Split(strings.TrimSpace(arrInput), " ")

    // Convert array of strings to array of integers
    var nums []int
    for _, numStr := range arr {
        num, _ := strconv.Atoi(numStr)
        nums = append(nums, num)
    }

    var positiveCount, negativeCount, zeroCount int
    for _, num := range nums {
        if num > 0 {
            positiveCount++
        } else if num < 0 {
            negativeCount++
        } else {
            zeroCount++
        }
    }

    fmt.Printf("%.6f\n", float64(positiveCount)/float64(n))
    fmt.Printf("%.6f\n", float64(negativeCount)/float64(n))
    fmt.Printf("%.6f\n", float64(zeroCount)/float64(n))
}
Explanation

The code above first reads the input and converts it to the appropriate data types. It then iterates through the array, keeping track of the counts of positive, negative, and zero elements using three variables.

Finally, it prints the fractions of positive, negative, and zero elements using the fmt.Printf function and the %f format specifier for floats. The %.6f format specifier specifies the precision of the float to six decimal places.

Conclusion

In conclusion, the Plus Minus challenge on HackerRank using GoLang is a good way to practice array iteration and basic arithmetic operations. It is a beginner-level challenge that can help you improve your problem-solving skills using GoLang.