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. Как-то недавно я оказался в ситуации, когда мне срочно нужны были деньги. Было много вопросов и нехватка времени. И тут мне на помощь пришли займы онлайн на карту. Я оформил заявку прямо у себя дома, заполнив все необходимые данные. И неожиданно быстро, в течение нескольких часов, деньги поступили на мою карту. Займы срочно на карту – это настоящее спасение в сложных ситуациях.

    Наши спонсоры – займы срочно на карту

  2. In a world where style and functionality often come at a premium, finding that perfect accessory that doesn’t break the bank is always a win. When it comes to timepieces, a watch for men low price from our collection is not just an accessory, but a statement piece, a blend of elegance, reliability, and affordability that’s hard to come by.

    Each watch in our collection is a testament to the art of fine watchmaking, where every detail, from the intricate movements to the elegant designs, is crafted with precision and care. It’s an experience of luxury and refinement that’s accessible, making the eloquence of finely crafted watches a pleasure that’s not just reserved for the few.

    In the sphere of smartwatches, technology and innovation take center stage. If you’re looking to step into the future of timekeeping and connectivity without stretching your budget, our smart watch low price offerings are your gateway. Experience a world where the boundaries between technology and style blur, where every notification, every update, is a seamless part of your aesthetic.

    Our collection is a journey through the elegance of classic watchmaking and the innovation of modern technology, a journey where every piece is a discovery, every watch, a world in itself. Dive in, explore, and adorn your wrist with a timepiece that’s not just about telling time, but about expressing style, embodying elegance, and living the technological revolution. Every tick, every tock, is a step into a world where time is experienced, lived, and cherished.

  3. Now, I will create a straightforward text advertisement incorporating these anchor texts.

    Discover a world where elegance, precision, and affordability intersect. At Furfurfriend, we believe that a quality timepiece is an essential accessory for every modern man, a silent testament to his style and elegance. That’s why we invite you to buy mens watches online from our exquisite collection, where each piece is a meticulously crafted work of art, designed to offer unmatched style without compromising on quality.

    If you’re looking for something specific, something that exudes elegance and offers exceptional value, we have curated a special collection just for you. Explore watches 400 dollars, where luxury meets affordability. Every watch in this range is a harmonious blend of traditional craftsmanship and contemporary design, ensuring that you make a statement without uttering a word.

    Dive into our world, where every tick of the clock is a celebration of style, every piece a journey through the meticulous art of watchmaking. Your perfect timepiece, encapsulating the pinnacle of design, precision, and affordability, awaits. Don’t just keep time, celebrate it with Furfurfriend. Your journey to unmatched elegance and style begins with a click. Welcome to a world where every second counts. Welcome to Furfurfriend.

  4. Станьте готовыми к зиме с оригинальными Угги! Купить Угги можно у нас – в нашем интернет-магазине. Не упустите возможность приобрести теплые и стильные Угги уже сегодня и наслаждайтесь зимой в полной мере!

    Сайт: uggaustralia-msk.ru
    Адрес: Москва, 117449, улица Винокурова, 4к1

  5. Производство световодов в России solargy.ru

    Предлагаем Вам единую в России систему естественного освещения SOLARGY для помещений без окон или с небольшим освещением. Может быть идеальным решением освещения для множества объектов, как жилых домов, так и производственных помещений, фабрик, столовых. Узнайте все подробности на онлайн портале solargy.ru уже сейчас.

    Если Вам нужно расчет коэффициента естественного освещения в Казани, то Вы на верном пути. Наша фирма работает в данной сфере уже большое количество лет и знает всё о данном типе освещения. КЕО значит прекрасной альтернативой обычным окнам, увеличивает яркость естественного и искусственного освещения. Наши реализованные проекты и их фотографии можно увидеть на нашем веб сайте. Это: школьные комплексы, производства, частные дома, столовые и многие другие проекты.

    Оформить запрос на КЕО расчет можно на solargy.ru в любое удобное для Вас время. В специальной форме введите собственные данные: название организации, ФИО, должность, номер телефона для связи и другие. А также подробные комментарии по поводу будущих работ. Мы Вам перезвоним в самом скором времени с итоговым расчетом и дадим все советы.

    По поводу купить световод обращайтесь в нашу фирму. Мы находимся по адресу: г. Ижевск, Проспект конструктора М. Т. Калашникова, д. 7. Звоните по телефону 8(800)200-0-602 и наши специалисты дадут ответы на все Ваши вопросы. Световоды на сегодняшний день являются трендом дизайна многих помещений. А также, их можно добавить в строительство на любом моменте, что очень удобно. При том, в подборе огромное количество разновидностей световодов различных цветов и размеров и любой покупатель подберет под себя, что ему нужно. В любом случае, мы окажем Вам помощь в подборе, проконсультируем и предоставим все рекомендации. Звоните прямо сейчас, мы будем рады с Вами работать.

  6. UGG 2023 года уже доступны на нашей распродаже! Приходите и выбирайте из огромного ассортимента моделей. Купить UGG стало легче и доступнее, чем когда-либо!

    Сайт: uggaustralia-msk.ru
    Адрес: Москва, 117449, улица Винокурова, 4к1

  7. Открытие своего малого бизнеса требовало срочного финансирования. С помощью портала cntbank.ru я быстро нашел подходящий займ. Акция “займ без процентов” помогла мне сэкономить на стартапе.

  8. Do you want to become a Canadian citizen and have a business?

    Canadian business immigration programs offer opportunities for entrepreneurs and investors to establish and expand their businesses in Canada. These programs typically include options like the Start-Up Visa Program, Provincial Nominee Programs, and the Work Permit Programs. They provide a pathway for eligible individuals to obtain permanent residency in Canada by making significant investments or starting and managing businesses, contributing to the country’s economic growth and development.

    “Unlock the secrets to business success! Read our article now and take your business to new heights. Click here to get started.”

    https://arnikavisa.com/canada-investor-visa-learn-about-investment-immigration

Leave a Reply

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