-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQ09.js
68 lines (57 loc) · 1.89 KB
/
Q09.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// [2020 카카오 인턴십] 수식 최대화
function solution(expression) {
let answers = new Set();
// 숫자, 연산자 배열
let nArray = expression.split(/[^\d]/g);
for (let i = 0; i < nArray.length; i++) {
nArray[i] = parseInt(nArray[i]);
}
let opArray = expression.split(/\d*/g);
opArray = opArray.filter((e) => e !== "");
// 연산자 우선 순위 구하기 (순열로)
function getPermutaion(arr, r) {
if (r === 1) return arr.map((value) => [value]);
let result = [];
arr.forEach((fixed, index, origin) => {
const rest = [...origin.slice(0, index), ...origin.slice(index + 1)];
const permutations = getPermutaion(rest, r - 1);
const attached = permutations.map((perm) => [fixed, ...perm]);
result.push(...attached);
});
return result;
}
// 연산자 중복 제외하고 우선순위 구함
const opSet = new Set([...opArray]);
const opPerm = getPermutaion([...opSet], opSet.size);
// 우선순위에 따라 반복
for (const ops of opPerm) {
let copyNumber = [...nArray];
let copyOp = [...opArray];
for (let i = 0; i < ops.length; i++) {
while (copyOp.includes(ops[i])) {
const index = copyOp.indexOf(ops[i]);
let result = 0;
switch (ops[i]) {
case "*":
result = copyNumber[index] * copyNumber[index + 1];
break;
case "+":
result = copyNumber[index] + copyNumber[index + 1];
break;
case "-":
result = copyNumber[index] - copyNumber[index + 1];
break;
default:
result = 0;
}
copyOp.splice(index, 1);
copyNumber[index] = result;
copyNumber.splice(index + 1, 1);
}
}
answers.add(Math.abs(copyNumber[0]));
}
return Math.max(...answers);
}
console.log(solution("100-200*300-500+20"));
console.log(solution("50*6-3*2"));