본문 바로가기
프로젝트들/코딩 테스트

[코딩테스트] 프로그래머스 - 가장 큰 수 (Lv2) in JS

by 코곰 2021. 1. 23.

주어진 숫자 array가 있을 때, 그 숫자들로 만들 수 있는 가장 큰 수를 문자열로 리턴하여라.

 

ex. [6, 10, 2] ~> '6210'

 

코드 구현 in JS

function solution(numbers) {
    
    const complete = [];
    const lenNum = numbers.length;
    
    for (let i=0;i<lenNum;i++){
        let num = String(numbers[i]);
        
        let originalNum = num;
        
        // 비교 부분
        if (num.length === 1) num += num + num;
        else if (num.length === 2) num += num;
        else if (num. length === 3) num += num[0];
        complete.push    ([num, originalNum]);
    }
    complete.sort().reverse();
    
    const answer = complete.map((element) => element[1])
                    .reduce((acc, curr) =>  String(acc)+curr);
    
    
    if (answer[0]==='0') return '0'
    return answer
}

호기롭게 오우... 잘풀리는데? 하면서 시작한 문제였지만 역시나 특이 케이스에서는 맥을 못 췄다 ㅠ

결국 숫자 비교 부분을 검색을 통해 해결하게 되는데...

 

비교 부분

- 모든 숫자를 4자리 수로 만들어준다. 입력 조건이 4자리 수 max라는 데에서 착안

- 이 때, 0을 붙이면서 4자리 수로 만드는 것이 아니라, 자기 자신을 이어 붙이면서 만듬.

  ex. 12 ~> 1212

  => [101, 1]이 주어질 때, '1101'이 '1011'보다 크다.

       하지만 이를 0을 붙여 네 자리수를 만들어 1011, 1000이 되면, 전자가 앞보다 더 크므로 앞에 위치하고, '1011'을 리턴하게 될 것.

       이 때, 자기 자신을 반복해 네 자리수를 만들어 1011, 1111이 되면, 후자가 앞으로 정렬되고 올바르게 '1101'을 리턴할 것이다.

 

 

틈새 코드 구현 in Python

def solution(numbers):
    numbers = [str(x) for x in numbers]
    numbers.sort(key = lambda x: (x * 4)[:4], reverse = True)
    
    if numbers[0] == '0':
    	return 0
    else:
    	return ''.join(numbers)

 

 

메모

- reduce 함수를 어따 쓰나 했는데 여기 쓰면 좋겠다는 생각이 들었다! 왜 사람들이 좋아하는 지 알겠드라...

 

다른 분들의 풀이 ~> 더 나은 방법

하지만 정말 정말 쉽게 sort하는 방법이 있었으니...

바로

.sort((a, b) => (b+a)*1 - (a+b)*1)

을 이용하는 것!!!

 

a, b는 모두 string.

b에 a를 이어붙인 것이, a에 b를 이어붙인 것보다 크다면, b를 앞으로 정렬하는 방식이다.

developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

If compareFunction(a, b) returns less than 0, sort a to an index lower than b (i.e. a comes first).

If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements.
Note: the ECMAScript standard only started guaranteeing this behavior in 2019, thus, older browsers may not respect this.

If compareFunction(a, b) returns greater than 0, sort b to an index lower than a (i.e. b comes first).

compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned, then the sort order is undefined.

 

 

이를 이용하면 코드가 굉장히 간단해진다.

마지막 부분, answer가 '0'으로 시작할 때 (그 말은 sort할 때 0이 가장 큰 수로 sort 되었다는 의미이므로 입력 모든 원소가 0일 때 - ex. [0,0,0] ~> '000', [0,0,0,0,0,0] ~> '000000') 처리하는 부분도

ternary operator로 해주면 간단하다.

 

function solution(numbers) {
    const answer = numbers.map((element) => String(element))
                        .sort((a, b) => (b+a)*1 - (a+b)*1)
                        .reduce((acc, curr) =>  String(acc)+curr);
  
    return answer[0] === '0'? '0': answer;

}

와우 ^_^

댓글