Home > OS >  JS Number of occurences in a sequence is a prime number
JS Number of occurences in a sequence is a prime number

Time:11-28

I have two arrays (X and Y) and I need to create array Z that contains all elements from array X except those, that are present in array Y p times where p is a prime number. I am trying to write this in JS.

For Example:
Array X: [2, 3, 9, 2, 5, 1, 3, 7, 10]
Array Y: [2, 1, 3, 4, 3, 10, 6, 6, 1, 7, 10, 10, 10]
Array Z: [2, 9, 2, 5, 7, 10]

So far I have this:

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

Any hint or help appreciated. Thanks!

CodePudding user response:

You're on the right track. counts should be an object mapping elements in arrY to their number of occurrences. It's easily gotten with reduce.

The prime check needs a minor edit, and the last step is to filter arrX. The filter predicate is just a prime check on the count for that element.

// 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) 
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related