본문 바로가기

Algorithm

[Algorithm- LocalDate] Kotlin - programmers Lv1 [ 개인정보 수집 유효기한 ]

[ Algorithm Link ]

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 


 

결과 코드 미리보기

 

fun solution(today: String, terms: Array<String>, privacies: Array<String>): IntArray {
    val dateFormatter = DateTimeFormatter.ofPattern("yyyy.MM.dd")
    val todayInfo = LocalDate.parse(today,dateFormatter)

    val termsInfo = HashMap <String,Int>()
    terms.forEach {
        it.split(" ").run {
            termsInfo.put(this.first(),this.last().toInt())
        }
    }

    return privacies.mapIndexedNotNull { index, str ->
        val expirationDate = LocalDate.parse(str.substringBefore(" "),dateFormatter)

        if (ChronoUnit.MONTHS.between(expirationDate, todayInfo) >= (termsInfo[str.substringAfter(" ")] ?: 9999)) {  index + 1
        	} else { null }
    }.toIntArray()
}

 

[ 리팩토링 내용 ]

  • DateTimeFormatter로 리팩토링 전 날짜 정보를 번거롭게 변환하는 과정 수정.
  • DateTimeFommater로 필요한 날짜 정보로 수정하므로 불필요하게 privacies를 2번 순환하던 문제도 해결되었다.

 

 

 

제출 코드 - 통과 → 리팩토링 전

 

fun solution(today: String, terms: Array<String>, privacies: Array<String>): IntArray {
	var answer: IntArray = intArrayOf()

	val toDayInfo = today.split(".").map {
        it.removePrefix("0").toInt()
    }
    val dateToday = LocalDate.of(toDayInfo[0],toDayInfo[1],toDayInfo[2])

    val termsInfo = HashMap <String,Int>()
        terms.forEach {
        it.split(" ").run {
            termsInfo.put(this.first(),this.last().toInt())
        }
    }

    val privaciesInfo = privacies.map {
        it.split(" ").run {
            val dayInfo = this.first().split(".").map {str ->
                str.removePrefix("0").toInt()
            }

            LocalDate.of(dayInfo[0],dayInfo[1],dayInfo[2]) to it.last()
        }
    }
    
    privaciesInfo.forEachIndexed { index, it ->
        if (ChronoUnit.MONTHS.between(it.first,dateToday) >= termsInfo["${it.second}"]!!){
            answer += index + 1
        }
    }
    return answer
}

 

[ 작성코드 리뷰 ]

  • 먼저 solution의 매개변수들을 각각 원하는 자료 형태로 변환하여 작업하였다.
    • today ➡️ LocalDate
      • ChronoUnit.MONTHS.between(a,b)메서드를 통해 기간의 차이를 계산하기 위함이다.
    • terms ➡️ HaspMap
      • terms의 각 값들은 중복되지 않는 값들 이므로,데이터 양에 상관없이 Key값으로 원하는 데이터에 바로 접근할 수 있는 HaspMap 사용
    • privacies ➡️ Pair<LocalDate,Char>
  • 문제에선 각 Month는 28일이라고 정해주면서 month * 28 로 풀어볼까 생각했지만, 표준 날짜 집합 클래스 ( Chrono Unit ) .between 을 통해 Month의 차이를 간단하게 계산하였다.

🏗️ 리팩토링 방향

  • 1️⃣ privaciesInfo 변수 생성, privaciesInfo.forEach 와 같이 불필요하게 privacies를 2번 순환하는 문제 수정하기.
  • 2️⃣ 날짜 정보를 .split().removePrefix() 메서드 적용 후 LocalDate.of() 를 하여서 코드 가독성 ↓ , 효율 ↓ 단점 수정하기.

 

 

알고리즘 회고

 

알고리즘 푸는 속도가 전보다는 빨라진 것 같다. 풀어놓고 제대로 정리하지 못한 문제들이 많은데, 어거지로 푼 경우가 많아 리팩토링할 엄두가 안나서 건드리지 못하고 있다. 블로그에 작성하면서 복습해보도록 해야겠다. 

 

멤버 변수와 스코프 함수를 적절하게 사용할 수 있도록 신경 써보자.

 

 

 

 

 

 


[Reference]