Sorting on planet Twisted-3-7 ( 6 kyu )

문제

There is a planet… in a galaxy far far away. It is exactly like our planet, but it has one difference:

The values of the digits 3 and 7 are twisted. Our 3 means 7 on the planet Twisted-3-7. And 7 means 3.

Your task is to create a method, that can sort an array the way it would be sorted on Twisted-3-7.

7 Examples from a friend from Twisted-3-7:

[1,2,3,4,5,6,7,8,9] -> [1,2,7,4,5,6,3,8,9]
[12,13,14] -> [12,14,13]
[9,2,4,7,3] -> [2,7,4,3,9]

3과 7이 바뀌었다 가정하고 정렬하는 문제

풀이

function sortTwisted37(array) {
  function change(val) {
    let result = val.toString().split('');
    for ( let i = 0; i < result.length; i++ ) {
      if ( result[i] === '3' ) result[i] = '7';
      else if ( result[i] === '7' ) result[i] = '3';
    }
    return Number(result.join(''));
  }
  let arr = array.slice().map( a => change(a) );
  arr.sort((a,b) => a-b);
  return arr.map( a => change(a) )
}

3,7을 바꿔 정렬 후 다시 바꿔줌

다른 사람의 풀이

function sortTwisted37(array) {
  const MAPPING = {7:3,3:7};

  return array.slice().sort((a,b) => twist(a) - twist(b));

  function twist(number) {
    return parseInt(number.toString().replace(/[37]/g,a=>MAPPING[a]));
  }
}

replace로 동시에 처리하려는 방법을 생각했는데 이렇게 하는 방법이 있었다.

왕꿀팁


+ Recent posts