Distributing Bananas Problem in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

Suppose there are n people standing in a queue, we wish to distribute bananas to the people in the following way −

• We give 1 banana to the first person, 2 bananas to the second person, and so on until we give n bananas to the last person.

• Then, we go back to the start of the row, giving n + 1 bananas to the first person, n + 2 bananas to the second person, and so on until we give 2 * n bananas to the last person.

• This process repeats (with us giving one more banana each time, and moving to the start of the row after we reach the end) until we run out of candies. The last person will receive all of our remaining bananas.

We are required to write a JavaScript function that takes in the number of people, num, as the first argument, and the number of bananas, m, as the second argument.

Our function should return an array (of length num sum m) that represents the final distribution of bananas.

For example, if the input to the function is −

const num = 3;
const m = 10;

Then the output should be −

const output = [5, 2, 3];

Output Explanation:

On the first turn, res[0] += 1, and the array is [1,0,0].

On the second turn, res[1] += 2, and the array is [1,2,0].

On the third turn, res[2] += 3, and the array is [1,2,3].

On the fourth turn, res[0] += 4, and the final array is [5,2,3].

Example

The code for this will be −

Live Demo

const num = 3;
const m = 10;
const distributeBananas = (num = 1, m = 1) => {
const res = new Array(num).fill(0);
let curr = 1;
while(true){
for(let i = 0; i < num; i++){
if(m < curr){
res[i] += m
return res
};
res[i] += curr;
m -= curr;
curr++;
};
};
};
console.log(distributeBananas(num, m));

Output

And the output in the console will be −

[5, 2, 3]
Published on 07-Apr-2021 07:36:32