Lv2. 수식 최대화 Javascript
https://programmers.co.kr/learn/courses/30/lessons/67257
const getPermutations = function (arr, selectNumber) {
const results = []
if (selectNumber === 1) return arr.map((value) => [value])
arr.forEach((fixed, index, origin) => {
const rest = [...origin.slice(0, index), ...origin.slice(index + 1)]
const permutations = getPermutations(rest, selectNumber - 1)
const attached = permutations.map((permutation) => [fixed, ...permutation])
results.push(...attached)
})
return results
}
function solution(exp) {
const spread = []
const expLen = exp.length
for (let i = 0, j = 0; i < expLen; i++) {
if (Number.isInteger(Number(exp[i]))) {
spread[j] = (spread[j] || '') + exp[i]
} else {
spread.push(exp[i])
j += 2
}
}
const types = ['-', '+', '*']
const perm = getPermutations(types, 3)
const answer = []
let ans = 0
for (let i = 0; i < perm.length; i++) {
const clone = spread.slice()
for (let j = 0; j < perm[i].length; j++) {
for (let k = 0; k < clone.length; k++) {
if (perm[i][j] === clone[k]) {
switch (perm[i][j]) {
case '-':
ans = Number(clone[k - 1]) - Number(clone[k + 1])
break
case '+':
ans = Number(clone[k - 1]) + Number(clone[k + 1])
break
case '*':
ans = Number(clone[k - 1]) * Number(clone[k + 1])
break
}
clone.splice(k - 1, 3, ans)
k--
}
}
}
answer.push(clone[0])
}
const abs = answer.map((v) => Math.abs(v))
return Math.max(...abs)
}
const getPermutations = function (arr, selectNumber) {
const results = []
if (selectNumber === 1) return arr.map((value) => [value])
arr.forEach((fixed, index, origin) => {
const rest = [...origin.slice(0, index), ...origin.slice(index + 1)]
const permutations = getPermutations(rest, selectNumber - 1)
const attached = permutations.map((permutation) => [fixed, ...permutation])
results.push(...attached)
})
return results
}
function solution(exp) {
const spread = []
const expLen = exp.length
for (let i = 0, j = 0; i < expLen; i++) {
if (Number.isInteger(Number(exp[i]))) {
spread[j] = (spread[j] || '') + exp[i]
} else {
spread.push(exp[i])
j += 2
}
}
const types = ['-', '+', '*']
const perm = getPermutations(types, 3)
const answer = []
let ans = 0
for (let i = 0; i < perm.length; i++) {
const clone = spread.slice()
for (let j = 0; j < perm[i].length; j++) {
for (let k = 0; k < clone.length; k++) {
if (perm[i][j] === clone[k]) {
switch (perm[i][j]) {
case '-':
ans = Number(clone[k - 1]) - Number(clone[k + 1])
break
case '+':
ans = Number(clone[k - 1]) + Number(clone[k + 1])
break
case '*':
ans = Number(clone[k - 1]) * Number(clone[k + 1])
break
}
clone.splice(k - 1, 3, ans)
k--
}
}
}
answer.push(clone[0])
}
const abs = answer.map((v) => Math.abs(v))
return Math.max(...abs)
}
댓글 환영
질문 환영
by.protect-me