Skip to content

Instantly share code, notes, and snippets.

@tyler-austin
Created June 2, 2017 17:03
Show Gist options
  • Save tyler-austin/30806adfdf1bbce5f1ef25a66b7409d8 to your computer and use it in GitHub Desktop.
Save tyler-austin/30806adfdf1bbce5f1ef25a66b7409d8 to your computer and use it in GitHub Desktop.
Code Fights - 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.

Input/Output

  • [time limit] 4000ms (py3)

  • [input] array.integer inputArray

    Non-empty array of positive integers.

    Guaranteed constraints:

    2 ≤ inputArray.length ≤ 10,
    1 ≤ inputArray[i] ≤ 40.
    
  • [output] integer

    The desired length.

from typing import List
class AvoidObstacles:
@classmethod
def avoid_obstacles(cls, obstacles: List[int]) -> int:
min_len = 2
found = False
while not found:
if cls._valid_length(obstacles, min_len):
return min_len
elif min_len > 40:
return -1
else:
min_len += 1
@classmethod
def _valid_length(cls, obstacles: List[int], length: int) -> bool:
for o in obstacles:
if o % length == 0:
return False
return True
def avoidObstacles(obstacles: list) -> int:
min_len = 2
found = False
while not found:
if _valid_length(obstacles, min_len):
return min_len
elif min_len > 40:
return -1
else:
min_len += 1
def _valid_length(obstacles: list, length: int) -> bool:
for o in obstacles:
if o % length == 0:
return False
return True
import unittest
from avoid_obstacles import AvoidObstacles
class TestAvoidObstacles(unittest.TestCase):
def test_1(self):
data = [5, 3, 6, 7, 9]
solution = 4
result = AvoidObstacles.avoid_obstacles(data)
self.assertEqual(result, solution)
def test_2(self):
data = [2, 3]
solution = 4
result = AvoidObstacles.avoid_obstacles(data)
self.assertEqual(result, solution)
def test_3(self):
data = [1, 4, 10, 6, 2]
solution = 7
result = AvoidObstacles.avoid_obstacles(data)
self.assertEqual(result, solution)
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment