본문 바로가기
알고리즘/Codewars

[Codewars] Your order, please (6 kyu) / JavaScript

by fluss 2022. 10. 14.

https://www.codewars.com/kata/55c45be3b2079eccff00010f/javascript

 

Codewars - Achieve mastery through coding practice and developer mentorship

Coding practice for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

Your task is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result.

Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).

If the input string is empty, return an empty string. The words in the input String will only contain valid consecutive numbers.

 

Examples

"is2 Thi1s T4est 3a"  -->  "Thi1s is2 3a T4est"
"4of Fo1r pe6ople g3ood th5e the2"  -->  "Fo1r the2 g3ood 4of th5e pe6ople"
""  -->  ""

 

설명:

당신은 주어진 문자열을 정렬해야 합니다. 문자열의 각 단어는 하나의 숫자를 포함합니다. 숫자는 결과에 그 단어가 있어야할 위치입니다.

참고: 숫자는 1부터 9까지일 수 있습니다. 그러므로 (0이 아니고) 1이 첫번째 단어가 됩니다.

만약 입력된 문자열이 비었다면 빈 문자열을 반환합니다. 입력된 문장의 단어는 유효한 연속적인 단어만 포함합니다.

 

예시

"is2 Thi1s T4est 3a"  -->  "Thi1s is2 3a T4est"
"4of Fo1r pe6ople g3ood th5e the2"  -->  "Fo1r the2 g3ood 4of th5e pe6ople"
""  -->  ""

 

풀이

function order(words){
  return words.split(' ').sort((a, b) => a.match(/\d/) - b.match(/\d/)).join(' ');
}

match로 문자열에서 숫자를 찾고('\d'는 숫자를 의미하는 정규식) 그 숫자를 기준으로 sort한 배열을 반환한다.

 

참고

https://stackoverflow.com/questions/29180284/can-javascript-sort-strings-containing-numbers

 

can javascript sort strings containing numbers?

I'm making a little web-app in which I used AHK and javascript. I make AHK a group of images paths to the .js file something like this var importedFiles = [ "file:///F:/image1.jpg", "file:///F:/

stackoverflow.com

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes

 

Character classes - JavaScript | MDN

Character classes distinguish kinds of characters such as, for example, distinguishing between letters and digits.

developer.mozilla.org

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/match

 

String.prototype.match() - JavaScript | MDN

match() 메서드는 문자열이 정규식과 매치되는 부분을 검색합니다.

developer.mozilla.org

https://codechacha.com/ko/javascript-extract-number-from-string/

 

JavaScript - 문자열에서 숫자만 추출

자바스크립트에서 정규식을 이용하여 문자열에서 숫자만 추출하는 방법을 소개합니다. 문자 사이에 숫자들이 있을 때, 문자를 모두 제거하고 남은 숫자들을 하나의 숫자로 이어서 `123456`을 추

codechacha.com

 

댓글