Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function widestGap(n, start, finish) {
- // Write your code here
- let gaps = []
- let positionsWithCars = []
- let positionsWithoutCars = []
- const getCarPositions = (start, end, step) => {
- // returns all the positions a car occupies
- // there's a bug when a car occupies positions such as [2,2], this is solved with a temporary solution:
- // if (carPositions[1] == undefined) carPositions[1] = car.finish;
- const length = Math.floor(Math.abs((end - start) / step)) + 1;
- return Array.from(Array(length), (x, index) => start + index * step);
- }
- // looping each position on the grid
- for (let position = 0; position <= n; position++) {
- // looping the cars
- for (let startIndex = 0; startIndex < start.length; startIndex++) {
- // creating a car reference
- let car = { start: start[startIndex], finish: finish[startIndex] };
- let carPositions = getCarPositions(car.start, car.finish, 1)
- // fixing bug for cars that are only one position wide
- if (carPositions[1] == undefined) carPositions[1] = car.finish;
- // checking if the current position has a car
- if (carPositions[0] <= position && position <= carPositions[1]) positionsWithCars.push(position)
- }
- // pushing the positions without cars
- if (!positionsWithCars.includes(position)) positionsWithoutCars.push(position)
- }
- // reducing the positions without cars to create arrays of sequential positions
- const result = positionsWithoutCars.reduce((accumulator, currentValue) => {
- // getting the last inner array
- const lastSubArray = accumulator[accumulator.length - 1];
- // checking if the last inner array's last item is different than the last value
- if(!lastSubArray || lastSubArray[lastSubArray.length - 1] !== currentValue - 1) {
- // if so, we create a new array
- accumulator.push([]);
- }
- // adding the value to the array (if we pushed a new one, this is the first value there)
- accumulator[accumulator.length - 1].push(currentValue);
- // returning the accumulator (the array of inner arrays)
- return accumulator;
- }, []);
- // getting all the array lengths
- let arrayLengths = result.map(function(innerArray){return innerArray.length;});
- // returning the biggest array length
- return Math.max(...arrayLengths)
- }
- // testing the implementation
- const result = widestGap(10, [2, 3, 8], [2, 4, 9]);
- console.log(result)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement