개발의변화
프로그래머스 LV2 파일명 정렬(카카오) 본문
반응형
문제
https://school.programmers.co.kr/learn/courses/30/lessons/17686
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
해설
function solution(files) {
files.sort((a,b)=>{
a=a.toLowerCase()
b=b.toLowerCase()
let findIndexA = a.split("").findIndex((x)=>{
return !isNaN(parseInt(x))
})
let findIndexB = b.split("").findIndex((x)=>{
return !isNaN(parseInt(x))
})
let arrA = a.slice(0,findIndexA)
let arrNumberA = a.slice(findIndexA)
let arrB = b.slice(0,findIndexB)
let arrNumberB = b.slice(findIndexB)
if (arrA>arrB) {
return 1
}
else if (arrA == arrB) {
let finalNumberA = arrNumberA.split("").findIndex((x)=>isNaN(parseInt(x)))
let finalNumberB = arrNumberB.split("").findIndex((x)=>isNaN(parseInt(x)))
finalNumberA= finalNumberA>=0 ? parseInt(arrNumberA.slice(0,finalNumberA)) : parseInt(arrNumberA)
finalNumberB= finalNumberB>=0? parseInt(arrNumberB.slice(0,finalNumberB)) : parseInt(arrNumberB)
return finalNumberA - finalNumberB
}
else {
return -1
}
})
return files
}
문자열 Head 그리고 Number에 따라 조건에 맞게 정렬을 하면 된다.
sort()안에서 해결하려고 노력을 했다.
Head부분을 문자열안에서 잘라내 비교한 후 만약 Head 부분이 같으면 숫자부분인 Number를 비교하는 것으로 해결했다.
포인트는 숫자를 비교할 때 Number 뒤에 Tail이 없는 경우와 문자열 중 공백은 IsNaN에서 false를 리턴한다는 것을 알았어야 했다.
Tail이 없는 경우는 삼항연산자로 처리했고 isNaN에 공백이 숫자로 판정나는것은 해당 문자에 parseInt를 활용해서 나타냈다
반응형
'알고리즘' 카테고리의 다른 글
프로그래머스 LV2 질문목록 (0) | 2023.04.12 |
---|---|
프로그래머스 LV2 프렌즈블록 (0) | 2023.04.11 |
프로그래머스 LV2 피보나치 수 (0) | 2023.04.02 |
프로그래머스 LV2 괄호 회전하기 (0) | 2023.04.01 |
프로그래머스 LV2 방문길이 (0) | 2023.03.28 |