【问题标题】:Find the highest scoring word from a string according to its position in the alphabet using JavaScript使用 JavaScript 根据其在字母表中的位置从字符串中查找得分最高的单词
【发布时间】:2020-07-12 08:47:29
【问题描述】:

我正在尝试解决 CodeWars 挑战,但我遇到了这个问题:

“给定一串单词,你需要找到得分最高的单词。 单词的每个字母根据其在字母表中的位置得分:

 a = 1, b = 2, c = 3 etc.

您需要将得分最高的单词作为字符串返回。 如果两个单词得分相同,则返回原始字符串中出现最早的单词。 所有字母都是小写,所有输入都是有效的。”

我的代码通过了 104 个案例,但在 1 个案例中出错。 错误答案测试用例是

'what time are we climbing up the volcano' 

根据 codewars - 预期:'volcano',而不是:'climbing'

有什么想法吗?

问题链接 - https://www.codewars.com/kata/57eb8fcdf670e99d9b000272/train/javascript

 function high(x){
  let result = '', value =0, counterValue = 0; 

  let splittedArray = x.split(' ');

  splittedArray.map(splitItem => {
    counterValue = 0;

    let splitItemArray = splitItem.split('');

    splitItemArray.map(splitChar => { 
      counterValue += splitChar.charCodeAt();
    })

    if(counterValue>value){
      result = splitItem;
      value = counterValue;
    }
  });
  return result;
}

【问题讨论】:

  • 你的问题是你使用 charCodeAt 它的 ascii 值不是你想要的1... 格式
  • 使用存储所有字母的数组并使用indexOf,错误是由于charCodeAt
  • 嗯,你去吧,4个答案和4种不同的方式将字母转换成数字!

标签: javascript string split array.prototype.map


【解决方案1】:
function high(x) {
  const words = x.split(' ');
  const alphabetMap = {};
  for (let i='a'.charCodeAt(), j = 1; i <= 'z'.charCodeAt(); i++, j++) {
    alphabetMap[i] = j;
  }
  let highestScoringWord = { word: '', score: 0 };
  words.forEach(w => {
    const chars = w.split('');
    const sumOfChars = chars.reduce((count, char) => count + alphabetMap[char.charCodeAt()], 0);
    if (sumOfChars > highestScoringWord.score) {
      highestScoringWord = { word: w, score: sumOfChars };
    }
  });

  return highestScoringWord.word;
}

console.log(high('what time are we climbing up the volcano')) // volcano ;)

【讨论】:

  • 我仍然不确定为什么您使用charCodeAt 的方法不起作用,但它可以这样工作! :)
  • 成功了,我了解您的解决方案。但是是的,我仍然无法理解我的解决方案有什么问题.....谢谢您的帮助
  • 令您惊讶的是您的解决方案有效,因为它似乎无法处理非字母字符(如逗号和句点),但它看起来像 count + alphabetMap[char.charCodeAt()] 因为像逗号之类的东西不在AlphabetMap它返回undefined 和count + undefined 只是count 所以它工作。不确定这是故意的还是只是幸运。但我看不出这个解决方案在哪里处理If two words score the same, return the word that appears earliest in the original string.的次要要求
  • 我最后的评论是错误的,这个解决方案实际上绝对不应该工作; count + undefine 是 NaN 而不是 undefined 所以它会在更严格的测试中出错。易于修复,只需将const words = x.split(' '); 更改为const words = x.split(/[^a-zA-Z]+/gm);
  • 嗨@AsherGarland,我不关心特殊字符,因为问题说得很清楚:“所有字母都是小写的,所有输入都是有效的。”
【解决方案2】:

您可以使用 reduce 和 object 来跟踪最高计数和相应的单词

function high(x){
  let mapper = [...`abcdefghijklmnopqurstuvwxyz`].reduce((op,inp,index)=>{
    op[inp] = index+1
    return op
  },{})
  return x.split(' ').reduce((op,inp)=>{
    let currentCount = 0;
    [...inp].forEach(v=>{
      currentCount += mapper[v]
    })
    if(currentCount > op.maxCount){
      op.maxCount = currentCount
      op.word = inp
    }
    return op
  }, {maxCount:0, word:''}).word
}

console.log(high('what time are we climbing up the volcano'), 'volcano'))

