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 places after the decimal.
Note: This challenge introduces precision problems. The test cases are scaled to six decimal places, though answers with absolute error of up to are acceptable.
Example
There are elements, two positive, two negative and one zero. Their ratios are , and . Results are printed as:
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
Print
Print the ratios of positive, negative and zero values in the array. Each value should be printed on a separate line with digits after the decimal. The function should not return a value.
Input Format
The first line contains an integer, , the size of the array.
The second line contains space-separated integers that describe .
Constraints
Output Format
Print the following lines, each to decimals:
- proportion of positive values
- proportion of negative values
- proportion of zeros
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
-----------------------------------------xxxxxxxx-----------------------------
Java Code
2021
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class Result {
/*
* Complete the 'plusMinus' function below.
*
* The function accepts INTEGER_ARRAY arr as parameter.
*/
public static void plusMinus(List<Integer> arr) {
// porpostion of positive numbers
// porpostion of negative numbers
// zeros
int positive_numbers=0;
int negative_numbers=0;
int zero_numbers=0;
int total_numbers=arr.size();
for(Integer var: arr) {
if(var ==0) {
zero_numbers+=1;
}
else if(var <0) {
negative_numbers+=1;
}else {
positive_numbers+=1;
}
}
double positive=(double)positive_numbers/total_numbers;
double negative=(double)negative_numbers/total_numbers;
double zeros=(double)zero_numbers/total_numbers;
System.out.println(String.format("%.6f",positive));
System.out.println(String.format("%.6f",negative));
System.out.println(String.format("%.6f",zeros));
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(bufferedReader.readLine().trim());
List<Integer> arr = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
.map(Integer::parseInt)
.collect(toList());
Result.plusMinus(arr);
bufferedReader.close();
}
}

После ремонта мне задумалось купить новая входная дверь. Выбрал https://dvershik.ru благодаря удобной навигации по сайту и детальным описаниям товаров. Заказ был сделан строго в оговоренные сроки, монтажники отличились профессионализмом и аккуратностью. Доволен качеством двери и предоставленными услугами, всем рекомендую!
Way cool! Some extremely valid points! I appreciate you penning this post and the rest of the site is also very good.
You are so interesting! I do not think I’ve truly read a single thing like this before. So wonderful to find another person with original thoughts on this subject matter. Seriously.. many thanks for starting this up. This web site is something that is required on the web, someone with a bit of originality.
Прошлым месяцем мне понадобилось обновить входную дверь в квартире. Обратился на сайт https://dvershik.ru, выбрал модель и заказал установку. Мастера приехали строго по расписанию, компетентно и оперативно смонтировали новую дверь. Очень доволен сервисом и результатом – теперь чувствую себя намного безопаснее!
There are some attention-grabbing closing dates in this article but I don?t know if I see all of them middle to heart. There may be some validity but I’ll take maintain opinion till I look into it further. Good article , thanks and we would like extra! Added to FeedBurner as nicely
Отправиться в увлекательное путешествие по Байкалу – это как воплотить свои самые смелые мечты в реальность. Именно такую возможность предоставляет нам байкальский отдых турагентство. Здесь нас встречает широкий выбор туров, олицетворяющих весь величественный дух этого уникального места.
Каждый тур от FanatBaikala.ru – это возможность узнать Байкал совершенно новым образом. От походов по живописным маршрутам до увлекательных экскурсий на комфортабельных судах – здесь каждый найдет что-то по своему вкусу.
Особый интерес вызывает бухта песчаная из листвянки – это настоящий рай для любителей природы и экзотических пейзажей. Нежные песчаные пляжи, окруженные сосновым лесом, создают удивительную атмосферу умиротворения и спокойствия.
Не упустите возможность окунуться в мир удивительных открытий с FanatBaikala.ru!
I have noticed that online education is getting popular because accomplishing your degree online has developed into popular method for many people. Many people have certainly not had a possible opportunity to attend a regular college or university yet seek the increased earning possibilities and a better job that a Bachelors Degree grants. Still others might have a qualification in one discipline but would want to pursue something they now possess an interest in.
After exploring a few of the blog posts on your web site, I truly appreciate your way of blogging. I book marked it to my bookmark webpage list and will be checking back soon. Please visit my website too and let me know your opinion.
When I originally left a comment I seem to have clicked the -Notify me when new comments are added- checkbox and now whenever a comment is added I recieve four emails with the same comment. Is there a way you can remove me from that service? Cheers.
Иркутск – это врата к величественному Байкалу, и отправиться в незабываемое путешествие по этому удивительному месту можно с помощью иркутск туры на байкал 2024. Это турагентство предлагает множество захватывающих маршрутов, которые помогут раскрыть всю красоту и уникальность этого региона.
FanatBaikala.ru приглашает нас в увлекательное путешествие, где каждый день наполнен новыми открытиями и впечатлениями. От экскурсий по историческим местам до пеших прогулок по живописным тропам – здесь есть все, чтобы сделать ваш отдых незабываемым.
Особенно привлекательно купить путевки на байкал через FanatBaikala.ru – это быстро, удобно и доступно каждому. Незабываемые приключения ждут вас на берегах Байкала, а FanatBaikala.ru поможет вам воплотить в жизнь ваши мечты о незабываемом отдыхе!