Home > Web Front-end > JS Tutorial > body text

Find confusing numbers in an array in JavaScript

王林
Release: 2023-09-11 22:45:05
forward
697 people have browsed it

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

Confusing Numbers:

If one number in the array becomes another after being rotated 180 degrees vertically and horizontally also exists in the array , then the number will be confusing. For example, if we rotate 6 180 degrees vertically and horizontally, it becomes 9 and vice versa.

We must remember that only rotations of 0, 1, 6, 8, 9 will produce valid results.

We need to write a JavaScript function that accepts the natural number num as the first and only parameter. The function should first construct an array containing all natural numbers up to and including num.

For example, for num = 5, the array should be -

[1, 2, 3, 4, 5]
Copy after login

The function should then count how many confusing numbers are present in the array and finally return that count.

For example -

If the input is -

const num = 10;
Copy after login

then the output should be -

const output = 5;
Copy after login

because the array will be: [1, 2, 3, 4 , 5, 6, 7, 8, 9, 10] and the confusing number is -

1, 6, 8, 9, 10
Copy after login

Example

its code is-

Live Demo

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));
Copy after login

Output

The output in the console will be -

5
Copy after login

The above is the detailed content of Find confusing numbers in an array in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!