

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding confusing number within an array in JavaScript
Confusing Numbers:
A number in an array is confusing if it becomes another number which is also present in the array after we rotate the number by 180 degrees vertically and horizontally. For instance, if we rotate 6 by 180 degrees vertically and horizontally it becomes 9 and vice-versa.
We have to keep in mind that only rotations of 0, 1, 6, 8, 9 yield a valid number.
We are required to write a JavaScript function that takes in a natural number, num, as the first and the only argument. The function should first construct an array of all natural numbers upto num, including num.
For example, for num = 5, the array should be −
[1, 2, 3, 4, 5]
Then the function should count how many confusing numbers are present in the array and finally return that count.
For example −
If the input is −
const num = 10;
Then the output should be −
const output = 5;
because the array will be: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and confusing numbers are −
1, 6, 8, 9, 10
Example
The code for this will be −
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));
Output
And the output in the console will be −
5
- Related Questions & Answers
- Finding the third maximum number within an array in JavaScript
- Finding unlike number in an array - JavaScript
- Number of vowels within an array in JavaScript
- JavaScript Finding the third maximum number in an array
- Confusing Number II in C++
- Finding the nth missing number from an array JavaScript
- Finding the largest 5 digit number within the input number using JavaScript
- Finding the first non-consecutive number in an array in JavaScript
- Finding the largest non-repeating number in an array in JavaScript
- Finding a number and its nth multiple in an array in JavaScript
- Counting possible APs within an array in JavaScript
- Find average of each array within an array JavaScript
- Find average of each array within an array in JavaScript
- Finding unique string in an array in JavaScript
- Finding the rotation of an array in JavaScript