Skip to content

Instantly share code, notes, and snippets.

@brunodb3
Created February 19, 2019 00:02
Show Gist options
  • Save brunodb3/88188e744ed3b9fde8849d6fc6daa0c5 to your computer and use it in GitHub Desktop.
Save brunodb3/88188e744ed3b9fde8849d6fc6daa0c5 to your computer and use it in GitHub Desktop.
DAZN Challenge Question 12
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment