티스토리 뷰

Codesignal

code signal - 22. avoidObstacles

터보건 2020. 2. 20. 19:57

Question

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.

    Check out the image below for better understanding:

    image


Input/Output

  • [execution time limit] 4 seconds (py3)

  • [input] array.integer inputArray

    Non-empty array of positive integers.

    Guaranteed constraints: 2 ≤ inputArray.length ≤ 1000, 1 ≤ inputArray[i] ≤ 1000.

  • [output] integer

    • The desired length

MY_ANSWER

def avoidObstacles(inputArray):
    for n in range(1, max(inputArray)):  # all은 모든요소가 참이면 true 출력
        if all(i%n for i in inputArray): # 일반적으로 0이면 false, 0이 아닌수는 true 
            return n   # 여기서 출력되는 n은 모든 리스트에서 나머지를 가지는 수, 즉 이동가능한 수이다. 그중 최소값 선택
    return max(inputArray)+1 #모두 나머지를 가지는 수를 해당 범위에서 찾을수 없으면 max + 1을 해준다.
  • input Array에 있는 숫자를 거치지 않는 이동 간격을 구하는 문제.

    일반적으로 표현하면 정해진 범위에서 input Array의 약수가 아닌 수를 구한다면 정답이 될 것이다. 예를 들어 , inputArray = [1, 4, 10, 6, 2] 일때 return(이동범위)이 5이면, 5는 10의 약수이기 때문에 input Array에 있는 10을 거치게 된다. 마찬가지로 3도 6의 약수이기 때문에 가능하지 않다. 주어진 범위에서 7,8,9가 약수를 가지지 않는데 그 중에 가장 작은 7을 이동 범위로 출력하면 답이다.

    만약 모두 약수를 가지는 경우 해당 최대 범위에서 +1을 해준다.

  • code로 살펴보면 inputArray에 원소를 1부터 9까지 나눌 때 하나라도 나머지가 0이 된다면 해당 원소가 약수를 가진다는 의미이기 때문에 all()을 이용해 false를 출력하고 아닐 경우 true를 출력한다.

  • 아무리봐도 잘 이해가 되지 않아서 사진으로 설명!

    image

    동그라미로 표현한 부분이 input Array원소가 해당 숫자로 나누어지니 약수를 가진다고 보면 된다.


Best_ANSWER

def avoidObstacles(inputArray):
    c = 2
    while True:
        if sorted([i%c for i in inputArray])[0]>0:
            return c
        c += 1
  • 이번문제는 답을 보았기에 위 아래 코드가 비슷한 것을 느낄 수 있다.
  • list comprehension과 while 구문을 이용해 간략하게 표현되어 있는 것을 알 수 있다.

 

'Codesignal' 카테고리의 다른 글

code signal - 24. Minesweeper  (0) 2020.02.22
code signal - 23. boxBlur  (0) 2020.02.20
code signal - 21. isIPv4Address  (0) 2020.02.19
code signal - 20. arrayMaximalAdjacentDifference  (0) 2020.02.19
code signal - 19. areEquallyStrong  (0) 2020.02.19
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함