Created
July 4, 2019 18:33
-
-
Save andersonleite/2cef86ad3a8992d5c11a4bfe11dda977 to your computer and use it in GitHub Desktop.
avoidObstacles
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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