- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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];

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].

The code for this will be −

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));

And the output in the console will be −

[5, 2, 3]

- Related Questions & Answers
- Koko Eating Bananas in C++
- Snail Trail Problem in JavaScript
- Recursive Staircase problem in JavaScript
- Distributing all balls without repetition in C++ Program
- Recursion problem Snail Trail in JavaScript
- Expressive words problem case in JavaScript
- 2 Key keyboard problem in JavaScript
- Meeting Rooms 2 problem in JavaScript
- Crack Alphabets fight problem in JavaScript
- Combination sum problem using JavaScript
- The algorithm problem - Backtracing pattern in JavaScript
- Two sum problem in linear time in JavaScript
- Solve the Sherlock and Array problem in JavaScript
- Solution to the clumsy factorial problem in JavaScript
- Parse and balance angle brackets problem in JavaScript

Advertisements