Skipping permutations
arve0 opened this issue · 1 comments
arve0 commented
Hi!
In some problems, skipping permutations that does not solve the problem is an effective optimization. Would it be possible to add skipping of permutations?
Example:
for (let perm of G.permutations([1,2,3,4,5])) {
if (shouldSkip(perm)) {
// "increments" element at position 1
G.incrementElement(1);
// given perm == [1, 2, 3, 4, 5],
// 2 is at index 1,
// next permutations will be [1, 3, 2, 4, 5]
}
if (isSolution(perm)) {
break;
}
}
function shouldSkip (perm) {
// we know somehow that any permutations starting
// with 1 and 2 will not solve the problem
// e.g. none of these will solve the problem: [1,2,3,4,5], [1,2,3,4,5], [1,2,4,3,5] ....
return perm[0] === 1 && perm[1] === 2;
}
PS: I've not looked into the code, but will take a grab at it if this sounds like a reasonable addition.
arve0 commented
An example using the generator for signaling:
let generator = G.permutations([1,2,3,4,5]);
let v = generator.next();
while (!v.done) {
let perm = v.value;
if (shouldSkip(perm)) {
// "increments" element at position 1
v = generator.next(1);
// given perm == [1, 2, 3, 4, 5],
// 2 is at index 1,
// next permutations will be [1, 3, 2, 4, 5]
continue;
}
if (isSolution(perm)) {
break;
}
v = generator.next(); // get next permutation
}