Skip to content

Instantly share code, notes, and snippets.

@andersonleite
Created July 4, 2019 18:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andersonleite/2cef86ad3a8992d5c11a4bfe11dda977 to your computer and use it in GitHub Desktop.
Save andersonleite/2cef86ad3a8992d5c11a4bfe11dda977 to your computer and use it in GitHub Desktop.
avoidObstacles
/**
You are given an array of integers representing coordinates of obstacles situated on a straight line.
Assume that you are jumping from the point with coordinate 0 to the right. You are allowed only to make jumps of the same length represented by some integer.
Find the minimal length of the jump enough to avoid all the obstacles.
Example
For inputArray = [5, 3, 6, 7, 9], the output should be avoidObstacles(inputArray) = 4.
*/
function avoidObstacles(inputArray) {
let max = Math.max(...inputArray)
let jump = 2
for(; jump<=max; jump++){
if(jumps(jump, max, inputArray)){
return jump
}
}
return jump++
}
function jumps(jump, max, inputArray){
let pos = 0 + jump
while(pos <= max){
if(inputArray.includes(pos)){
return false
}
pos += jump
}
return true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment