rewrite an array of letters to numbers using dictionary

Viewed 59

examples:

"heLLo" => 0.1.2.2.3

"javAscript" => 0.1.2.1.3.4.5.6.7.8

"hippopotomonstrosesQuippedaliophobia" => 0.1.2.2.3.2.3.4.3.5.3.6.7.4.8.3.7.9.7.10.11.1.2.2.9.12.13.14.1.3.2.0.3.15.1.13

my non-working code:


function wordPattern(word) {
  var res = []
  var dic = []
  var count = 0
  var pipa = word.toLowerCase().split("")

  for (i=0;i<pipa.length;i++) {
    if (!dic.includes(pipa[i])) {
      dic.push({key:   count, value: pipa[i]});
      count ++
  }
    for (j=0;j<pipa.length;j++) {
      res.push(dic.key[pipa[i]])
    }
    return res.join("."); 
}

Thanks in advance

2 Answers

To associate characters to numbers, don't use an array, use an object:

function wordPattern(word) {
  const numbersByChar = {};
  let i = 0;
  return [...word]
    .map(char => numbersByChar[char] ?? (numbersByChar[char] = i++))
    .join('.');
}

console.log(wordPattern('hello'));
console.log(wordPattern('hippopotomonstrosesquippedaliophobia'));

Or without the concise syntax that you might find more readable

function wordPattern(word) {
  const numbersByChar = {};
  let i = 0;
  return Array.from(word)
    .map((char) => {
      if (numbersByChar[char] === undefined) {
        numbersByChar[char] = i;
        i++;
      }
      return numbersByChar[char];
    })
    .join('.');
}

console.log(wordPattern('hello'));
console.log(wordPattern('hippopotomonstrosesquippedaliophobia'));

hint 1 is that you can get a letter like: word[index]

so change your code to this:

    function wordPattern(word) {
      var res = []
      var dic = []
      var count = 0
      for (i=0;i<word.length;i++) {
        let dicItem = dic.find(x=>x.value==word[i]);
        if(!dicItem) {
          dic.push({key: count, value: word[i]});
          res.push(count);
          count ++;
         }
         else res.push(dicItem.key);
       }
        return res.join("."); 
}
Related