I've searched, and I found nothing about what I am going to ask. I have a question as a beginner and a student who learns JavaScript. I know how to check if a number is a prime or not. This is my problem:
numbers([
[5, 7, 10],
[8, 2, 3],
[44, 50, 22]
])
expected output:
[
['#', '#', 10],
[8, '#', '#'],
[44, 50, 22]
]
What I need is: if there is a prime number in a multidimensional array, i need to change it to #, and if not, nothing change. This task requires no built in function such as .indexOf, .include, .findIndex, .reduce, .map, .filter, and no new parameters added, or regex. And this is what I got so far:
function multidimensionalPrimesChecker(numbers)
{
for (var i = 0 ; i < numbers.length ; i++)
{
for (var j = 0 ; j < numbers[i].length ; j++)
{
if (numbers[i][j] % i === 0)
{
return false;
}
}
}
}
And I have no idea anymore how to solve this. Help me, please. And thanks for your kindness
First of all, you will need a function to check if a number is prime or not, since your current check numbers[i][j] % i === 0 only checks if numbers[i][j] is divisible by i. The next method will do it:
function isPrime(num)
{
for(let i = 2, s = Math.sqrt(num); i <= s; i++)
if(num % i === 0) return false;
return num !== 1 && num !== 0;
}
Now, using your code, you detect this condition and replace by # when the condition becomes true.
const input = [
[5, 7, 10],
[8, 2, 3],
[44, 50, 22]
];
function isPrime(num)
{
for(let i = 2, s = Math.sqrt(num); i <= s; i++)
if(num % i === 0) return false;
return num !== 1 && num !== 0;
}
function multidimensionalPrimesChecker(numbers)
{
for (var i = 0; i < numbers.length; i++)
{
for (var j = 0; j < numbers[i].length; j++)
{
if (isPrime(numbers[i][j]))
numbers[i][j] = "#";
}
}
return numbers;
}
let res = multidimensionalPrimesChecker(input);
console.log(JSON.stringify(res));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With