hacker rank practice Q2 in c

 Hacker rank plus mi minus, min max, time conversion

Question: 

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



Anser: 

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');
Number.prototype.toFixed()
let inputString = '';
let currentLine = 0;

process.stdin.on('data'function(inputStdin) {
    inputString += inputStdin;
});

process.stdin.on('end'function() {
    inputString = inputString.split('\n');

    main();
});

function readLine() {
    return inputString[currentLine++];
}


/*
RTCIdentityAssertion
 * Complete the 'plusMinus' function below.
 *
 * The function accepts INTEGER_ARRAY arr as parameter.
 */

function plusMinus(arr) {
    // Write your code here
 let len = arr.length;
    let positiveCount = 0;
    let negativeCount = 0;
    let zeroCount = 0;
    // Traverse the array and count the
    // total number of positive, negative,
    // and zero elements.
    for(let i = 0; i < arr.length; i++)
    {
        if (arr[i] > 0)
        {
            positiveCount++;
        }
        else if (arr[i] < 0)
        {
            negativeCount++;
        }
        else if (arr[i] == 0)
        {
            zeroCount++;
        }
    }
   process.stdout.write((positiveCount / len).toFixed(4) + " ");
    process.stdout.write(`\n`);
    process.stdout.write((negativeCount / len).toFixed(4) +" ");
     process.stdout.write(`\n`);
     process.stdout.write((zeroCount / len).toFixed(4));
  
    
}

function main() {
    const n = parseInt(readLine().trim(), 10);

    const arr = readLine().replace(/\s+$/g'').split(' ').map(arrTemp => parseInt(arrTemp, 10));

    plusMinus(arr);
}

Anser: in C

#include <assert.h>
#include <ctype.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* readline();
char* ltrim(char*);
char* rtrim(char*);
char** split_string(char*);

int parse_int(char*);

/*
 * Complete the 'miniMaxSum' function below.
 *
 * The function accepts INTEGER_ARRAY arr as parameter.
 */

void miniMaxSum(int arr_count, int* arr) {
     int min = arr[0] ,  max;
     int j;
    for(int i=0; i < arr_count-1;i++)
    {  
      for(int  j=0; j< arr_count-i-1; j++)
      {
          if(arr[j] > arr[j+1])
          {
              min = arr[j];
              arr[j] = arr[j+1];
              arr[j+1] = min;
          }
         
      }
       
    }
   
 long int minimal_sum = 0, max_sum = 0;
    for(int i = 0; i< arr_count-1;i++ )
    {
        minimal_sum += arr[i];
    }

    for(int j = 1; j< arr_count;j++ )
    {
         max_sum += arr[j];
    }

    printf("%ld %ld",minimal_sum,max_sum);

}

int main()
{

    char** arr_temp = split_string(rtrim(readline()));

    int* arr = malloc(5 * sizeof(int));

    for (int i = 0; i < 5; i++) {
        int arr_item = parse_int(*(arr_temp + i));

        *(arr + i) = arr_item;
    }

    miniMaxSum(5, arr);

    return 0;
}

char* readline() {
    size_t alloc_length = 1024;
    size_t data_length = 0;

    char* data = malloc(alloc_length);

    while (true) {
        char* cursor = data + data_length;
        char* line = fgets(cursor, alloc_length - data_length, stdin);

        if (!line) {
            break;
        }

        data_length += strlen(cursor);

        if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') {
            break;
        }

        alloc_length <<= 1;

        data = realloc(data, alloc_length);

        if (!data) {
            data = '\0';

            break;
        }
    }

    if (data[data_length - 1] == '\n') {
        data[data_length - 1] = '\0';

        data = realloc(data, data_length);

        if (!data) {
            data = '\0';
        }
    } else {
        data = realloc(data, data_length + 1);

        if (!data) {
            data = '\0';
        } else {
            data[data_length] = '\0';
        }
    }

    return data;
}

char* ltrim(char* str) {
    if (!str) {
        return '\0';
    }

    if (!*str) {
        return str;
    }

    while (*str != '\0' && isspace(*str)) {
        str++;
    }

    return str;
}

char* rtrim(char* str) {
    if (!str) {
        return '\0';
    }

    if (!*str) {
        return str;
    }

    char* end = str + strlen(str) - 1;

    while (end >= str && isspace(*end)) {
        end--;
    }

    *(end + 1) = '\0';

    return str;
}

char** split_string(char* str) {
    char** splits = NULL;
    char* token = strtok(str, " ");

    int spaces = 0;

    while (token) {
        splits = realloc(splits, sizeof(char*) * ++spaces);

        if (!splits) {
            return splits;
        }

        splits[spaces - 1] = token;

        token = strtok(NULL, " ");
    }

    return splits;
}

int parse_int(char* str) {
    char* endptr;
    int value = strtol(str, &endptr, 10);

    if (endptr == str || *endptr != '\0') {
        exit(EXIT_FAILURE);
    }

    return value;
}


Comments

Popular posts from this blog

Become a Expert + Secret of Success -- ii

Change Detection

without writing media queries How to make responsive component