반응형
https://programmers.co.kr/learn/courses/30/lessons/67257
결과 코드
function solution(expression) {
let answer = [];
let number_arr = expression.split(/[+\-\*]/);
let operator_arr = expression.replace(/[^+\-\*]/g, "").split("");
answer.push(solve(number_arr.slice(), operator_arr.slice(), ["+", "-", "*"]));
answer.push(solve(number_arr.slice(), operator_arr.slice(), ["+", "*", "-"]));
answer.push(solve(number_arr.slice(), operator_arr.slice(), ["-", "+", "*"]));
answer.push(solve(number_arr.slice(), operator_arr.slice(), ["-", "*", "+"]));
answer.push(solve(number_arr.slice(), operator_arr.slice(), ["*", "+", "-"]));
answer.push(solve(number_arr.slice(), operator_arr.slice(), ["*", "-", "+"]));
return Math.max.apply(null, answer);
}
const solve = (number_param, operator_param, selected_operator) => {
selected_operator.forEach((selected_oper) => {
let number_arr = [];
let operator_arr = [];
operator_param.forEach((v, i) => {
let number = number_param[i];
let operator = operator_param[i];
if(operator == selected_oper) {
number_param[i+1] = eval(number + operator + number_param[i+1]);
} else {
number_arr.push(number);
operator_arr.push(operator);
}
})
number_arr.push(number_param[number_param.length-1]);
number_param = number_arr;
operator_param = operator_arr;
})
return Math.abs(number_param[0]);
}
// 리팩토링 이전
function solution(expression) {
let answer = [];
let number_arr = expression.split(/[+\-\*]/);
let operator_arr = expression.replace(/[^+\-\*]/g, "").split("");
answer.push(Math.abs(func(func(func([number_arr,operator_arr], "+"), "-"), "*")[0]));
answer.push(Math.abs(func(func(func([number_arr,operator_arr], "+"), "*"), "-")[0]));
answer.push(Math.abs(func(func(func([number_arr,operator_arr], "-"), "+"), "*")[0]));
answer.push(Math.abs(func(func(func([number_arr,operator_arr], "-"), "*"), "+")[0]));
answer.push(Math.abs(func(func(func([number_arr,operator_arr], "*"), "+"), "-")[0]));
answer.push(Math.abs(func(func(func([number_arr,operator_arr], "*"), "-"), "+")[0]));
return Math.max.apply(null, answer);
}
const func = (params, selected_operator) => {
let number_param = params[0].slice();
let operator_param = params[1].slice();
let number_arr = [];
let operator_arr = [];
operator_param.forEach((v, i) => {
let number = number_param[i];
let operator = operator_param[i];
if(operator == selected_operator) {
number_param[i+1] = eval(number + operator + number_param[i+1]);
} else {
number_arr.push(number);
operator_arr.push(operator);
}
})
number_arr.push(number_param[number_param.length-1]);
return [number_arr, operator_arr];
}
반응형
'코딩테스트 문제풀이 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] 다단계 칫솔 판매 (0) | 2022.03.08 |
---|---|
[프로그래머스] Level1 문제풀기 1 (0) | 2022.03.08 |
[프로그래머스] 신규 아이디 추천 (0) | 2021.09.29 |
[프로그래머스] 124 나라의 숫자 (0) | 2021.09.29 |
[프로그래머스] 숫자 문자열과 영단어 (0) | 2021.09.29 |