【讨论】:

  • 虽然我不理解 [...abcdefghijklmnopqurstuvwxyz].reduce 部分仍在测试 -> tjqajbudvkxhtrpon nazakuthuczkvbwkl lyhvlqigrhhexfrlr cbjsnmhwaadsevajr 预期:'tjqajbudvkxhtrpon',而不是:'nazakuthuczkvb回答这个。请帮助我理解 [...abcdefghijklmnopqurstuvwxyz].reduce part.T 谢谢你
  • @MustafizurRahmanChoudhury 我仅使用此解决方案在代码战上清除了所有测试,您所使用的部分用于创建像 {a : 1, b : 2 ..., z: 26 } 这样的映射对象
  • @MustafizurRahmanChoudhury 我刚才也试过了,它通过了代码战的所有测试
  • 好的,知道了。你知道为什么我的代码在那里出错了吗???
  • @MustafizurRahmanChoudhury 您正在使用 charCodeAt,它给出的 asci 值不是基于 1,所以这就是问题所在
【解决方案3】:

解决方案是使用一个字母数组并索引其中的字符位置,

let al = `abcdefghijklmnopqrstuvwxyz`.split('')


   function high(x){
     let words = x.split(" ");
     let out = words.map(word => {
     let score = 0;
     let letters = word.split("");
     letters.map(c => {
      score += al.indexOf(c);
     })
     return [word, score];
    });

    out = out.sort((a,b) => { 
      if(a[1] > b[1]) return -1;
      else if(a[1] < b[1]) return 1; 
      else return 0;  });

return out[0][0];
}

【讨论】:

  • 知道了。感谢您的反馈
  • 使用字母数组非常聪明,但是如果您改为使用哈希表进行 O(1) 查找(一个标准的 Javascript 对象可以充当您的 HashTable)。此外,您应该使用.reduce(),而不是使用.map() 进行聚合。在您的排序中,您不需要 if/else,只需执行return a[1] - b[1]。此解决方案似乎缺少If two words score the same, return the word that appears earliest in the original string. 的要求
【解决方案4】:

我对您的counterValue += splitChar.charCodeAt(); 行感到困惑。我不明白 splitChar.charCodeAt() 如何翻译成 1-26 也就是字母表中的字母位置。 "单词的每个字母根据其在字母表中的位置得分"

我能够通过做两件事使您的代码正常工作:

  1. 添加一个映射来存储字母表中每个字母的值。我确信这可以通过多种方式完成,但这是我的方法:
let letterValues = { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10, k: 11, l: 12, m: 13, n: 14, o: 15, p: 16, q: 17, r: 18, s: 19, t: 20, u: 21, v: 22, w: 23, x: 24, y: 25, z: 26 };
  1. 然后在counterValue += splitChar.charCodeAt(); 中将其用作counterValue += letterValues[letter];

【讨论】:

  • 感谢您的反馈。那是我的错误。
【解决方案5】:

想法:

  • 将得分值存储在表格中以便于查找
  • 按非字母字符将句子分成单词
  • 首先计算各个字符的分数,然后将它们相加(使用 reduce)来获得每个单词的分数。
  • 如果分数相同,不要忘记按原始位置排序,通过跟踪原始位置来进行。

演示:https://jsfiddle.net/9xkfqh1m/

const ScoreTable = {
  "a": 1,
  "b": 2,
  "c": 3,
  "d": 4,
  "e": 5,
  "f": 6,
  "g": 7,
  "h": 8,
  "i": 9,
  "j": 10,
  "k": 11,
  "l": 12,
  "m": 13,
  "n": 14,
  "o": 15,
  "p": 16,
  "q": 17,
  "r": 18,
  "s": 19,
  "t": 20,
  "u": 21,
  "v": 22,
  "w": 23,
  "x": 24,
  "y": 25,
  "z": 26
};

// non-ascii letters = 0
function CharScore(char) {
  const lowerCaseChar = char.toLowerCase();
  return lowerCaseChar in ScoreTable ? ScoreTable[lowerCaseChar] : 0;
}

function WordScore(word) {
  return word.split("").reduce((score, char) => {
    return score + CharScore(char);
  }, 0);
}

function SplitOnNonAlphabeticCharacters(str) {
  return str.split(/[^a-zA-Z]+/gm);
}

