簡體   English   中英

JS 序列中出現的次數是素數

[英]JS Number of occurences in a sequence is a prime number

我有兩個 arrays(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

任何提示或幫助表示贊賞。 謝謝!

你在正確的軌道上。 counts應該是一個 object 將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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM