简体   繁体   中英

Find word in string using RegEx javascript

How can I make a search function using regEx? I have some code but can't post it at the moment due to my computer being very broken and annoying, I will try again tomorrow!

This is not really what would be called combinations , but permutations .

The idea is to use recursion for getting the result for a shorter array, ie the one that lacks the first element.

Then take all permutations you get back from the recursive call, and insert the left-out value in each possible index.

When input has duplicates, then you need to stop inserting the left-out value as soon as you find that same value preceding the insertion spot.

Here is how that looks:

 function scramble(array) { if (array.length == 0) { return [[]]; } let results = []; // solve the problem for a shorter array (first value excluded), and iterate: for (let perm of scramble(array.slice(1))) { // add the missing element in each possible position: for (let i = 0; i < array.length; i++) { // next IF is only needed when input has duplicates, and // output should not repeat same array: if (i && array[0] === perm[i-1]) break; results.push(perm.slice(0, i).concat(array[0], perm.slice(i))); } } return results; } let array = ["I", "am", "coding", "am"]; console.log(scramble(array));

Without the inner if , an input with duplicate values will produce duplicate arrays. If this is not desired, then the if is needed.

You could iterate and get a flat array of the mapping of the value with the result of the nested calls.

 function permutation(array) { return array.length === 1 ? [array] : array.flatMap((v, i) => permutation([ ...array.slice(0, i), ...array.slice(i + 1) ]).map(a => [v, ...a])); } permutation(["I", "am", "coding"]).map(a => console.log(...a));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM