Thursday, 4 July 2019

Loop Through String of Words, Return Word With Highest Score According To Character Value in Object - JavaScript

I'm trying to figure out how to solve this kata on CodeWars.

Function high recieves a string and returns the word with the highest "score" according to which letters in the word are present. The letters receive a score based on their position in the alphabet. So a = 1 point, b = 2 points, c = 3 points, and so on.

I think it makes sense to create an object where all of the letters in the alphabet are assigned a value:

If the letter in the word appears in alphabetScore, that word will receive its "points" and continue on to the next letter in the word, increasing the total points of the word.

I have:

function high(string) {

  let words = string.split(" ");
  let wordScore = 0;

  const alphabetScore = {
    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
  }

  let word = words[i];
  let wordCount = 0;

  //loop through all words in the string

  for (let i = 0; i < words.length; i++) {

    let word = words[i];

    //loop through all characters in each word

    for (let j = 0; j < word.length; j++) {

      let value = alphabetScore[j];

      wordCount += alphabetScore[value];

    }
  }
  return wordCount;
}

console.log(high("man i need a taxi up to ubud"));

And this is returning an error saying

i is not defined

in let word = words[i] - how else would I define a word, then?

If it's possible to solve this Kata with my existing logic (using for-loops), please do so.

EDIT: Changed wordCount = alphabetScore.value++; to wordCount += alphabetScore[value];

EDIT 2: This is now returning NaN

EDIT 3: Latest attempt:

function myScore(input) {
    let key = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
    "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
    "w", "x", "y", "z"
    ];
    let bestWord = "";
    let bestScore = 0;
    let words = input.split(" ");
    for (let i = 0; i < words.length; i++) {
      let score = 0;
      let word = words[i];
      for (let j = 0; j < word.length; j++) {
        let char = word[j];
        score += (key.indexOf(char) + 1);
      }
      if (score > bestScore) {
        bestScore = score;
        bestWord = word;
      }
    }
    return bestWord;
  }

ReferenceError: high is not defined at Test.describe._



from Loop Through String of Words, Return Word With Highest Score According To Character Value in Object - JavaScript

No comments:

Post a Comment