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
Finding the sum of floors covered by an elevator in JavaScript
Problem
We need to write a JavaScript function that calculates the total number of floors covered by an elevator. The function takes an array representing the floor numbers where the elevator stopped, and returns the sum of distances traveled between consecutive stops.
Understanding the Logic
The elevator covers floors by moving between consecutive stops. If it goes from floor 7 to floor 1, it covers 6 floors (7-1). If it then goes from floor 1 to floor 7, it covers another 6 floors (7-1). The total distance is the sum of absolute differences between consecutive floors.
Solution
const arr = [7, 1, 7, 1];
const floorsCovered = (arr = []) => {
let res = 0;
for (let i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
res += arr[i] - arr[i + 1];
}
if (arr[i] < arr[i + 1]) {
res += arr[i + 1] - arr[i];
}
}
return res;
};
console.log(floorsCovered(arr));
18
Step-by-Step Breakdown
Let's trace through the example array [7, 1, 7, 1]:
const arr = [7, 1, 7, 1];
const floorsCoveredDetailed = (arr = []) => {
let res = 0;
console.log("Elevator stops:", arr);
for (let i = 0; i < arr.length - 1; i++) {
let distance = Math.abs(arr[i] - arr[i + 1]);
res += distance;
console.log(`From floor ${arr[i]} to floor ${arr[i + 1]}: ${distance} floors`);
}
console.log(`Total floors covered: ${res}`);
return res;
};
floorsCoveredDetailed(arr);
Elevator stops: [ 7, 1, 7, 1 ] From floor 7 to floor 1: 6 floors From floor 1 to floor 7: 6 floors From floor 7 to floor 1: 6 floors Total floors covered: 18
Optimized Solution Using Math.abs()
We can simplify the code using Math.abs() to calculate absolute differences:
const floorsCoveredOptimized = (arr = []) => {
let total = 0;
for (let i = 0; i < arr.length - 1; i++) {
total += Math.abs(arr[i] - arr[i + 1]);
}
return total;
};
// Test with different examples
console.log(floorsCoveredOptimized([7, 1, 7, 1])); // 18
console.log(floorsCoveredOptimized([1, 2, 3, 4])); // 3
console.log(floorsCoveredOptimized([10, 5, 8])); // 8
18 3 8
Key Points
- The algorithm calculates the sum of distances between consecutive elevator stops
- Distance is always positive, regardless of direction (up or down)
- The loop runs
arr.length - 1times to avoid accessing undefined elements - Using
Math.abs()simplifies the conditional logic
Conclusion
This solution efficiently calculates total floors covered by summing absolute differences between consecutive stops. The optimized version using Math.abs() provides cleaner, more readable code.
