说明: 我今天一直在玩 Codinggames,并在 Clash of Code 中遇到了这个问题。
问题: 给定一个单词,根据它在 ABC 中的位置输出该单词的索引之和。
示例: 字=“嗨” 结果 = 15
说明: H = 7 且 I = 8,其和为 15。这是因为如果我们确定 A = 0,H 和 I 位于字母表中的第 7 和第 8 个索引;
我的解决方案:我已经让它与嵌套循环一起工作,但效率不是很高。 其他解决方案1:
print(readline().split("").reduce((a,b)=>b.match(/[A-Z]/)?a+b.charCodeAt(0)-65:a,0))
其他解决方案2:
s=0
readline().split``.map(e=>/[A-Z]/.test(e)?s+=e.charCodeAt(0)-'A'.charCodeAt(0):0)
print(s)
有人可以向我解释这些代码吗?我尝试过人工智能,但我没有掌握它的窍门。我也欢迎网站等的建议,帮助我更好地理解这些代码。
谢谢!
使用正常的分割、归约和匹配给出 29
const res = "HeLLo"
.split("")
.reduce((a,b)=>
b.match(/[A-Z]/)? // does the current letter match an uppercase?
a+b.charCodeAt(0)-65 // return accumulator plus current letter value minus A's letter value of 65
:a // otherwise return the accumulator
,0) // start with an accumulator of 0
console.log(res);
使用标记模板分割,地图和测试在同一个字符串上给出54 - 我现在不明白为什么第二个L给出29
s=0;
const res = "HeLLo"
.split`` // split on anything
.map(e=>/[A-Z]/.test(e)? // if from A-Z
s+=e.charCodeAt(0)-65 // add each charcode minus the charCode for A
:0 // otherwise 0
)
// .reduce((a,b) => a+b) // missing from your example
console.log(res);