Q:

distribute numbers randomly in javascript

I have 40 fruits and I want to distribute it randomly and store in array of length 10.

See below code inputs.
var fruits = 40;
var arr = [];

And I want output like this
arr = [2,5,1,0,0,3,6,10,0,13];
10 positions of array should be filled randomly but addition of values should be 40.

A:

A recursive divide-and-conquer approach:
function distribute(length, value) {
    if (length <= 1)
        return [value];
    var half = Math.floor(length / 2),
        dist = Math.floor(Math.random() * value);
    return distribute(half, dist).concat(distribute(length-half, value-dist));
}

