我有兩個陣列(X 和 Y),我需要創建陣列 Z,其中包含陣列 X 中的所有元素,除了那些出現在陣列 Y 中 p 次的元素,其中 p 是素數。我想用JS寫這個。
例如:
陣列 X:
[2, 3, 9, 2, 5, 1, 3, 7, 10]
陣列 Y:
[2, 1, 3, 4, 3, 10, 6, 6, 1, 7, 10, 10, 10]
陣列 Z:
[2, 9, 2, 5, 7, 10]
到目前為止,我有這個:
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 4
任何提示或幫助表示贊賞。謝謝!
uj5u.com熱心網友回復:
你在正確的軌道上。counts應該是一個物件,將元素映射arrY到它們的出現次數。它很容易得到reduce。
主要檢查需要一個小的編輯,最后一步是過濾arrX. 過濾謂詞只是對該元素計數的主要檢查。
// 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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/367810.html
標籤:javascript 数组 数数 序列 素数
下一篇:保留 , 讀取XML時
