본문 바로가기
코딩테스트(알고리즘)/프로그래머스

[프로그래머스] 수식 최대화 (Javascript)

by Cafe Mocha 2022. 6. 20.

코딩테스트 연습 - 수식 최대화 | 프로그래머스 (programmers.co.kr)

 

코딩테스트 연습 - 수식 최대화

IT 벤처 회사를 운영하고 있는 라이언은 매년 사내 해커톤 대회를 개최하여 우승자에게 상금을 지급하고 있습니다. 이번 대회에서는 우승자에게 지급되는 상금을 이전 대회와는 다르게 다음과

programmers.co.kr


문제 접근 : 완전탐색

 

구현이 생각보다 어려웠던 문제이다.

차근차근 생각하면 접근할 수 있지만, 경우의 수가 더 늘어나면 풀기어려울 것같다.

 


Javascript

function solution(expression) {
    var answer = 0;
    const permutation = [
        ['+', '-', '*'],
        ['+', '*', '-'],
        ['-', '+', '*'],
        ['-', '*', '+'],
        ['*', '-', '+'],
        ['*', '+', '-']
    ];
    
    expression = expression.split("");
    let tmp ="";
    let arr = [];
    let operator =[];
    //input
    expression.forEach(v=>{
        if(v==='-'||v==='+'||v==='*'){
            operator.push(v);
            arr.push(tmp);
            tmp ="";
        } else{
            tmp+=v;
        }
    })
    arr.push(tmp);
    arr = arr.map(v=>+v);
    
    console.log(arr,operator)
    
    for(let i=0;i<6;i++){
        let tmp = check(arr,operator,permutation[i]);
        console.log(tmp);
        
        answer = tmp>answer? tmp: answer;
    }

    
    return answer;
}

function check(arr,operator,permu){
    let copyarr = [...arr];
    let copyoper = [...operator];
    
    
    for(let i=0;i<permu.length;i++){
        for(let j=0;j<copyoper.length;j++){
            if(permu[i]===copyoper[j]){
                copyarr[j]= calculator(copyarr[j],copyarr[j+1],copyoper[j]);
                copyarr.splice(j+1,1);
                copyoper.splice(j,1);
                j--;
            }
        }
    }
       
    return Math.abs(copyarr[0]);
}

function calculator(a,b,oper){
    if(oper ==="*") return a*b;
    if(oper ==="+") return a+b;
    if(oper ==="-") return a-b;
}