Given an array of integers, calculate the ratios of its elements that are positive, negative, and zero. Print the decimal value of each fraction on a new line with 6 places after the decimal.
Note: This challenge introduces precision problems. The test cases are scaled to six decimal places, though answers with absolute errors of up to 10(-4) are acceptable.
Example
arr = [1, 1, -1, -1, 0]
Results are printed as (the ratios of positive, negative, and zero values):
0.400000
0.400000
0.200000
Function Description
Complete the plusMinus function in the editor below.
plusMinus has the following parameter(s):
- int arr[n]: an array of integers
Input Format
The first line contains an integer n, the size of the array.
The second line contains n space-separated integers that describe arr[n].
Constraints
0 < n <= 100
-100 <= arr[i] <= 100
Sample Input
STDIN Function
----- --------
6 arr[] size n = 6
-4 3 -9 0 4 1 arr = [-4, 3, -9, 0, 4, 1]
Sample Output
0.500000
0.333333
0.166667
func plusMinus(arr: [Int]) -> Void {
var ans: [Double] = [0, 0, 0]
for i in arr {
if i > 0 {
ans[0] += 1
} else if i < 0 {
ans[1] += 1
} else {
ans[2] += 1
}
}
ans[0] = ans[0]/(Double)(arr.count)
ans[1] = ans[1]/(Double)(arr.count)
ans[2] = ans[2]/(Double)(arr.count)
for i in ans {
print(String(format: "%.6f", i))
}
}
guard let n = Int((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!)
else { fatalError("Bad input") }
guard let arrTemp = readLine()?.replacingOccurrences(of: "\\s+$", with: "", options: .regularExpression) else { fatalError("Bad input") }
let arr: [Int] = arrTemp.split(separator: " ").map {
if let arrItem = Int($0) {
return arrItem
} else { fatalError("Bad input") }
}
guard arr.count == n else { fatalError("Bad input") }
plusMinus(arr: arr)
It's a very basic code, but when developing apps, I often lose the basic Swift syntax.
So I plan to complete the one-month kit first. Unlike other test sites, Hacker Rank provides code for the part that receives input values (I'm also attaching this part for study).
'Computer Science > Algorithm with Code' 카테고리의 다른 글
Hacker Rank_5/54 tests (Easy, Lonely Integer) (0) | 2024.05.09 |
---|---|
Hacker Rank_4/54 tests (Easy, Sparse Array) (0) | 2024.05.09 |
Hacker Rank_3/54 tests (Easy, Time Conversion) (0) | 2024.05.08 |
Hacker Rank_2/54 tests (Easy, Min-Max Sum) (0) | 2024.05.07 |
Updated_Hacker Rank (Intermediate, Equal) (0) | 2024.05.06 |