이번 글은 아래 포스팅을 참고하여 작성하였습니다.
[프로그래머스/자바스크립트(JavaScript)] 문자열 내 마음대로 정렬하기
🎯 문자열 내 마음대로 정렬하기 📁 문제 출처 코딩테스트 연습 - 문자열 내 마음대로 정렬하기 문자열로 구성된 리스트 strings와, 정수 n이 주어졌을 때, 각 문자열의 인덱스 n번째 글자를 기준
lakelouise.tistory.com
이번 문제를 풀어 보고 싶다면? 아래 링크를 클릭하세요!
내장 메서드인 sort() 및 localeCompare()를 활용하면 쉽게 풀 수 있는 문제이다.
sort()의 경우 숫자뿐만 아니라 문자열 정렬도 가능하다. 보통 String.sort((a, b) =>{...})와 같이 작성하게 되는데 a와 b의 대소관계에 따라 반환값이 결정된다. 즉 sort([compareFunction])에서 compareFunction의 반환값에 따라 정렬 방식이 바뀌는 것이다.(아래 반환값은 오름차순 기준이다. 내림차순은 반대로 적으면 된다.)
- a > b ? return 1. compareFunction에서 반환값이 0보다 클 경우 b를 a보다 작은 색인으로 인식하여 정렬.
- b > a ? return -1. compareFunction에서 반환값이 0보다 작을 경우 a를 b보다 작은 색인으로 인식하여 정렬.
- a = b ? return 0. 두 요소를 정렬하지 않고 모든 다른 요소들을 정렬.
이를 활용하여 반환값을 구할 때 (a > b) - (a < b)와 같이 적을 수도 있는데
- (a > b) 가 true (a < b)가 false면 1 - 0으로 1을 반환
- (a > b)가 false (a < b) 가 true면 0 - 1으로 -1을 반환
위와 같이 1 아니면 -1을 반환하므로 sort() 메서드를 통해 문자열을 정렬할 수 있는 것이다.
localeCompare() 메서드의 경우 참조 문자열.localeCompare(비교 문자열)과 같이 적는데 참조 문자열과 비교 문자열 간의 대소관계에 따라 반환값이 바뀐다.
- 참조 문자열 > 비교 문자열 ? return 1
- 비교 문자열 > 참조 문자열 ? return -1
- 참조 문자열 = 비교 문자열 ? return 0
위와 같은 sort() 및 localeCompare() 메서드의 동작 원리를 이해하는 데 매우 유익한 문제이지 싶다.
Solutions
Solutions
function solution(strings, n) { /* sort() Ver. */ strings.sort((a, b) => { if (a[n] > b[n]) return 1; if (a[n] < b[n]) return -1; if (a[n] === b[n]) if (a > b) return 1 else return -1 return 0 const first = a[n] const second = b[n] /* Using Boolean */ if (first === second) return (a > b) - (a < b) else return (first > second) - (first < second) }) return strings /* localeCompare() Ver. */ return strings.sort((a, b) => a[n] === b[n] ? a.localeCompare(b) : a[n].localeCompare(b[n])) }
함께 보기
Array.prototype.sort() - JavaScript | MDN
The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units val
developer.mozilla.org
String.prototype.localeCompare() - JavaScript | MDN
The localeCompare() method returns a number indicating whether a reference string comes before, or after, or is the same as the given string in sort order. In implementations with Intl.Collator API support, this method simply calls Intl.Collator.
developer.mozilla.org
'👩💻 Programming > Coding Test 문제 풀이' 카테고리의 다른 글
[Programmers] level 1: 문자열 내림차순으로 배치하기 by JavaScript (0) | 2022.07.09 |
---|---|
[Programmers] level 1: 문자열 내 p와 y의 개수 by JavaScript (0) | 2022.07.09 |
[Programmers] level 1: 두 정수 사이의 합 by JavaScript (0) | 2022.07.09 |
[Programmers] level 1: 나누어 떨어지는 숫자 배열 by JavaScript (0) | 2022.07.09 |
[Programmers] level 1: 같은 숫자는 싫어 by JavaScript (0) | 2022.07.09 |
댓글