관리 메뉴

나만을 위한 블로그

[Algorithm] 프로그래머스 - 직사각형 넓이 구하기 (Kotlin) 본문

알고리즘 문제 풀이/프로그래머스

[Algorithm] 프로그래머스 - 직사각형 넓이 구하기 (Kotlin)

참깨빵위에참깨빵_ 2023. 1. 11. 21:37
728x90
반응형
2차원 좌표 평면에 변이 축과 평행한 직사각형이 있다. 직사각형 네 꼭짓점의 좌표 [[x1, y1], [x2, y2], [x3, y3], [x4, y4]]가 담긴 배열 dots가 매개변수로 주어질 때, 직사각형의 넓이를 리턴하는 solution()을 완성하라

 

 

그림으로 어떤 값을 빼야 하는지는 알았지만 어떻게 그 값을 얻어내 계산해야 할지 감도 안 왔던 문제였다. 다른 사람의 풀이를 참고했다.

 

https://mycodingreview.tistory.com/entry/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4%EC%A7%81%EC%82%AC%EA%B0%81%ED%98%95%EB%84%93%EC%9D%B4

 

[프로그래머스/Java] Lv.0 직사각형 넓이 구하기

문제 풀이 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 import java.util.ArrayList; import java.util.HashSet; class Solution { //조건이 x축, y축과 평행한 직사각형이므로 x좌표와 y좌표는 각각 두개씩 publi

mycodingreview.tistory.com

class Solution {
    fun solution(dots: Array<IntArray>): Int {
        var answer = 0
        val xc = HashSet<Int>()
        for (i in 0..3) {
            xc.add(dots[i][0])
        }
        val arr1 = ArrayList(xc)
        val x1 = arr1[0]
        val x2 = arr1[1]
        val yc = HashSet<Int>()
        for (i in 0..3) {
            yc.add(dots[i][1])
        }
        val arr2 = ArrayList(yc)
        val y1 = arr2[0]
        val y2 = arr2[1]
        answer = Math.abs((x1 - x2) * (y1 - y2))
        return answer
    }
}

 

이것을 간단하게 하면 아래처럼 된다.

 

class Solution {
    fun solution(dots: Array<IntArray>): Int =
    dots.sortedWith(compareBy<IntArray> { it[0] }.thenBy { it[1] })
        .let { (A, _, _, B) ->
            (B[0] - A[0]) * (B[1] - A[1])
        }
}
class Solution {
    fun solution(dots: Array<IntArray>): Int {
        val coordX = dots.map { it[0] }.toSortedSet()
        val coordY = dots.map { it[1] }.toSortedSet()

        return (coordX.last() - coordX.first()) * (coordY.last() - coordY.first())
    }
}

 

맨 위의 코드부터 차례대로 파악해야겠다.

반응형
Comments