skip to Main Content

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


  1. 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.

    function allocateRooms(c) {
      let s = c.sort((a, b) => a[0] - b[0]);
      let rooms = [];
    
      for (let i = 0; i < s.length - 1; i++) {
        let depart = s[i][1];  
        let arrive = s[i + 1][0]; 
    
        if (depart >= arrive) {
          rooms.push([i + 1, i + 2]); 
        } else {
          rooms.push(0);
        }
      }
    
      return rooms;
    }
    
    console.log(allocateRooms([[1, 5], [2, 4], [6, 8], [7, 7]]));

    which returns:

    [[1, 2], 0, [3, 4]]
    

    So, in case your departure is greater than the arrival it pushes current and next items to the rooms array, else it pushes 0.

    Login or Signup to reply.
  2. You can do something like this

    let arr = [
      [1, 5],
      [2, 4],
      [6, 8],
      [7, 7],
    ];
    
    for (let i = 0; i < arr.length; i++) {
      let depart = arr[i][1];
      let arrive = arr[i + 1 === arr.length ? 0 : i + 1][0];
      console.log(depart, arrive);
      //your compare logic
    }

    Working sample: https://stackblitz.com/edit/vitejs-vite-daf2tz?file=main.js

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search