javascript - JS - 为什么 Codewars 挑战的一项测试返回未定义,而其他 104 项测试却通过了?

标签 javascript algorithm optimization

我正在解决 Highest Scoring Word Codewars 的挑战,其中指出 -

Given a string of words (x), you need to find the highest scoring word.

Each letter of a word scores points according to it's position in the alphabet. a=1, z=26 and everything inbetween.

You need to return the highest scoring word as a string.

If two words score the same, return the word that appears earliest in the original string.

All letters will be lower case and all inputs will be valid.

我解决这个问题的方法如下 -

  1. 构造一个对象,将字母表映射到相应的整数值,例如 a - 1b - 2 等。
  2. 将输入字符串拆分为空格,对于每个单词 - 找到它的分数 -
    • 创建单词字母数组
    • 映射数组以获得每个字母的分数
    • 通过加法减少该数组并得到该单词的总分
  3. 第 2 步返回的数组将包含原始字符串中每个单词的分数。找到该数组中的最大值并获取其位置,返回原始字符串中该特定位置的单词。

    我的代码片段(演示 here )-

function high(x) {
  let myObj = {};
  for (let i = 1; i <= 26; i++) {
    myObj[String.fromCharCode(i + 96)] = i;
  }
  // console.log(myObj);

  let scores = x.split(' ').map(word => [...word].map(a => myObj[a]).reduce((a, b) => a + b, 0));

  return x.split(' ')[scores.indexOf(Math.max(...scores))];
}

console.log(high('take me to semynak'))

当我在 codewars 中运行此命令时,结果显示 104 个测试通过,1 个测试失败,1 个错误。唯一的信息。关于显示的失败/错误是 -

Expected: 'bintang', instead got: undefined

由于未显示此测试用例的实际输入,因此此信息。其本身并不是很有用。

我尝试考虑一些边缘情况,例如两个具有相同分数的单词,但即使这样 .indexOf() 也应该返回较早值的位置,如您在本示例中看到的-

let nums = [1, 2, 3, 3];
console.log(nums.indexOf(Math.max(...nums)));

这是屏幕截图 -

enter image description here

最佳答案

问题的陈述表明单词仅由小写字母组成,但并不能保证输入字符串仅包含单词和空格。

为了考虑标点符号、数字和其他非单词,您需要将所有小写字母序列提取为单词(而不是仅按空格分割输入字符串)。

function high(x) {
    let words = x.split(/[^a-z]+/);
    let scores = words.map(word => [...word].map(a => a.charCodeAt(0) - 96).reduce((a, b) => a + b, 0));
    return words[scores.indexOf(Math.max(...scores))];
}
    
console.log(high('today is 24 august, 2017'));

关于javascript - JS - 为什么 Codewars 挑战的一项测试返回未定义,而其他 104 项测试却通过了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45854349/

相关文章:

javascript - 在 jQuery 中使用带有符号的 html() 方法

algorithm - 寻找一种将宽度分配给列的算法

c++ - C++ 优化级别是否影响 Swig Python 模块性能

c++ - 优化读写大数据(C++)

javascript - js奇怪的return语句

javascript - jQuery 防止动画分区的跳跃

javascript - 以 mm/dd/yyyy 格式验证日期的正则表达式

java - 检测数组中的所有突然变化

python - 在 0's and 1' 的矩阵中查找路径

MYSQL IN优化