2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

JavaScript: 配列の直積を返すジェネレータを作ってみた

Last updated at Posted at 2020-11-08

前の記事のついでにやってみた。
多重ループとかの時に便利そう。

// 直積を返すジェネレータの内部再帰関数
const innerProdG = selected => (xs, ...xss) => function*(){
  if (xs === undefined ) {
      yield selected
      return
  }
  for (const x of xs) yield* innerProdG( [...selected, x] )( ...xss )
}()

// 複数の配列をとって直積を返すジェネレータ
const prodG = 
  innerProdG([])

// 使用例:
const a = [0, 1]
const b = [2, 3]
const c = [4, 5]

for(const e of prodG(a, b, c)) console.log(e)
/* 
[ 0, 2, 4 ]
[ 0, 2, 5 ]
[ 0, 3, 4 ]
[ 0, 3, 5 ]
[ 1, 2, 4 ]
[ 1, 2, 5 ]
[ 1, 3, 4 ]
[ 1, 3, 5 ]
 */
2
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?