Algorithm / 카펫

알고리즘 코드카타

목록 보기
32/59

문제

프로그래머스 / 카펫

1) 문제 풀이

func solution(_ brown:Int, _ yellow:Int) -> [Int] {
    var height: Int = 1
    var width: Int = yellow + 2
    var total: Int = (width*2+height*2)
    
    while brown < total {
        height += 1
        width = (yellow / height) + 2
        total = (width*2+height*2)
        
        if width <= 3 {
            break
        }
    }
    
    if (height+2) > width {
        return [height+2, width]
    } else {
        return [width, height+2]
    }
}

결과

2) 코드 개선

❌ 문제점

  • 잘못된 while 조건
    • 이 조건은 brown보다 total이 클 때 루프를 반복.
    • 그러나 목표는 (width - 2) * (height - 2) == yellow이면서 (width * height - yellow == brown)이 되도록 모든 조합을 탐색하는 것
    • 현재 코드에서는 일부 조합을 놓칠 수 있으며, 조건 충족 없이 break될 가능성도 존재
  • 잘못된 width 계산 방식
    • yellowheight로 나눠지지 않으면 정사각형이 되지 않으며, (yellow % height) != 0인 경우도 고려하지 않아 비정확
  • total 사용 오류
    • total = (width*2 + height*2) 이 식은 테두리 길이만 구하는 것이고, 문제에서 구하고자 하는 것은 (전체넓이 - 노란색) 임.
    • 즉, brown == width * height - yellow가 정확한 수식임.

✅ 개선점

  • 전체 격자의 넓이는 brown + yellow
  • yellow는 (width - 2) * (height - 2)여야 함
  • 모든 (height, width) 조합 중 이 조건을 만족하는 경우를 찾는다.
func solution(_ brown: Int, _ yellow: Int) -> [Int] {
    let total = brown + yellow
    
    for height in 3...total {
        if total % height != 0 { continue }
        
        let width = total / height
        
        if (width - 2) * (height - 2) == yellow {
            return [width, height]
        }
    }
    
    return []
}

결과

profile
이유있는 코드를 쓰자!!

0개의 댓글