從 JavaScript 中混亂的數值名稱中準備數字


問題

假設具有以下數字名稱字串 -

const str = 'TOWNE';

如果重新排列此字串,則可以在其中找到兩個數字名稱 2 (TWO) 和 1 (ONE)。

因此,我們期望輸出 21

我們需要編寫一個 JavaScript 函式,在該函式中輸入一個這樣的字串並返回字串中存在的數字。

示例

以下為程式碼 -

 即時演示

const str = 'TOWNE';
const findNumber = (str = '') => {
   function stringPermutations(str) {
      const res = [];
      if (str.length == 1) return [str];
      if (str.length == 2) return [str, str[1]+str[0]];
      str.split('').forEach((chr, ind, arr) => {
         let sub = [].concat(arr);
         sub.splice(ind, 1);
         stringPermutations(sub.join('')).forEach(function (perm) {
            res.push(chr+perm);
         });
      });
      return res;
   }
   const legend = {
      'ONE': 1, 'TWO': 2, 'THREE': 3, 'FOUR': 4,
      'FIVE': 5, 'SIX': 6, 'SEVEN': 7, 'EIGHT': 8,
      'NINE': 9, 'ZERO': 0
   };
   const keys = Object.keys(legend);
   const res = {};
   const resArr = [];
   let result = '';
   keys.forEach(key => {
      const match = stringPermutations(key).find(el => el.split('').every(char => str.includes(char)));
      if(match){
         const index = str.indexOf(match[0]);
         if(!res.hasOwnProperty(key)){
            res[key] = [index];
         }else if(!res[key].includes(index)){
            res[key].push(index);
         };
      };
   });
   Object.keys(res).forEach(word => {
      resArr.push([word, ...res[word]]);
   });
   resArr.sort((a, b) => a[1] - b[1]);
   resArr.forEach(sub => {
      result = result + String(legend[sub[0]]).repeat(sub.length - 1);
   });
   return +result;
};
console.log(findNumber(str));

輸出

以下為控制檯輸出 -

21

更新於: 2021 年 4 月 17 日

123 次瀏覽

開啟你的 職業生涯

完成課程以獲得認證

立即開始
廣告
© . All rights reserved.