Last active
February 7, 2018 17:10
-
-
Save watilde/f10e677dccb36dd8bcca1d12ca1faee6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const input = '1 4 5 6 7 8' | |
const arr = input.split(' ').map(Number) | |
console.log(`\ninput:\n ${input}\n\noutput:`) | |
for (let i = 1; arr.length > i; i++) { | |
compare(arr.slice(0, i), arr.slice(i)) | |
} | |
function compare(left, right) { | |
const lc = allCases(left) | |
const rc = allCases(right) | |
const rr = Object.keys(rc) | |
Object.keys(lc).forEach((lr, i) => { | |
const copied = rr.slice() | |
const ris = [] | |
while (copied.indexOf(lr) !== -1) { | |
const p = copied.indexOf(lr) | |
ris.push(p) | |
copied.splice(p, 1) | |
} | |
ris.forEach((ri) => { | |
lc[lr].forEach((la) => { | |
rc[rr[ri]].forEach((ra) => { | |
console.log(` ${la} = ${ra}`) | |
}) | |
}) | |
}) | |
}) | |
} | |
function allCases(list) { | |
if (list.length === 1) { | |
const out = {} | |
out[list] = list | |
return out | |
} | |
const cases = {} | |
const patterns = [] | |
const operations = ['+', '-', '*'] | |
const len = list.length - 1 | |
for (let i = 0; operations.length ** len > i; i++) { | |
patterns.push(i.toString(3).padStart(len, '0')) | |
} | |
patterns.forEach((a) => { | |
let p = 1 | |
const item = list.slice() | |
a.split('').map((b, i) => { | |
item.splice(i + p, 0, operations[b]) | |
p += 1 | |
}) | |
const ex = item.join('') | |
const res = rpn(ex) | |
if (!cases[res]) cases[res] = [] | |
cases[res].push(ex) | |
}) | |
return cases | |
} | |
function rpn (input) { | |
const p = [] | |
const s = [] | |
const prio = (i) => { | |
if (i === '+' || i === '-') return 2 | |
if (i === '*') return 1 | |
return 0 | |
} | |
input.split('').forEach((n, i) => { | |
if (i === 0) return s.push(n) | |
const c = prio(n) | |
let l = prio(s.slice(-1)[0]) | |
if (l > c) return s.push(n) | |
while (c >= l && s.length !== 0) { | |
p.push(s.pop()) | |
l = prio(s.slice(-1)[0]) | |
} | |
s.push(n) | |
}) | |
const ex = p.concat(s.reverse()) | |
const t = [] | |
ex.forEach((item) => { | |
if (Number.isInteger(Number(item))) return t.push(Number(item)) | |
const f = t.pop() | |
const s = t.pop() | |
if (item === '+') return t.push(s + f) | |
if (item === '-') return t.push(s - f) | |
if (item === '*') return t.push(s * f) | |
}) | |
return t.pop() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
計算量減らしたい