I have a list of words
Entrance Lobby Entrance Doors and Windows Security Stairwells Laundry Rooms Internal Guards and Handrails Garbage Chute Rooms Garbage Bin Storage Area Elevators Storage Areas & Lockers Interior Walls Ceilings and Floors Interior Lighting Levels Graffiti Exterior Cladding Exterior Grounds Exterior Walkways Balcony Guards Water Penetration on Exterior Building Elements Parking Area Other Facilities
I want to get all combinations of the words in sets of pairs
Entrance Doors and Windows, Security Stairwells
Entrance Lobby, Garbage Bin
ect...
The sentence is "What is more important to you?
I've found the following examples using permutations of N elements with runtime complexity in O(N!)
function getPermutations(sentence, word) {
const matches = sentence.split(" ").filter(w => w.includes(word));
let permutations = permute(matches);
return {
word: matches,
permutations
}
}
function permute(permutation) {
var length = permutation.length,
result = [permutation.slice()],
c = new Array(length).fill(0),
i = 1,
k, p;
while (i < length) {
if (c[i] < i) {
k = i % 2 && c[i];
p = permutation[i];
permutation[i] = permutation[k];
permutation[k] = p;
++c[i];
i = 1;
result.push(permutation.slice());
} else {
c[i] = 0;
++i;
}
}
return result;
}
console.log(getPermutations("THIS IS AN ISSUE FROM GIHAN", "IS"))
And this example :
function permute(permutation) {
var length = permutation.length,
result = [permutation.slice()],
c = new Array(length).fill(0),
i = 1, k, p;
while (i < length) {
if (c[i] < i) {
k = i % 2 && c[i];
p = permutation[i];
permutation[i] = permutation[k];
permutation[k] = p;
++c[i];
i = 1;
result.push(permutation.slice());
} else {
c[i] = 0;
++i;
}
}
return result;
}
console.log(permute([1, 2, 3]));