首頁  >  文章  >  web前端  >  在 JavaScript 中尋找數組中令人困惑的數字

在 JavaScript 中尋找數組中令人困惑的數字

王林
王林轉載
2023-09-11 22:45:05679瀏覽

在 JavaScript 中查找数组中令人困惑的数字

令人困惑的數字:

如果數組中的一個數字在垂直和水平旋轉180 度後變成了另一個也存在於數組中的數字,那麼該數字就會令人困惑。例如,如果我們將 6 垂直和水平旋轉 180 度,它就會變成 9,反之亦然。

我們必須記住,只有 0、1、6、8、9 的旋轉才會產生有效的結果。

我們需要寫一個 JavaScript 函數,該函數接受自然數 num 作為第一個也是唯一的參數。此函數應先建構一個包含 num 之前所有自然數的數組,包括 num。

例如,對於 num = 5,數組應為 -

[1, 2, 3, 4, 5]

然後該函數應該計算數組中存在多少個令人困惑的數字,並最終返回該計數。

例如-

如果輸入是-

const num = 10;

那麼輸出應該是-

const output = 5;

因為陣列將是:[1, 2, 3, 4 , 5, 6, 7, 8, 9, 10] 而令人困惑的數字是-

1, 6, 8, 9, 10

範例

其程式碼為-

## 即時示範

const num = 10;
const countConfusing = (num = 1) => {
   let count = 0;
   const valid = '01689';
   const rotateMap = {'0': '0', '1': '1', '6': '9', '8': '8', '9': '6'};
   const prepareRotation = num => {
      let res = '';
      const numArr = String(num).split('');
      if(numArr.some(el => !valid.includes(el))){
         return false;
      };
      numArr.map(el => {
         res = rotateMap[el] + res;
      });
      return +res;
   };
   for(let i = 1; i <= num; i++){
      const rotated = prepareRotation(i);
      if(rotated && rotated > 0 && rotated <= num){
         count++;
      };
   };
   return count;
};
console.log(countConfusing(num));

輸出

控制台中的輸出將是-

5

以上是在 JavaScript 中尋找數組中令人困惑的數字的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除