# Finding confusing number within an array in JavaScript

JavascriptWeb DevelopmentFront End Technology

## 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 −

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));

## Output

And the output in the console will be −

5