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[i + 1]) {
res += arr[i] - arr[i + 1];
}
if (arr[i]
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
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
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.
