How To Solve The Plus Minus Code Challenge [C programming language]
How To Solve HackerRank’s Plus Minus Code Challenge With C language
Problem
Let’s break down the challenge into requirements:
- Link to challenge: HackerRank’s Plus Minus Code Challenge
- n(I) = length of array arr, I = 0,1 … 100
- arr = array with values between -100 ≤ arr ≤ 100
- The goal is to console.log 3 values based on the number -ve, +ve, and zeros present in the array.
- Count the number of (positive, negative, zeros) and divide it by the total length of the array to get the ratio.
Examples
// [2, 5, 7, 0,-3,-6,0]
// positive number count = 3
printf(3/7); // 0.42
// Negative number count = 2
print(2/7) // 0.28
// zero number count = 2
print(2/7)
Goal
Write a function or functions that print the ratios for positive, negative, and zero numbers in that order
Covering Our Bases
Making sure we meet the requirements:
#include <stdio.h>
int function (arr)
{
double positives,negatives = 0;
int zeros = 0;
int lengthSize = sizeof(arr) / sizeof(arr[0]);
if (lengthSize > 0 && lengthSize <= 100) {
// continue
}
// output
print((positives / lengthSize) || 0);
print((negatives / lengthSize) || 0);
print((zeros / lengthSize) || 0);
}
Understanding The Problem
This is quite a simple problem. All we need to do is count the number of positives, negatives, and zeros. In order to traverse the array, we’ll use the map function.
void plusMinus(int arr_count, int* arr) {
int positive = 0, negative = 0, zero = 0;
for (int i = 0; i < arr_count; i++) {
if (arr[i] > 0) {
positive++;
} else if (arr[i] < 0) {
negative++;
} else {
zero++;
}
}
double ratioPositive = (double) positive / arr_count;
double ratioNegative = (double) negative / arr_count;
double ratioZero = (double) zero / arr_count;
printf("%.6f\n", ratioPositive);
printf("%.6f\n", ratioNegative);
printf("%.6f\n", ratioZero);
}
Test Cases
Now let’s validate the code:
Input (stdin)
6
-4 3 -9 0 4 1
Your Output (stdout)
0.500000
0.333333
0.166667
Expected Output
0.500000
0.333333
Feedback
If you have any tips on how this can be better optimized or talk about coding, I would love to talk.
If you got value from this, please share it on twitter 🐦 or other social media platforms. Thanks again for reading. 🙏
Please also follow me on Twitter: @white_christx and linkedin at @Whitejsx