orderWords.js

Codewars 알고리즘 풀이


Problem

  • 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.
    • 이 숫자는 위치를 나타낸다.
  • Numbers can be from 1 to 9.
    • 숫자는 1부터 9까지 가능하다.
  • So 1 will be the first word (not 0).
    • 따라서 0이 아닌 1이 첫 단어이다.



Solution 01

function orderWords(str) {
  return str.split(' ').sort((a, b) => a.match(/\d+/g) - b.match(/\d+/g)).join(' ');
}

orderWords('T4est is2 Thi1s 3a');  // Thi1s is2 3a T4est
orderWords('is2 Thi1s T4est 3a');  // Thi1s is2 3a T4est
orderWords('3a is2 T4est Thi1s');  // Thi1s is2 3a T4est


Solution 02

function orderWords(str) {
  return str.split(' ').sort((a, b) => a.replace(/[^\d]/g, '') - b.replace(/[^\d]/g, '')).join(' ');
}

orderWords('T4est is2 Thi1s 3a');  // Thi1s is2 3a T4est
orderWords('is2 Thi1s T4est 3a');  // Thi1s is2 3a T4est
orderWords('3a is2 T4est Thi1s');  // Thi1s is2 3a T4est


Solution 03

function orderWords(str) {
  return str.split(' ').sort((a, b) => a[a.search(/\d+/g)] = b[b.search(/\d+/g)]).join(' ');
}

orderWords('T4est is2 Thi1s 3a');  // Thi1s is2 3a T4est
orderWords('is2 Thi1s T4est 3a');  // Thi1s is2 3a T4est
orderWords('3a is2 T4est Thi1s');  // Thi1s is2 3a T4est


Solution 04

function orderWords(str) {
  let arr = str.split(' ');
  let result = [];
  
  for (let i = 0; i <= arr.length; i++) {
    for (let j = 0; j < arr.length; j++) {
      if (arr[j].indexOf(i) >= 0) {
        result.push(arr[j]);
      }
    }
  }
  return result.join(' ');
}

orderWords('T4est is2 Thi1s 3a');  // Thi1s is2 3a T4est
orderWords('is2 Thi1s T4est 3a');  // Thi1s is2 3a T4est
orderWords('3a is2 T4est Thi1s');  // Thi1s is2 3a T4est


Solution 05

function orderWords(str) {
  let words = str.split(' ');
  let result = [];
  
  for (let i = 1; i < words.length + 1; i++) {
    result.push(words.find(word => word.includes(i)));
  }
  return result.join(' ');
}

orderWords('T4est is2 Thi1s 3a');  // Thi1s is2 3a T4est
orderWords('is2 Thi1s T4est 3a');  // Thi1s is2 3a T4est
orderWords('3a is2 T4est Thi1s');  // Thi1s is2 3a T4est