TIL (2022.02.14)
➕ 오늘 푼 문제
프로그래머스 - 카펫
➕ 아이디어
- 전체 타일 수를 구한다.(total = brown + yellow)
- 가로(width)는 세로(height)보다 크거나 같으므로, 가로와 세로는 다음과 같이 나타낼 수 있다.
- height = 1부터 total / 2까지의 수들
- width = total / height
- 각 경우에 brown 타일 수를 구한다.
- brown = 2 width + 2 (height - 2)
- 문제 조건으로 인해, 저 공식을 벗어나게 타일 수를 가지는 경우는 없다.
- 타일 수가 같다면, 그때의 가로 세로 길이를 반환한다.
➕ Java 코드
class Solution {
public int[] solution(int brown, int yellow) {
int[] answer = new int[2];
int total = brown + yellow;
for(int height=1; height<total/2; height++){
if(total%height == 0){
int width = total / height;
int b = 2*width + 2*(height-2);
if(brown == b){
answer[0] = width;
answer[1] = height;
return answer;
}
}
}
return answer;
}
}
➕ Python 코드
def solution(brown, yellow):
answer = []
total = brown + yellow
for height in range(1, total//2):
if total % height == 0:
width = total // height
b = 2 * width + 2 * (height - 2)
if b == brown:
answer = [width, height]
break
return answer
➕ 궁금한 내용 및 소감
- 간단한 수학적 공식을 찾아내면 쉽게 풀 수 있는 문제였다. 이런 문제는 자주 풀 수록 감이 느는 것 같다. 앞으로도 꾸준히 문제 풀면서 감을 잃지 않도록 노력하겠다!
➕ 참고 문헌