JavaScript - 确定从序列中移除一组值的全部可能方式
我们需要编写一个 JavaScript 函数,该函数确定我们可以用多少种不同的方式从序列中移除一组值,同时保持原始序列的顺序(稳定),并确保每次只从原始序列中移除一个实例值。
例如 - 如果序列数组为 -
const arr = [1, 2, 1, 3, 1, 4, 4];
而要移除的数组为 -
const arr2 = [1, 4, 4];
那么有三种可能的方式可以做到这一点,而不会破坏元素的顺序 -
1 --> [2, 1, 3, 1] 2 --> [1, 2, 3, 1] 3 --> [1, 2, 1, 3]
因此,对于这些序列,我们的函数应该输出 3。代码如下 -
示例
const arr = [1, 2, 1, 3, 1, 4, 4]; const arr2 = [1, 4, 4]; const possibleRemovalCombinations = (original, part) => { const sorter = (a, b) => a - b; part.sort(sorter); let place = []; part.forEach(el => { place[el] = [] }); original.forEach((el, index) => { if(place[el]){ place[el].push(index); } }); let connection = part.map(el => place[el].slice()); for(let i = 1; i < connection.length; i++){ if (part[i - 1] != part[i]){ continue; } let left = connection[i - 1][0]; while(connection[i][0] <= left){ connection[i].shift(); }; }; for (let i = connection.length - 2; i >= 0; i--) { if(part[i] != part[i + 1]){ continue; } let right = connection[i + 1][connection[i + 1].length - 1]; while(connection[i][connection[i].length - 1] >= right){ connection[i].pop(); }; }; const combineArray = (step, prev, combination) => { for (let i = 0; i < connection[step].length; i++) { let curr = connection[step][i]; if(prev >= curr && original[prev] == original[curr]){ continue; } if(step + 1 == connection.length){ combinations.push(combination.concat([curr])) } else { combineArray(step + 1, curr, combination.concat([curr])); }; }; }; let combinations = [], res = []; combineArray(0, -1, []); for (let i = 0; i < combinations.length; i++) { let copy = original.slice(); combinations[i].forEach(el => copy[el]); res[i] = copy.filter(el => el !== undefined); }; return res.length; }; console.log(possibleRemovalCombinations(arr, arr2));
输出
控制台中的输出将为 -
3
广告