Advertisement
PowerCell46

Train JS

Nov 29th, 2022
1,117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function train(array) {
  2.  
  3.     let peopleInTheWagons = array[0]; // number of passengers that are currently in a wagon.
  4.     peopleInTheWagons = peopleInTheWagons.split(" ");
  5.     let maxCapacityOfAWagon = Number(array[1]); // the max capacity of each wagon
  6.     peopleInTheWagons = peopleInTheWagons.map(x => Number(x));
  7.     let leftSeatsArray = [];
  8.  
  9.     for (let index = 0; index < Number(peopleInTheWagons.length); index++) {
  10.         let currentNum = peopleInTheWagons[index];
  11.         leftSeatsArray.push(maxCapacityOfAWagon - currentNum);
  12.     }
  13.  
  14.     for (let index = 2; index < Number(array.length); index++) {
  15.         let currentInput = array[index];
  16.         currentInput = currentInput.split(" ");
  17.         if (currentInput[0] === "Add") {
  18.             peopleInTheWagons.push(Number(currentInput[1]));
  19.             leftSeatsArray.push(maxCapacityOfAWagon - Number(currentInput[1]));
  20.         } else {
  21.             currentInput = Number(currentInput[0]);
  22.             let index1 = 0;
  23.             while (currentInput > leftSeatsArray[index1]) {
  24.                 index1++;
  25.             }
  26.             let newNumber = (peopleInTheWagons[index1] + currentInput);
  27.             let newNumberDivide = leftSeatsArray[index1] - currentInput;
  28.             leftSeatsArray.splice(index1, 1, newNumberDivide);
  29.             peopleInTheWagons.splice(index1, 1, newNumber);
  30.         }
  31.     }
  32.     console.log(peopleInTheWagons.join(" "));
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement