Distributing Bananas Problem in JavaScript

The distributing bananas problem involves giving bananas to people in a queue following a specific pattern. We start by giving 1 banana to the first person, 2 to the second, and so on. After reaching the end, we continue from the beginning with increasing amounts until all bananas are distributed.

Problem Statement

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 bananas. The last person will receive all of our remaining bananas.

We need to write a JavaScript function that takes the number of people (num) and the total number of bananas (m), returning an array representing the final distribution.

Example Input and Output

For example, if we have:

const num = 3;
const m = 10;

Then the expected output should be:

[5, 2, 3]

Distribution Process

Let's trace through the distribution process:

  • Turn 1: Give 1 banana to person 0 ? [1, 0, 0]

  • Turn 2: Give 2 bananas to person 1 ? [1, 2, 0]

  • Turn 3: Give 3 bananas to person 2 ? [1, 2, 3]

  • Turn 4: Give 4 bananas to person 0 ? [5, 2, 3]

At this point, we've distributed all 10 bananas (1 + 2 + 3 + 4 = 10).

Solution

const distributeBananas = (num = 1, m = 1) => {
    const res = new Array(num).fill(0);
    let curr = 1;
    
    while (true) {
        for (let i = 0; i 

[5, 2, 3]

How It Works

The algorithm works by:

  • Creating an array res initialized with zeros to track each person's bananas

  • Using curr to track the current number of bananas to distribute

  • Iterating through people in a circular manner using a for loop inside while

  • If remaining bananas are less than curr, giving all remaining bananas to the current person

  • Otherwise, giving curr bananas to the current person and incrementing curr

Testing with Different Values

// Test with different values
console.log("Test 1:", distributeBananas(4, 15));
console.log("Test 2:", distributeBananas(2, 7));
console.log("Test 3:", distributeBananas(5, 20));
Test 1: [6, 2, 3, 4]
Test 2: [4, 3]
Test 3: [1, 2, 3, 4, 10]

Conclusion

This solution efficiently distributes bananas in a circular pattern, ensuring all bananas are distributed while following the specified rules. The algorithm handles edge cases where remaining bananas are fewer than the next distribution amount.

Updated on: 2026-03-15T23:19:00+05:30

415 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements