KarolaMach
KarolaMach

Reputation: 1

How to check if two int arrays are permutations in JavaScript

How can I check if two integers arrays are permutations? I need to do it in JavaScript.

For example, I have two arrays:

a = [1, 2, 3, 4, 5]

and

b = [2, 3, 5, 1, 4]

I need the program to return true.

Upvotes: 0

Views: 549

Answers (4)

claasic
claasic

Reputation: 1050

The lazy solution:

let a = [1,2,3,4,5],
    b = [2,3,5,1,4];

let res = JSON.stringify(a.sort()) === JSON.stringify(b.sort())

console.log(res)

The more efficient solution:

function perm (a,b) {
  let map = a.reduce((acc,c) => {acc[c] = (acc[c] || 0) + 1; return acc},{})
  for (el of b) {
    if (!map[el] || map[el] == 0) {
      return false;
    } else {
      map[el]--;
    }
  }
  for (k in map) {
    if (map[k] != 0) {
      return false;
    }
  }
  return true;
}

console.log(perm([1, 2, 3, 4, 5],[2, 3, 5, 1, 4])) // => true
console.log(perm([1, 2, 3, 4, 5, 5, 5],[2, 3, 5, 1, 4])) // => false
console.log(perm([1,1,2],[1,2,2])) // => false
console.log(perm([1,2,3,4,5,1],[2,3,1,5,1,4])) // => true

This solution is in hindsight similar to the one of @trincot but I guess slightly different enough to keep it posted.

The idea is the following: We create a map from the first array via reduce where the value is a count of occurrences. We then take the other array and subtract occurrences from the respective keys of map. If the key doesn't exist is or the value is already zero, we know this is not a permutation. Afterwords we loop the map, checking whether all values are exactly zero.

Upvotes: 2

AAA
AAA

Reputation: 3670

This worked:

var a =[1,2,3,4,5,1];
var b = [2,3,1,5,1,4];
console.log(a.sort().toString() === b.sort().toString())

Upvotes: 0

trincot
trincot

Reputation: 350320

You could use a Map to store the occurrence count and then decrease that count whenever you find a mapping occurrence in the other array:

function isPermutation(a, b) {
    if (a.length !== b.length) return false;
    let map = new Map(a.map(x => [x, { count: 0 }]));
    a.forEach(x => map.get(x).count++);
    return b.every(x => {
         let match = map.get(x);
         return match && match.count--;
    });
}

let a =[1,2,3,4,5,1];
let b = [2,3,1,5,1,4];
console.log(isPermutation(a, b));

Upvotes: 2

Fredrik
Fredrik

Reputation: 5108

var a = [1, 2, 3, 4, 5];
var b = [2, 3, 5, 1, 4];
return a.filter(x => !b.includes(x)).length === 0

This will return true if all of the values in a exists in b, regardless of position.

Upvotes: 1

Related Questions