Sunday, October 4, 2020

HACKERRANK ALGORITHMS - PLUS MINUS

 HACKERRANK ALGORITHMS - PLUS MINUS 

QUESTION

SOLUTION 

IN C

#include <assert.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** split_string(char*);

// Complete the plusMinus function below.
void plusMinus(int arr_count, int* arr) {
    float cplus = 0, cminus = 0, czero = 0;
    int i;
    for(i = 0; i < arr_count; i++){
        if(arr[i]> 0)
            cplus++;
        else if(arr[i] < 0)
            cminus++;
        else
            czero++;
    }
    printf("%f\n%f\n%f\n", cplus/arr_count, cminus/arr_count, czero/arr_count);
}

int main()
{
    char* n_endptr;
    char* n_str = readline();
    int n = strtol(n_str, &n_endptr, 10);

    if (n_endptr == n_str || *n_endptr != '\0') { exit(EXIT_FAILURE); }

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

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

    for (int i = 0; i < n; i++) {
        char* arr_item_endptr;
        char* arr_item_str = *(arr_temp + i);
        int arr_item = strtol(arr_item_str, &arr_item_endptr, 10);

        if (arr_item_endptr == arr_item_str || *arr_item_endptr != '\0') { exit(EXIT_FAILURE); }

        *(arr + i) = arr_item;
    }

    int arr_count = n;

    plusMinus(arr_count, 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; }

        size_t new_length = alloc_length << 1;
        data = realloc(data, new_length);

        if (!data) { break; }

        alloc_length = new_length;
    }

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

    data = realloc(data, data_length);

    return data;
}

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;
}

No comments:

Post a Comment

LEETCODE JUNE 2021 DAILY CODING CHALLENGE

 LEETCODE JUNE 2021 DAILY CODING CHALLENGE JUNE 1 JUNE 2 JUNE 3 JUNE 4 JUNE 5 Maximum Performance of a Team LINK You are given two integers ...