Given an array of integers, calculate the ratios of its elements that are positive, negative, and zero.

2 0
Read Time:2 Minute, 15 Second

Given an array of integers, calculate the ratios of its elements that are positivenegative, 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:

  1. proportion of positive values
  2. proportion of negative values
  3. 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();
    }
}
Happy
Happy
30 %
Sad
Sad
20 %
Excited
Excited
10 %
Sleepy
Sleepy
10 %
Angry
Angry
30 %
Surprise
Surprise
0 %

About Author

Average Rating

5 Star
39%
4 Star
21%
3 Star
15%
2 Star
21%
1 Star
3%

977 thoughts on “Given an array of integers, calculate the ratios of its elements that are positive, negative, and zero.

  1. После ремонта мне задумалось купить новая входная дверь. Выбрал https://dvershik.ru благодаря удобной навигации по сайту и детальным описаниям товаров. Заказ был сделан строго в оговоренные сроки, монтажники отличились профессионализмом и аккуратностью. Доволен качеством двери и предоставленными услугами, всем рекомендую!

  2. 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.

  3. Прошлым месяцем мне понадобилось обновить входную дверь в квартире. Обратился на сайт https://dvershik.ru, выбрал модель и заказал установку. Мастера приехали строго по расписанию, компетентно и оперативно смонтировали новую дверь. Очень доволен сервисом и результатом – теперь чувствую себя намного безопаснее!

  4. 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

  5. Отправиться в увлекательное путешествие по Байкалу – это как воплотить свои самые смелые мечты в реальность. Именно такую возможность предоставляет нам байкальский отдых турагентство. Здесь нас встречает широкий выбор туров, олицетворяющих весь величественный дух этого уникального места.

    Каждый тур от FanatBaikala.ru – это возможность узнать Байкал совершенно новым образом. От походов по живописным маршрутам до увлекательных экскурсий на комфортабельных судах – здесь каждый найдет что-то по своему вкусу.

    Особый интерес вызывает бухта песчаная из листвянки – это настоящий рай для любителей природы и экзотических пейзажей. Нежные песчаные пляжи, окруженные сосновым лесом, создают удивительную атмосферу умиротворения и спокойствия.

    Не упустите возможность окунуться в мир удивительных открытий с FanatBaikala.ru!

  6. 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.

  7. 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.

  8. 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.

  9. Иркутск – это врата к величественному Байкалу, и отправиться в незабываемое путешествие по этому удивительному месту можно с помощью иркутск туры на байкал 2024. Это турагентство предлагает множество захватывающих маршрутов, которые помогут раскрыть всю красоту и уникальность этого региона.

    FanatBaikala.ru приглашает нас в увлекательное путешествие, где каждый день наполнен новыми открытиями и впечатлениями. От экскурсий по историческим местам до пеших прогулок по живописным тропам – здесь есть все, чтобы сделать ваш отдых незабываемым.

    Особенно привлекательно купить путевки на байкал через FanatBaikala.ru – это быстро, удобно и доступно каждому. Незабываемые приключения ждут вас на берегах Байкала, а FanatBaikala.ru поможет вам воплотить в жизнь ваши мечты о незабываемом отдыхе!

Leave a Reply

Your email address will not be published. Required fields are marked *