Coding 3min: Symmetric Sort ( 6 kyu )

문제

This is the simple version of Shortest Code series. If you need some challenges, please try the challenge version

Task:

Give you a number array(element range:1-99, array length range: 6-40), please do a "Symmetric Sort" with it.

rule: sort the number, the first smallest number at the left side, the second smaller number at the right side, and so on...

Example:

example1:                        example2:

array=[1,2,3,4,5,6,7,8,9]        array=[1,1,2,2,3,3,4,4,5]

after sort, should return:       after sort, should return:

      [1,3,5,7,9,8,6,4,2]              [1,2,3,4,5,4,3,2,1]

See more example at the testcases.

배열을 앞뒤로 한개씩 넣으면서 정렬

풀이

function sc(array){
  let result = [];
  array.sort((a,b) => { return b-a });
  while ( array.length > 0 ) {
    result.unshift(array.shift());
    if ( array.length === 0 ) break;
    result.push(array.shift());
  }
  return result.length % 2 ? result : result.reverse();
}

큰수부터 차례로 언시프트, 푸시하고 배열의 길이가 짝수라면 뒤집어서 리턴

다른 사람의 풀이

function sc(a) {
  a = a.slice().sort((x,y) => x - y);
  var left = a.filter((v,i) => i % 2 == 0);
  var right = a.filter((v,i) => i % 2 == 1).reverse();
  return left.concat(right);
}

개고슈다


+ Recent posts