[프로그래머스] 카펫

당당·2023년 5월 28일
0

프로그래머스

목록 보기
144/245

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

📔문제

Leo는 카펫을 사러 갔다가 아래 그림과 같이 중앙에는 노란색으로 칠해져 있고 테두리 1줄은 갈색으로 칠해져 있는 격자 모양 카펫을 봤습니다.

Leo는 집으로 돌아와서 아까 본 카펫의 노란색과 갈색으로 색칠된 격자의 개수는 기억했지만, 전체 카펫의 크기는 기억하지 못했습니다.

Leo가 본 카펫에서 갈색 격자의 수 brown, 노란색 격자의 수 yellow가 매개변수로 주어질 때 카펫의 가로, 세로 크기를 순서대로 배열에 담아 return 하도록 solution 함수를 작성해주세요.


🚫제한사항

갈색 격자의 수 brown은 8 이상 5,000 이하인 자연수입니다.
노란색 격자의 수 yellow는 1 이상 2,000,000 이하인 자연수입니다.
카펫의 가로 길이는 세로 길이와 같거나, 세로 길이보다 깁니다.


📝입출력 예

brownyellowreturn
102[4, 3]
81[3, 3]
2424[8, 6]

🧮알고리즘 분류

  • 완전탐색

📃소스 코드

class Solution {
    public int[] solution(int brown, int yellow) {
        int[] answer = new int[2];
        int total=brown+yellow;
        int[] divisor=new int[total];
        boolean isLoop=true;
        
        int start=1;
        int count=0;
        while(start<=total){
            if(total%start==0){
                divisor[count]=start;
                count++;
            }
            if((double)total/start==start){
                divisor[count]=start;
                count++;
            }
            start++;
            
            if(start>total){
                break;
            }
        }
        
        if(count==2){
            answer[0]=total;
            answer[1]=1;
            return answer;
        }
        int horizon=divisor[count/2];
        int vertical=divisor[count/2-1];
        int plus=1;
        while(isLoop){
            int round=horizon*2+vertical*2-4;
            
            if(brown!=round){
                try{
                    horizon=divisor[count/2+plus];
                    vertical=divisor[count/2-1-plus];
                }catch(ArrayIndexOutOfBoundsException e){
                    System.out.println("Here");
                }
                
            }
            else{
                break;
            }
            plus++;
        }
        
        answer[0]=horizon;
        answer[1]=vertical;
        
        return answer;
    }
}

📰출력 결과


📂고찰

남들이 다 틀린다는 4,6,7이 아니라 4,5,7에서 심지어 런타임 에러가 떠서 왜그런가 했더니 약수 계산을 잘못했다.

4*4=16 과 같은 것 처럼 중복해서 저장해주려고 했다보니 total/start==start와 같은 식으로 계산했는데, double이 아니라 int형이다 보니 정수부분만 같아도 같다고 계산해서 오류가 발생한 것이었다.

그리고

brown=16, yellow=8
return=[8,3]

겉의 한 줄만 brown이기 때문에 둘레를 겉의 칸을 구해서 그것이 brown이랑 같을 때 답이고 같지 않으면 다음 약수로 계산해서 확인해야 한다.

profile
MySQL DBA 신입 지원

0개의 댓글