排列组合算法在项目的应用

Posted by Turingdo Studio on June 7, 2018

应用一

var arr = [[{name:'小明'},{name:'小花'}],[{age:10},{age:30}],[{height:180},{height:175}],[{grade:'一'},{grade:'二'}]];
/**
 * 排列组合
 * eg.
 * @param arr 一个二维数组 如: const arr = [[{name:'小明'},{name:'小花'}],[{age:10},{age:30}]];
 * @returns {*} 返回一个排列组合后的一维数组 [{name: "小明", age: 10},{name: "小明", age: 30},{name: "小花", age: 10},{name: "小花", age: 30}]
 */
  function genNewArr(arr) {
      if (!arr.length) {
          return [];
      }
      const result = [];
      //先提取出来两个元素,考虑两个元素组合的情况
      //两个元素排列组合生成的数组,然后再与其余数组递归
      const [arr1, arr2, ...others] =[...arr];
      if (arr.length === 1) {
          return arr1;
      }
      console.log(arr1, arr2, others)

      arr1.forEach(item1 => {
          arr2.forEach(item2 => {
              result.push({...item1, ...item2})
          })
      });
      if (!others.length) {
          console.log('--->', result)
          return result
      }
      permutation([...others, result]);

  }

应用二

var arr=[[“颜色:白色”,“颜色:黑色”],[“尺码:10”,“尺码:20”],[“材质:钻石”,“材质:水晶”,“材质:玛瑙”]];

网上示例

function getProducts(specs) {
    if (!specs || specs.length == 0) {
        return [];
    } else {
        return joinSpec([[]], specs, 0, specs.length-1);
    }
    function joinSpec(prevProducts, specs, i, max) {
        var currentProducts = [], currentProduct, currentSpecs = specs[i];
        if ( i > max ) {
            return prevProducts;
        }
        prevProducts.forEach(function(prevProduct) {
            currentSpecs.forEach(function(spec) {
                currentProduct = prevProduct.slice(0);
                currentProduct.push(spec);
                currentProducts.push(currentProduct);
            });
        });
        return joinSpec(currentProducts, specs, ++i, max);
    }
}

var specs = [[{"spec_name":"颜色","spec_type":"1","spec_id":"5","spec_value_id":"11","spec_value_name":"白色"},{"spec_name":"颜色","spec_type":"1","spec_id":"5","spec_value_id":"12","spec_value_name":"黑色"}],[{"spec_name":"尺码","spec_type":"0","spec_id":"6","spec_value_id":"9","spec_value_name":"10"},{"spec_name":"尺码","spec_type":"0","spec_id":"6","spec_value_id":"10","spec_value_name":"20"}],[{"spec_name":"材质","spec_type":"0","spec_id":"7","spec_value_id":"13","spec_value_name":"钻石"},{"spec_name":"材质","spec_type":"0","spec_id":"7","spec_value_id":"14","spec_value_name":"水晶"},{"spec_name":"材质","spec_type":"0","spec_id":"7","spec_value_id":"15","spec_value_name":"玛瑙"}]];

console.log(getProducts(specs));