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

更新於: 2020年11月23日

66 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.