알고리즘 문제 풀기
프로그래머스: 수식 최대화 - javascript(정규식, 숫자 계산)
Fo_rdang
2024. 4. 18. 12:05
반응형
문제 출처
https://school.programmers.co.kr/learn/courses/30/lessons/67257
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문제 풀이 힌트
정답 풀이 코드
function solution(expression) {
//두 숫자와 연산자가 들어왔을 때 계산하는 함수
function calculator(a,b,oper) {
if(oper === '+') return a+b
if(oper === '-') return a-b
else return a*b
}
//주어진 연산자의 우선순위 조합
const combinations = [
["+","-","*"],
["+","*","-"],
["-","+","*"],
["-","*","+"],
["*","-","+"],
["*","+","-"],
]
//가장 큰 값이 answer이 된다.
let answer = Number.MIN_SAFE_INTEGER;
//연산자 우선순위 조합을 순회한다.
combinations.forEach((combination) => {
const operands = expression.match(/[0-9]+/g).map(Number);
const operators = expression.match(/[\*\-\+]/g);
//조합 하나의 경우일 때, 각 연산자 순회
combination.forEach((c)=>{
let idx = operators.indexOf(c); //연산자들 중 해당 연산자가 있는지 확인
while(idx !== -1){ //해당 연산자가 있다면,
operands[idx] = calculator(operands[idx] , operands[idx+1], c); //두 수와 해당 연산자를 계산한 값을 idx에 넣어준다.
operands.splice(idx+1,1); //idx+1 숫자를 없앤다.
operators.splice(idx, 1); //해당 연산자도 숫자 계산에 사용했으니 없앤다.
idx = operators.indexOf(c); //남은 연산자가 있는지 확인한다. 있다면 다음 연산에 활용, 없다면 반복문 종료
}
})
if (answer < Math.abs(operands[0])) answer = Math.abs(operands[0]) 그동안 최대값보다 더 큰 수면 현재 값을 최대값으로 변경
});
return answer;
}
Only 풀이 코드
function solution(expression) {
function calculator(a,b,oper) {
if(oper === '+') return a+b
if(oper === '-') return a-b
else return a*b
}
const combinations = [
["+","-","*"],
["+","*","-"],
["-","+","*"],
["-","*","+"],
["*","-","+"],
["*","+","-"],
]
let answer = Number.MIN_SAFE_INTEGER;
combinations.forEach((combination) => {
const operands = expression.match(/[0-9]+/g).map(Number);
const operators = expression.match(/[\*\-\+]/g);
combination.forEach((c)=>{
let idx = operators.indexOf(c);
while(idx !== -1){
operands[idx] = calculator(operands[idx] , operands[idx+1], c);
operands.splice(idx+1,1);
operators.splice(idx, 1);
idx = operators.indexOf(c);
}
})
if (answer < Math.abs(operands[0])) answer = Math.abs(operands[0])
});
return answer;
}
알고가는 ppoint
01. indexOf
02. 정규식 표현
반응형