I was wondering how to check if a number is a permutation of another number in Javascript.
Ex:
perm(1234,2413); ---> True
perm(154,154); ---> True
perm(101,011); ---> False
perm(501,104); --->False
Any help would be appreciated :)
I was wondering how to check if a number is a permutation of another number in Javascript.
Ex:
perm(1234,2413); ---> True
perm(154,154); ---> True
perm(101,011); ---> False
perm(501,104); --->False
Any help would be appreciated :)
I would do this just by converting each input into an array of characters, then sorting them, and then just checking for equality. If two inputs are permutations of each other, then sorting them will put them into the same order, at which point it's easy to see if they're the same:
function perm(n1, n2) {
return String(n1).split("").sort().join("") === String(n2).split("").sort().join("");
}
console.log(perm(1234,2413)); // ---> True
console.log(perm(154,154)); // ---> True
console.log(perm(101,011)); // ---> False
console.log(perm(501,104)); // --->False
Here's a snippet of code that converts the two numbers to strings, then checks if the second number is contained in an array of permutations of the first number.
The permutation function is from this question: Permutations in JavaScript?. I did not duplicate the answer, I simply included a piece of code available online that permutes strings and I cited it appropriately. The other function and all of the comments/explanations are mine.
var permArr = [],
usedChars = [];
function permute(input) {//Returns an array of all permutations of a string
var i, ch, chars = input.split("");
for (i = 0; i < chars.length; i++) {
ch = chars.splice(i, 1);
usedChars.push(ch);
if (chars.length == 0)
permArr[permArr.length] = usedChars.join("");
permute(chars.join(""));
chars.splice(i, 0, ch);
usedChars.pop();
}
return permArr
}
console.log(permute("HI!"))
//Returns permutations of "HI!"
function perm(firstnum, secondnum) {//My original code!
if (permute(firstnum.toString()).includes(secondnum.toString())) {//test if the second number, converted to a string, is in an array of permutations of the first number
return true
} else {
return false
}
}
//Converts both numbers to strings, checks if second number is a permutation of first number
console.log(perm(123, 321))//Returns true