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]
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;
then the output should be -
const output = 5;
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
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));
The output in the console will be -
5
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!