Your order, please ( 6 kyu )

문제

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.

For an input: “is2 Thi1s T4est 3a” the function should return “Thi1s is2 3a T4est”

your_order("is2 Thi1s T4est 3a")
[1] "Thi1s is2 3a T4est"

문자열에서 단어마다 숫자가 있는데 숫자 순서대로 나열하는 문제

풀이

function order(words){
  let arr = words.split(' ');
  let num = [];
  for ( let i = 0; i < arr.length; i++ ) {
    num[arr[i].match(/[1-9]/)] = arr[i]
  }
  num.shift();
  return num.join(' ');
}

단어마다 쪼개서 배열로 arr에 담고, num이라는 배열에 숫자 순서대로 담아 join으로 합쳐 리턴

다른 사람의 풀이

function order(words){

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

생각한 방법보다 훨씬 간단하게 접근

신박하군


'자료구조, 알고리즘 > Codewars 문제' 카테고리의 다른 글

Array.diff ( 6 kyu )  (0) 2017.11.30
Are they the "same"? ( 6 kyu )  (0) 2017.11.30
Greed is Good ( 5 kyu )  (0) 2017.11.30
Two Joggers ( 5 kyu )  (0) 2017.11.30
First non-repeating character ( 5 kyu )  (0) 2017.11.30

+ Recent posts