js-combinatorics
js-combinatorics copied to clipboard
Any way to handle duplicates?
I have a set of elements with possible duplication.
I need to get all possible permutations of combinations but removing duplicates.
Like so:
const all = ['a', 'a', 'b'];
const cmb = Combinatorics.permutationCombination(all);
console.log(cmb.toArray());
Expected output is:
[ [ 'a' ],
[ 'b' ],
[ 'a', 'a' ],
[ 'a', 'b' ],
[ 'b', 'a' ],
[ 'a', 'a', 'b' ],
[ 'a', 'b', 'a' ],
[ 'b', 'a', 'a' ] ]
but instead, I am getting
[ [ 'a' ],
[ 'a' ],
[ 'b' ],
[ 'a', 'a' ],
[ 'a', 'a' ],
[ 'a', 'b' ],
[ 'b', 'a' ],
[ 'a', 'b' ],
[ 'b', 'a' ],
[ 'a', 'a', 'b' ],
[ 'a', 'b', 'a' ],
[ 'a', 'a', 'b' ],
[ 'a', 'b', 'a' ],
[ 'b', 'a', 'a' ],
[ 'b', 'a', 'a' ] ]
So far I have been able to work around this with a control list and checking while iterating. I could refactor this into a lazyFilter that checks such list, but it would pretty much be the same as I still need to externally keep track of the already visited permutations.
Any way to keep this contained within the library?
An example of external control list would be something like this:
const checked = [];
let controlHash = '';
let element;
while (element = cmb.next()) {
controlHash = element.join('');
if (checked.indexOf(controlHash) === -1) {
console.log(element);
checked.push(controlHash);
}
}
As you can see it adds quite a bit to a simple code that should simply iterate a precalculated list
Why don't you create your input as a Set
?
On Sat., 29 Dec. 2018, 6:04 am Barbazul <[email protected] wrote:
An example of external control list would be something like this:
const checked = [];let controlHash = '';let element; while (element = cmb.next()) { controlHash = element.join(''); if (checked.indexOf(controlHash) === -1) { console.log(element); checked.push(controlHash); } }
As you can see it adds quite a bit to a simple code that should simply iterate a precalculated list
— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/dankogai/js-combinatorics/issues/56#issuecomment-450419092, or mute the thread https://github.com/notifications/unsubscribe-auth/AAFR38akwu0E0fHKufbcHUJ1OWzvPs6Pks5u9nlTgaJpZM4ZkLXD .