새소식

Programmers

[Programmers] 수식 최대화 문제 - (javascript)

  • -
728x90
문제 이름 :  수식 최대화

 

<<< 문제 내용 >>>

 

// 딕셔너리에 arrow function 사용
const operator = {
    '+': (a, b) => a + b,
    '-': (a, b) => a - b,
    '*': (a, b) => a * b,
};

function solution(e) {
    let answer = 0;
    
    const operate = [['*', '+', '-'],
                     ['*', '-', '+'],
                     ['+', '*', '-'],
                     ['+', '-', '*'],
                     ['-', '*', '+'],
                     ['-', '+', '*']];
    
    let str = '';
    let numArr = e.split(/[\D]/g).map(Number);
    let operArr = e.match(/[\*\+\-]/g);
    
    for(const op of operate){
        let copyNum = [...numArr];
        let copyOper = [...operArr];
        let cnt = 0;
        
        while(copyNum.length>1){
            for(let i=0; i<copyOper.length; i++){
                if(copyOper[i] === op[cnt]){
                    copyNum[i] = operator[op[cnt]](copyNum[i], copyNum[i + 1]);
                    copyNum.splice(i + 1, 1);
                    copyOper.splice(i, 1);
                    i--
                }
            }
            
            cnt++;
        }
        
        if (Math.abs(copyNum[0]) > answer) answer = Math.abs(copyNum[0]);
    }
    
    return answer;
}

* 시간초과를 고려할 필요없는 단순 구현 문제인데.. for문 순서를 잘못고려해서 정답을 참고하게됐다.

 

다른 사람이 푼 코드를 통해 dictionary(해시 테이블과 비슷한)에 Arrow function을 이용할 수 있다는 것을 알았다.

상당히 깔끔하고 보기좋은 코드였다.

 

도움이 되셨다면 공감 부탁드립니다.

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.