Google表格-从列中生成所有可能的字符串组合

时间:2018-07-15 13:48:58

标签: javascript arrays google-apps-script google-sheets combinations

您好(对于模棱两可的问题标题,我们深表歉意,欢迎使用更好的标题)

我目前有一个看起来像这样的数据表:

CLASS       Type A  Type B  Type C
A              1       3      7
B              2       4      8
C                               
D               

通过公式(我不知道如何)或脚本,我试图获取每个“类”与每种类型的组合,例如:

A1,A2,A3,A4,A7,A7和A13,A14,A17等和A137,A138等(+所有其他可能性)。到目前为止,我只设法获得了“ 2位数”版本。

到目前为止,下面的代码(在我的数据中,我还有一些额外的列,告诉我该特定类需要哪种类型):

function expand(){
  //create the sheet to use
  var ss = SpreadsheetApp.getActive().getSheetByName('data');
  //create blank array
  var fin_resultAry = [];
  //extract the range of data
  var main_Range =  ss.getRange('A2:D5').getValues();
  //extract all the variations of data
  var range1 = ss.getRange('E2:E3').getValues();
  var range2 = ss.getRange('F2:F3').getValues();
  var range3 = ss.getRange('G2:G3').getValues();
  
  //create dictionary with variations
  var var_dict = {1: range1, 2: range2, 3: range3}
    
  //main for loop
  for(var k = 0; k<main_Range.length;k++){
    //push the initial no type variation
    fin_resultAry.push(main_Range[k][0]);    
    //create the loop to check what class variations have the set value == true
    for(var i = 1; i<=main_Range[k].length;i++){
      if (main_Range[k][i] == true){
        //for each of the variations add the var string to the initial class and push it
        for(var j = 0; j<var_dict[i].length;j++){
          fin_resultAry.push(main_Range[k][0] + " " + var_dict[i][j][0]);
        }  
      }
    }
  }    
  return fin_resultAry;
  }

还请注意,我的数据有很多“类”和3种以上的类型,这使得使用公式成为不可能,因为它们仅限于X行/字符/等。

1 个答案:

答案 0 :(得分:1)

这是用于生成不同组合的“以3为底数”方法的实现:

function expand(classes,types) {
 //No. of classes
  var nClasses=classes.length;
  //No. of types;
  var nTypes=types[0].length;
  //No. of 'subtypes' i.e. rows in type columns;
  var nSubTypes=types.length;
  //No. of combinations to go through for types;
  var nCombinations=Math.pow(nSubTypes+1,nTypes)-1;

  var resultArray=[];
  var iRow;
  var comb;
  // Loop over classes
  for (var iClass=0;iClass<nClasses;iClass++)
  {
    var class=classes[iClass];
    // Loop over all combinations of types
    for (var iComb=0;iComb<nCombinations;iComb++)
    {
      var shift=iComb;
      comb=class;
      //Pick out array elements for one combination of types
      for (var iType=0;iType<nTypes;iType++)
      {
        iRow=shift%(nSubTypes+1);

        if (iRow<nSubTypes)
          comb=comb+types[iRow][iType];

        shift=Math.floor(shift/(nSubTypes+1))
      }
    resultArray.push(comb);
    }
  }
  return resultArray.sort();
}

它称为

=expand(classes,types)

例如测试数据

=expand(A2:A5,E2:G3)

enter image description here