Skip to content

Instantly share code, notes, and snippets.

@eduardonunesp
Last active June 7, 2018 08:32
Show Gist options
  • Save eduardonunesp/1321bd2ab1dd0af1fabd7de0c144615d to your computer and use it in GitHub Desktop.
Save eduardonunesp/1321bd2ab1dd0af1fabd7de0c144615d to your computer and use it in GitHub Desktop.
/*
Given an array of integers, calculate which fraction of its elements are positive, which fraction of its elements are negative, and which fraction of its elements are zeroes, respectively. Print the decimal value of each fraction on a new line.
Note: This challenge introduces precision problems. The test cases are scaled to six decimal places, though answers with absolute error of up to 10−410−4 are acceptable.
Input Format
The first line contains an integer, NN, denoting the size of the array.
The second line contains NN space-separated integers describing an array of numbers (a0,a1,a2,…,an−1)(a0,a1,a2,…,an−1).
Output Format
You must print the following 33 lines:
A decimal representing of the fraction of positive numbers in the array.
A decimal representing of the fraction of negative numbers in the array.
A decimal representing of the fraction of zeroes in the array.
Sample Input
6
-4 3 -9 0 4 1
Sample Output
0.500000
0.333333
0.166667
Explanation
*/
function main() {
var n = parseInt(readLine());
arr = readLine().split(' ');
arr = arr.map(Number);
var filter = (arr) => {
return function() {
var funcs = Array.prototype.slice.call(arguments)
return funcs.map(f => arr.filter(f).length);
}
}
var fractize = (prec) => {
return val => (val/n).toPrecision(prec);
}
var arrFilter = filter(arr);
var arrResult = arrFilter(
n => parseInt(n) > 0,
n => parseInt(n) < 0,
n => parseInt(n) === 0
);
var valueFractizer = fractize(6);
var output = arrResult.map(valueFractizer);
console.log(output.join("\n"));
}
@wcwhite71
Copy link

Here's a shorter way ....

function main() {
var n = parseInt(readLine());
arr = readLine().split(' ');
arr = arr.map(Number);
//console.log(arr);
integerCount(arr);

function integerCount(arr) {
    var negative = 0;
    var positive = 0;
    var zero = 0;
        for (i=0; i<arr.length; i++) {
            if (arr[i]>0) {
                positive++;
            } else if (arr[i]<0) {
                negative++;
            } else {
                zero++;
            }
        }
    console.log(positive/n);
    console.log(negative/n);
    console.log(zero/n);
} 

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment