[Programmers] 카펫 - JAVA

ONE·2022년 2월 15일
0

Programmers

목록 보기
7/24

📚 Problem

카펫

  • 갈색 격자수는 노란색 격자의 테두리를 둘러싼 모습
  • 갈색 격자 수와 노란색 격자 수가 주어졌을 때 전체 카펫의 가로 세로 길이 구하기

📝 Solution

Key Idea

  • brown 의 가로값을 3부터 증가시키며
  • 전체격자수를 brown의 가로값으로 나누었을때 딱 떨어지고,
  • yellow 의 가로 세로는 brown 의 가로, 세로보다 각각 2씩 작기 때문에
  • 이를 이용해 yellow 의 격자 개수와 yellow 의 가로, 세로를 곱한 값을 비교
private void solving(int brown, int yellow, int[] answer) {
    int sum = brown + yellow;

    for (int i = 3; i <= sum; i++) {
        if(sum % i != 0)
            continue;
        if (i >= sum / i && isYellowRight(i, brown, yellow)) {
            answer[0] = i;
            answer[1] = sum / i;
            return;
        }
    }
}

💻 Code

Solution.java

class Solution {
    public int[] solution(int brown, int yellow) {
        // 두 개의 합을 두 개의 곱으로 나타낸다

        int[] answer = new int[2];

        solving(brown, yellow, answer);

        return answer;
    }

    private boolean isYellowRight(int bw, int brown, int yellow) {
        int bh = (brown + yellow) / bw;
        int yw = bw - 2;
        int yh = bh - 2;

        return yellow == yw * yh;
    }

    private void solving(int brown, int yellow, int[] answer) {
        int sum = brown + yellow;

        for (int i = 3; i <= sum; i++) {
            if(sum % i != 0)
                continue;
            if (i >= sum / i && isYellowRight(i, brown, yellow)) {
                answer[0] = i;
                answer[1] = sum / i;
                return;
            }
        }
    }
}

SolutionTest.java

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertArrayEquals;

public class SolutionTest {
    Solution solution;

    @BeforeEach
    public void setSol(){
        solution = new Solution();
    }

    @Test
    public void solution_1(){
        int[] result = solution.solution(10, 2);
        assertArrayEquals(new int[]{4, 3}, result);
    }

    @Test
    public void solution_2(){
        int[] result = solution.solution(8, 1);
        assertArrayEquals(new int[]{3, 3}, result);
    }

    @Test
    public void solution_3(){
        int[] result = solution.solution(24, 24);
        assertArrayEquals(new int[]{8, 6}, result);
    }
}
profile
New, Strange, Want to try

0개의 댓글