Reputation: 2431
I am trying to learn Regex but this is quite a complex question for me to understand: how do you check if one number's characters matches another number's characters? I feel examples will explain this better:
If the number is 12:
12 and 21 are true
11 and 22 are false
If the number is 323:
Here is a sample code to test with (the best Regex I can come up with):
//Testing 12
for (i = 1; i < 99; i++) {
if (i.toString().match(/[12][12]/)) {
console.log(i)
}
}
console.log('#####')
//Testing 332
for (i = 1; i < 999; i++) {
if (i.toString().match(/[32][32][32]/)) {
console.log(i)
}
}
Upvotes: 0
Views: 64
Reputation: 5148
You can sort the digits in your number, sort the digits of your input - and compare the sorted lists.
If the input is a permutation of the original number, the sorted digits arrays should be identical.
This example prints only the permutations of its first argument:
let compareFunc = (initial, arrayToCheck) => {
let initial_digits = initial.toString().split('');
initial_digits.sort();
arrayToCheck.forEach(function(item) {
let item_digits = item.toString().split('');
item_digits.sort();
if(item_digits.toString() === initial_digits.toString()) {
console.log(item + ' is a permutation of ' + initial);
}
})
}
compareFunc(321, [1,2,123,213]);
The use of regular expressions here is very inefficient, as you'll need to start by calculating all the permutations of your number. You usually don't want to go there, as permutations calculation has time complexity of O(n!).
Upvotes: 2