ES6(JavaScript), 250, 171, 154, 149,147字节
纯Javascript版本。
“元编程”(如此处的其他大多数答案一样),通过对输入文本进行大量直接文本替换(即保持程序结构不变),将输入程序文本转换为相应的Javascript程序。
可以进一步打高尔夫球。
更新(v2.1)
- 减去两个字节(在三进制表达式中删除了括号)
- 通过使用变量进行结果提取,消除多余的5个字节,从而摆脱了多余的“ []”
更新(v2)
刚刚意识到ES数组中的待处理逗号完全有效,因此可以删除整个逗号标准化代码。@Titus还提供了关于优化字母查找的出色建议。
更新(v1)
删除重复的“替换”别名。
更新(v1)
打高尔夫球(v2.1)
s=>eval("o="+s.replace(/./g,r=>"2+1-3*3/"["()[]{}<>".indexOf(r)]).replace(/\d\D?|\D/g,r=>r[1]?r[0]-2+",":r*1?'([':`].reduce((r,a)=>r${r}a)),`)+"o
打高尔夫球(v1)
(s,A="(2)+[1]-{3}*<3>/")=>eval(s[R="replace"](/./g,r=>A[A.indexOf(r)+1])[R](/\d\D?|\D/g,r=>r[1]?r[0]-2+",":(r[0]*1?'([':`].reduce((r,a)=>r${r}a)),`))[R](/,(\])|,$/g,"$1"))
打高尔夫球(v0)
([...s],A="(a)b[c]d{e}f<g>h",R="replace")=>eval(s.reduce((r,c)=>r+=A[A.indexOf(c)+1],'')[R](/ab|cd|ef|gh/g,r=>({d:-1,b:'0'}[r[1]]||1) + ',')[R](/[aceg]/g,"([")[R](/[bdfh]/g,r=>`].reduce((r,a)=>r${"+*-/"["bfdh".indexOf(r)]}a)),`)[R](/,(\])|,$/g,"$1"))
解释(v0)
//BEGIN
//s - input text, A - alphabet, R - "String.replace()" alias
E=([...s],A="(a)b[c]d{e}f<g>h",R="replace")=>eval(
//Replace input alphabet by a more friendly one, to avoid too much escaping and quoting
// () - ab, [] -cd, {} - ef, <> - gh
s.reduce((r,c)=>r+=A[A.indexOf(c)+1],'')
//Replace no-arg invocations with a corresponding constant value
// () => 0, [] => -1, {} => 1, <> => 1
[R](/ab|cd|ef|gh/g,r=>({d:-1,b:'0'}[r[1]]||1) + ',')
//Replace opening brackets with "(["
[R](/[aceg]/g,"([")
//Replace closing brackets with "].reduce(...)),"
//An arithmetic operation to apply (+-*/) is chosen based on the bracket type
//and is substituted into the template
[R](/[bdfh]/g,r=>`].reduce((r,a)=>r${"+*-/"["bfdh".indexOf(r)]}a)),`)
//Strip excessive commas
[R](/,(\])|,$/g,"$1")
);
//END: eval() the result
Example:
E("{([]<>()<>{})(<><>)}")
=> eval("([([-1,1,0,1,1].reduce((r,a)=>r+a)),([1,1].reduce((r,a)=>r+a))].reduce((r,a)=>r*a))")
=> 4
测试
E=([...s],A="(a)b[c]d{e}f<g>h",R="replace")=>eval(s.reduce((r,c)=>r+=A[A.indexOf(c)+1],'')[R](/ab|cd|ef|gh/g,r=>({d:-1,b:'0'}[r[1]]||1) + ',')[R](/[aceg]/g,"([")[R](/[bdfh]/g,r=>`].reduce((r,a)=>r${"+*-/"["bfdh".indexOf(r)]}a)),`)[R](/,(\])|,$/g,"$1"))
T=(s,a)=>{
console.log(s,r=E(s),r==a?"OK":"NOT OK");
}
T("()",0)
T("(()())",0)
T("([][])",-2)
T("({}<>)",2)
T("({}[])",0)
T("[]",-1)
T("[[][]]",0)
T("[()<>]",-1)
T("{()}",0)
T("{([]<>)}",0)
测试输出
() 0 OK
(()()) 0 OK
([][]) -2 OK
({}<>) 2 OK
({}[]) 0 OK
[] -1 OK
[[][]] 0 OK
[()<>] -1 OK
{()} 0 OK
{([]<>)} 0 OK