-
[Algorithm] 버전 비교 알고리즘 (Version Compare)Algorithm 2019. 7. 26. 23:39
프로젝트 진행 중 두 개의 버전을 비교해야 할 일이 있었습니다.
단순 버전 코드 비교가 아니고 major.minor.hotfix 형식의 String형 비교였기 때문에, 복잡한 알고리즘은 아니지만 나중에 사용할 수도 있어 기록합니다.
목표
두 개의 버전이 주어졌을 때 비교하여 큰 버전을 반환하시오.
버전은 major.minor.hotfix(1.0.0)의 형태로 제한됩니다.입력 예시
"1.0.0", "2.0.2"
출력 예시
"2.0.2"
코드
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersclass VersionCompare { init { compareVersion("1.0.0", "1.0.1") compareVersion("1.0.0", "1.1.0") compareVersion("1.0.0", "2.0.0") compareVersion("1.0.9", "2.0.1") compareVersion("1.9.0", "2.1.0") compareVersion("4.0.0", "3.0.0") } /** * v1, v2를 비교해 높은 버전을 반환합니다. * major.minor.hotfix 형식만 지원합니다. */ private fun compareVersion(v1: String, v2: String, index: Int = 0): String { try { val code1 = v1.split(".")[index] val code2 = v2.split(".")[index] val nextIndex = index + 1 when { code1 < code2 -> return v2 code1 == code2 -> { return compareVersion(v1, v2, nextIndex) } else -> return v1 } } catch (e: IndexOutOfBoundsException) { return v1 } } } 'Algorithm' 카테고리의 다른 글
[Codility] CyclicRotation (0) 2020.11.20 [Codility] BinaryGap (0) 2020.11.19