Here is a nested array [[1,5], [2,4], [6,8], [7,7]]
, and I need to compare each items second index (departure
) to the following items first index (arrival
) like so: 5 >= 2
, 4 >= 6
, 8 >= 7
and finally 7 >= 1
.
My code on the other hand only compares once (so [1,5]
and [2,4]
) and omits the rest.
Please don’t mind the rest of the code; it doesn’t really make sense as it’s just a draft and right now I just need to know how the customers (departure
) and (arrival
) times can be compared continuously. I was thinking of using a while loop instead of an if statement but I keep getting
fatal error: javascript heap out of memory’
console.log(allocateRooms([[1,5], [2,4], [6,8], [7,7]]));
function allocateRooms(c) {
let s = c.sort((a, b) => a[0] - b[0])
let rooms = [];
for (let i = 0; i < s.length; i++) {
for (let j = i + 1; j < s[i].length; j++) {
let depart = s[i][1];
let arrive = s[j][0];
if (depart >= arrive) {
rooms.push(s.indexOf(s[i]) + 1)
rooms.push(s.indexOf(s[j]) + 1)
} else {
rooms.push(0)
}
}
}
return rooms
}
2
Answers
You can solve it by using one loop. You are on the right path by using
.sort()
, but instead of using two loops, one loop could be sufficient. You just have to iterate through the array and compare the departure of the current with the arrival of the next item.which returns:
So, in case your departure is greater than the arrival it pushes current and next items to the rooms array, else it pushes
0
.You can do something like this
Working sample: https://stackblitz.com/edit/vitejs-vite-daf2tz?file=main.js