-2

I am trying to solve a problem where I have to check if two different numbers contain the same numbers, for example 12 and 21, 34 and 43 and so on. I found this method work out, but it is very complicated and not practical. Any better idea?

let num = 3332
let num2 = 3323

let arr = Array.from(num.toString()).map(Number);
let arr2 = Array.from(num2.toString()).map(Number);
if (arr2.includes(arr[0],arr[1],arr[2], arr[3])) {
  console.log("it works")
}

Thanks!!!

thomalex
  • 59
  • 1
  • 2
  • 8
  • `includes` doesn't take multiple arguments like that. It accepts a **single** argument to search for, and an optional starting index. (It has no further parameters after those first two.) – T.J. Crowder Sep 21 '20 at 16:16
  • @TKoL - Hit refresh, the *instant* I hit Add Comment I went *Doh!* and deleted it. – T.J. Crowder Sep 21 '20 at 16:16
  • 1
    Should `23` and `323` match? – Barmar Sep 21 '20 at 16:18
  • @thomalex it's not exactly clear to me the conditions that your function should return true / false for a match or miss. You say 21 and 12 should be a match, but what about 112 and 221? – TKoL Sep 21 '20 at 16:18

2 Answers2

2

Your current test is not accurate because it doesn't check if the num2 contains other numbers as well - for example, 9993332 would match as well.

One possibility is to sort the digits, then check that every digit at an index is equal to every digit in the other array:

const toArr = num => [...String(num)].sort();
const check = (num1, num2) => {
  const arr1 = toArr(num1);
  const arr2 = toArr(num2);
  return arr1.length === arr2.length && arr1.every(
    (digit, i) => arr2[i] === digit
  );
};
console.log(check(3332, 3323));
console.log(check(3332, 9993323));

(Once we get Array.prototype.equals, the above simplifies to => toArr(num1).equals(toArr(num2))

A less computationally expensive way (but harder to read at a glance) would be to turn each number into an object which counts up frequencies, then compare the objects.

const toObj = num => {
  const obj = {};
  for (const char of String(num)) {
    obj[char] = (obj[char] || 0) + 1;
  }
  return obj;
};
const check = (num1, num2) => {
  const entries1 = Object.entries(toObj(num1));
  const obj2 = toObj(num2);
  return (
    entries1.length === Object.keys(obj2).length &&
    entries1.every(([key, val]) => obj2[key] === val)
  );
};
console.log(check(3332, 3323));
console.log(check(3332, 9993323));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

You could sort digits get a string and compare with the other string.

function check(a, b) {
    return Array.from(a.toString()).sort().join('') === Array.from(b.toString()).sort().join('');
}

console.log(check(3332, 3323));
console.log(check(117, 771));
console.log(check(113, 771));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392