LoginSignup
2
2

More than 3 years have passed since last update.

[GAS] スプレッドシートで組み合わせを生成するスクリプト

Posted at

目的

組み合わせを作りたい。

結論

コード

// 直積集合
function cartesian_product(array) {
  return array.reduce(function(a,b){
      return a.map(function(x){
          return b.map(function(y){ return x.concat(y) })
        }).reduce(function(a,b){ return a.concat(b) },[])
    }, [[]])
}


function convert_values_to_array(values) {
  var array = []
  for(var i = 0; i < values.length; ++i){
    if( values[i][0] === ''){
      // pass
    } else {
      array.push(values[i][0])
    }
  }
  return array
}


function generate_combination() {
  const book = SpreadsheetApp.getActiveSpreadsheet()
  const sheet = {
      from: book.getSheetByName("from_name"), 
      out: book.getSheetByName("out_name")}
  // 出力先シートをきれいにしておく
  sheet.out.clear()

  const row = {
      first: 1, // Headerがあれば2 / なしなら1
      last: sheet.from.getLastRow()}
  const values = sheet.from.getDataRange().getValues()
  var array = []

  for (var j = 0; j < values[0].length; ++j) {
    array.push(convert_values_to_array(sheet.from.getRange(row.first, j+1, row.last).getValues()))
  }

  const r = cartesian_product(array)
  sheet.out.getRange(1, 1, r.length, r[0].length).setValues(r)
}

from データ

image.png

out データ

image.png

概説。

(実は、若干見様見真似なので、自分でも理解しきっていないところがあります。すいません。)
直積集合使えるよ? みたいなことを、高専時代の同期に言われたので、色々検索したところ、それっぽいのにあたりました。

Stack Overflow - Cartesian product of multiple arrays in JavaScript

ここの部分。

function cartesian_product(array) {
  return array.reduce(function(a,b){
      return a.map(function(x){
          return b.map(function(y){ return x.concat(y) })
        }).reduce(function(a,b){ return a.concat(b) },[])
    }, [[]])
}
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2