Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Problem Can we fit remaining passengers in the bus using JavaScript
Problem
We need to write a JavaScript function that determines if a bus can accommodate all waiting passengers. The function takes three parameters:
cap ? the total capacity of people the bus can hold (excluding the driver)
on ? the number of people currently on the bus (excluding the driver)
wait ? the number of people waiting to board the bus
If there's enough space for everyone, return 0. Otherwise, return the number of passengers who cannot board.
Solution
The logic is straightforward: calculate total passengers needed (current + waiting) and compare with capacity.
const cap = 120;
const on = 80;
const wait = 65;
const findCapacity = (cap, on, wait) => {
let totalPassengers = on + wait;
if (totalPassengers > cap) {
return totalPassengers - cap; // Return excess passengers
}
return 0; // Everyone can fit
};
console.log(findCapacity(cap, on, wait));
Output
25
How It Works
In this example:
- Bus capacity: 120 passengers
- Currently on bus: 80 passengers
- Waiting to board: 65 passengers
- Total needed: 80 + 65 = 145 passengers
- Excess: 145 - 120 = 25 passengers cannot board
Alternative Examples
// Everyone can fit console.log(findCapacity(50, 20, 25)); // 0 // Exactly at capacity console.log(findCapacity(100, 60, 40)); // 0 // Overcapacity console.log(findCapacity(30, 25, 10)); // 5
0 0 5
Optimized Version
We can make the function more concise using Math.max():
const findCapacityOptimized = (cap, on, wait) => {
return Math.max(0, (on + wait) - cap);
};
console.log(findCapacityOptimized(120, 80, 65)); // 25
console.log(findCapacityOptimized(50, 20, 25)); // 0
25 0
Conclusion
This bus capacity problem demonstrates basic arithmetic logic and conditional statements in JavaScript. The solution efficiently determines passenger overflow by comparing total demand with available capacity.