function high(str){
  const scoreObjects = SplitOnNonAlphabeticCharacters(str)        // split into words
  .map((word, index) => {                                         // map our words into an object with its score and original position
    return {
      text: word,
      score: WordScore(word),
      originalPosition: index
    };
  }).sort((word1, word2) => {                                        // sort
    return word2.score - word1.score                                 // highest score first
                ||  word1.originalPosition - word2.originalPosition; // if score same, earliest original position in string
  });

  return scoreObjects.length > 0 ? scoreObjects[0].text : null;   // return word by the highest score (or earliest original position), or null
}

【讨论】:

    【解决方案6】:

    charCodeAt() 方法返回一个介于 0 和 65535 之间的整数,表示给定索引处的 UTF-16 代码单元。

    基本上,您需要将其转换为大写字母并将 charCodeAt 的值减去 64,这将为您提供字符串在字母表中的位置。

    看看这个:

    function high(x) {
        let splittedArray = x.split(' ');
        let splitChar = splittedArray.map(el => el.split(''));
        let charValue = splitChar.map(el => {
            let counter = 0;
            el.map(element => counter += element.toUpperCase().charCodeAt() - 64);
            return counter;
        });
        let largest = 0;
        let largestIndex;
        for (let i = 0; i < charValue.length; i++) {
            if (charValue[i] > largest) {
                largest = charValue[i];
                largestIndex = i;
            }
        }
        return splittedArray[largestIndex];
    }

    【讨论】:

    • 是的,我明白了。感谢您的反馈
    • 由于保证字符是小写的,不大写可能更容易,只需减去 96。
    【解决方案7】:

    我犯了一个错误,没有计算字母表中的字母位置。如果我从 ASCII 值中减去 96,那么它将计算 a as 1, b as 2......

    所以下面给出解决方案

     function high(x){
      let result = '', value =0, counterValue = 0; 
    
      let splittedArray = x.split(' ');
    
      splittedArray.map(splitItem => {
        counterValue = 0;
    
        let splitItemArray = splitItem.split('');
    
        splitItemArray.map(splitChar => { 
          counterValue += splitChar.charCodeAt()-96; // if I subtract 96 then it will calculate a as 1, b as 2......
        })
    
        if(counterValue>value){
          result = splitItem;
          value = counterValue;
        }
      });
      return result;
    }
    

    【讨论】:

      【解决方案8】:
      function high(x){
      const str = x.split(' ');
      const result1 = [];
      const result = str.reduce((_, dig) => {
        let c = 0;
        for (let j = 0; j < dig.length; j++) {
          c = c + (dig.charCodeAt(j) - 96);
        }
        result1.push(c);
      }, 0);
      return str[result1.indexOf(result1.slice().sort((a, b) => b - a)[0])];
      }
      

      【讨论】:

      • 这段代码有什么作用?阅读How to Answer 并通过tour 了解这个网站的工作原理。
      【解决方案9】:

      自从我解决了它后,我想我会发布,即使帖子已经很旧了。无论如何,这是通过纯 javascript 解决的。

      //This main function loops thru each sum from the helper function and returns the position of the highest scoring word
      
      function highestScoringWord(sentence) {
      let arr = []
      let sentenceSplit = sentence.split(' ')
      for(i=0; i<sentenceSplit.length; i++) {
      arr.push(scoringWord(sentenceSplit[i]))
      }
      let max = arr[0]
      for(x=0; x<arr.length; x++) {
          if(arr[x] > max) {
              max = arr[x]
          }   
      }
      
      for(p=0; p<arr.length; p++) {
          if(max === arr[p]) {
              return sentenceSplit[p]
          }
      }
      
      }
      
      //Helper function that takes a word, splits it, and sums up the numbers that each letter is worth.
      
      function scoringWord(word) {
       let wordSplit = word.split('')
       let alphabet = 'abcdefghijklmnopqrstuvwxyz'
       let sum = 0
       for(j=0; j<word.length; j++) {
           sum+=alphabet.indexOf(word[j])
       }
       return sum
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-07-06
        • 2019-08-26
        • 2019-11-06
        • 1970-01-01
        • 1970-01-01
        • 2011-09-27
        相关资源
        最近更新 更多