Search code examples
javascriptarraysalgorithm

How to generated N numbers in array that sum of these numbers is equal to 0


I have a code like this:

function myArr(N){

    let arr = [];

    function randomNumber(min,max) {
        if (min > max) {
            let vMin = min;
            min = parseInt(max,10);
            max = parseInt(vMin,10);
        }
        return Math.floor(Math.random()*(max-min+1)+min);
    }

    for(let i = 0; i < N; i++) {
        arr.push(randomNumber(100,-100));
    }
    return arr;
}

This function generates an array with N numbers. But I want that the sum of these generated numbers will be equal to 0. How to make it? I was thinking about conditional 'if' but I don't exactly know, how to use it in this case ... Maybe some of you know, how to do this? Thanks for any tips!


Solution

  • This is my solution, basically you do a for loop and start adding elements.

    Whenever you add an element, just add the same element * -1

    You will end up with an array of elements with sum 0.

    function arrayOfSumZero(N) {
        let sum = 0;
        let i = N % 2 === 0 ? 0 : 1;
        let output = [];
    
        for (i; i < N; i++) {
            if (output.length < N) {
                sum += i;
                output.push(i);
            }
    
            if (sum > 0) {
                sum += i * -1;
                output.push(i * -1);
            }
        }
    
        return output;
    }