TIL_22 : Brute Force

JaHyeon Gu·2021년 8월 2일
0

Algorithm

목록 보기
4/7
post-thumbnail

🙄 알고리즘 패러다임


자주 나타나는 알고리즘들을 묶어서 알고리즘 패러다임이라고 부름
여러 알고리즘 패러다임으로 같은 문제 접근 가능



🙄 Brute Force


➡ Brute Force란?

  • Brute-Force Attack : 무차별 대입 공격
  • 가능한 모든 방법을 시도
  • 가장 순진한 알고리즘 접근법

➡ Brute Force 평가

  • 비효율적인 알고리즘

➡ Brute Force 장점

  • 직관적이고 명확함 >>> 코드를 구현하기도 쉬움
  • 모든 경우의 수를 따지기 때문에 답을 확실하게 찾을 수 있다.
  • input이 작다면 굳이 효율적인 알고리즘을 찾을 필요가 없다.
  • 효율적인 알고리즘의 첫 시작은 항상 Brute Force



🙄 Brute Force 예시


➡ 거리가 가장 가까운 두 좌표 출력

# 제곱근 사용을 위한 sqrt 함수
from math import sqrt

# 두 좌표 직선 거리를 계산해 주는 함수
def distance(store1, store2):
    return sqrt((store1[0] - store2[0]) ** 2 + (store1[1] - store2[1]) ** 2)

# 가장 가까운 두 좌표 찾아주는 함수
def closest_pair(coordinates):
    shortest = distance(coordinates[0], coordinates[1])
    for i in range(len(coordinates)):
        for j in range(i + 1, len(coordinates)):
            dist = distance(coordinates[i], coordinates[j])
            if dist < shortest:
                shortest = dist
                shortest_loc = [coordinates[i], coordinates[j]]
            
    return shortest_loc

test_coordinates = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)]
print(closest_pair(test_coordinates))

# [(2, 3), (3, 4)]
profile
IWBAGDS

0개의 댓글

관련 채용 정보