Advertisement
Guest User

Untitled

a guest
Feb 21st, 2019
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.44 KB | None | 0 0
  1. function widestGap(n, start, finish) {
  2. // Write your code here
  3. let gaps = []
  4. let positionsWithCars = []
  5. let positionsWithoutCars = []
  6.  
  7. const getCarPositions = (start, end, step) => {
  8. // returns all the positions a car occupies
  9. // there's a bug when a car occupies positions such as [2,2], this is solved with a temporary solution:
  10. // if (carPositions[1] == undefined) carPositions[1] = car.finish;
  11. const length = Math.floor(Math.abs((end - start) / step)) + 1;
  12. return Array.from(Array(length), (x, index) => start + index * step);
  13. }
  14.  
  15. // looping each position on the grid
  16. for (let position = 0; position <= n; position++) {
  17. // looping the cars
  18. for (let startIndex = 0; startIndex < start.length; startIndex++) {
  19. // creating a car reference
  20. let car = { start: start[startIndex], finish: finish[startIndex] };
  21.  
  22. let carPositions = getCarPositions(car.start, car.finish, 1)
  23.  
  24. // fixing bug for cars that are only one position wide
  25. if (carPositions[1] == undefined) carPositions[1] = car.finish;
  26.  
  27. // checking if the current position has a car
  28. if (carPositions[0] <= position && position <= carPositions[1]) positionsWithCars.push(position)
  29. }
  30.  
  31. // pushing the positions without cars
  32. if (!positionsWithCars.includes(position)) positionsWithoutCars.push(position)
  33. }
  34.  
  35. // reducing the positions without cars to create arrays of sequential positions
  36. const result = positionsWithoutCars.reduce((accumulator, currentValue) => {
  37. // getting the last inner array
  38. const lastSubArray = accumulator[accumulator.length - 1];
  39.  
  40. // checking if the last inner array's last item is different than the last value
  41. if(!lastSubArray || lastSubArray[lastSubArray.length - 1] !== currentValue - 1) {
  42. // if so, we create a new array
  43. accumulator.push([]);
  44. }
  45.  
  46. // adding the value to the array (if we pushed a new one, this is the first value there)
  47. accumulator[accumulator.length - 1].push(currentValue);
  48.  
  49. // returning the accumulator (the array of inner arrays)
  50. return accumulator;
  51. }, []);
  52.  
  53. // getting all the array lengths
  54. let arrayLengths = result.map(function(innerArray){return innerArray.length;});
  55.  
  56. // returning the biggest array length
  57. return Math.max(...arrayLengths)
  58. }
  59.  
  60.  
  61. // testing the implementation
  62. const result = widestGap(10, [2, 3, 8], [2, 4, 9]);
  63. console.log(result)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement