Tengo dos matrices (X e Y) y necesito crear una matriz Z que contenga todos los elementos de la matriz X excepto aquellos que están presentes en la matriz Y p veces donde p es un número primo. Estoy tratando de escribir esto en JS.
Por ejemplo:
Matriz X: [2, 3, 9, 2, 5, 1, 3, 7, 10]
Matriz Y: [2, 1, 3, 4, 3, 10, 6, 6, 1, 7, 10, 10, 10]
Matriz Z: [2, 9, 2, 5, 7, 10]
Hasta ahora tengo esto:
const arrX = [2, 3, 9, 2, 5, 1, 3, 7, 10] const arrY = [2, 1, 3, 4, 3, 10, 6, 6, 1, 7, 10, 10, 10] const arrZ = [] const counts = []; // count number occurrences in arrY for (const num of arrY) { counts[num] = counts[num] ? counts[num] + 1 : 1; } // check if number is prime const checkPrime = num => { for (let i = 2; i < num; i++) if (num % i === 0) return false return true } console.log(counts[10]); // returns 4Cualquier pista o ayuda apreciada. ¡Gracias!
Estás en el camino correcto. counts debe ser un objeto mapeando elementos en arrY a su número de ocurrencias. Se obtiene fácilmente con reduce .
La verificación principal necesita una edición menor y el último paso es filtrar arrX . El predicado de filtro es solo una verificación principal del recuento de ese elemento.
// produce an object who's keys are elements in the array // and whose values are the number of times each value appears const count = arr => { return arr.reduce((acc, n) => { acc[n] = acc[n] ? acc[n]+1 : 1; return acc; }, {}) } // OP prime check is fine, but should handle the 0,1 and negative cases: const checkPrime = num => { for (let i = 2; i < num; i++) if (num % i === 0) return false return num > 1; } // Now just filter with the tools you built... const arrX = [2, 3, 9, 2, 5, 1, 3, 7, 10] const arrY = [2, 1, 3, 4, 3, 10, 6, 6, 1, 7, 10, 10, 10] const counts = count(arrY); const arrZ = arrX.filter(n => checkPrime(counts[n])); console.log(arrZ)