0

I have two arrays Arr1 = [1,1,1,2,2,2,3,3] Arr2 =[1,1,2,1]

Comparing both arrays should return True as there are same occurrences of no. 1.

However If Arr2 = [1,1,2] it should return false as the no. Of occurrences of 1 or 2 don't match with the no. Of occurrences of 1 and 2 in Arr1

Even Arr2 = [1,1,2,3,1] should return True.

Thanks in advance! Cheers

I tried this but doesn't work for other instances.

function allElementsPresent(first, second) {
  return second.every((element) => first.includes(element));
}

3 Answers3

1

I believe I understand what you want to accomplish. You want to see if the number of occurrences in the second array matches the first. If that's the case, I've used this answer as a basis

function allElementsPresent(first, second, matchAll = false) {
  if (first.length > 0 && second.length === 0) return false;
  var counts1st = {};
  var counts2nd = {};

  for (var num of first) {
    counts1st[num] = counts1st[num] ? counts1st[num] + 1 : 1;
  }
  for (var num of second) {
    counts2nd[num] = counts2nd[num] ? counts2nd[num] + 1 : 1;
  }

  for (var count in counts2nd) {
    if (matchAll && (!counts1st[count] || counts1st[count] !== counts2nd[count])) return false;
    if (!matchAll && (counts1st[count] && counts1st[count] === counts2nd[count])) return true;
  }
  return matchAll ? true : false;
}
milklizard
  • 228
  • 1
  • 7
0

First conditional expression should be checking length

if (first.length != second.length) {
  // They don't have the same number of element thus we don't need to check further
  return -1
}

Then, try re-arranging the array in order. using an ordering algorithm

Then with two loop check if each element of the same index matches each array like below

for(int i =0;i<length;i++)
{
  if (first[i] != second[i]) {
    //if they don't at this instance both array does not have all elements
    return -1;
  }
}

Hope this helps

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
0

simple JS-magic, (if I understand the problem):

String(first).includes(second) && // second in first
/[^1,]/.test(second) // not all 1s or empty

Sometimes dynamic types really simplify things by treating data generically; use that strength where you can.

If the second array is not allowed to be uniform elements, but could be all non-1 digits, then it's more complicated:

String(first).includes(second) && // second in first
RegExp(`[^${second[0]},]`).test(second) // not all uniform or empty

as a function:

function allElementsPresent(first, second) {  
  return String(first).includes(second) && /[^1,]/.test(second)
}
dandavis
  • 16,370
  • 5
  • 40
  • 36