[프로그래머스] 42842 카펫

jyleever·2022년 7월 15일
0

알고리즘

목록 보기
7/26

문제

https://school.programmers.co.kr/learn/courses/30/lessons/42842

풀이

  • brown + yellow 하여 총 타일의 수 total 구함
  • 합이 될 수 있는 곱셉의 조합 구함 : (x, y), 즉 x * y = total
  • 각 조합의 숫자를 2씩 빼서 곱했을 때 yellow가 되는지 확인
  • yellow가 되게 하는 x, y가 정답
  • 이 때 x >= y 임을 주의 (가로가 세로보다 같거나 커야 한다)

코드

/**
* brown + yellow 하여 총 타일의 수 total 구함
* 합이 될 수 있는 곱셉의 조합 구함 : (x, y) x * y = total
* 각 조합의 숫자를 2씩 빼서 곱했을 때 yellow가 되는지 확인
* yellow가 되게 하는 x, y가 정답
* 이 때 x >= y
**/

import java.util.ArrayList;
class point{
    int x, y;
    
    public point(int x, int y){
        this.x = x;
        this.y = y;
    }
}

class Solution {
    public int[] solution(int brown, int yellow) {
        int[] answer = new int[2];
        
        int total = brown + yellow;
        
        ArrayList<point> pt = new ArrayList<>();
        
        for(int i=1; i<=total; i++){
            if(total % i == 0 && i >= total/i){
                pt.add(new point(i, total/i));
            }
        }
        
        for(point pts : pt){
            if(pts.x - 2 > 0 && pts.y - 2 > 0){
                if((pts.x - 2) * (pts.y - 2) == yellow){
                    answer[0] = pts.x;
                    answer[1] = pts.y;
                }
            }
        }
        return answer;
    }
}

0개의 댓글