4
2

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 1 year has passed since last update.

Dartで順列組み合わせ

Posted at

背景

つい最近、結構昔にコーディングした内容を、備忘録的にこんな記事としてQiitaに載せたのですが、何かの巡り合わせでしょうか・・・?
なぜか今度はDartで順列(上記事では組み合わせのみ記載)を書くことになったので、またしても備忘録として置いておきます。

出来上がり

順列

permutation.dart
List<List<int>> permutation(List<int> list, int n) {
  return n == 1 
  ? list.map((el) => [el]).toList()
  : list.asMap().entries.expand((entry){
  	return permutation(list.sublist(0, entry.key) + list.sublist(entry.key + 1), n - 1)
    	.map((el) => [entry.value] + el).toList();
  }).toList();
}

print(permutation([1,2,3],2));

// expexted : [[1,2],[1,3],[2,1],[2,3],[3,1],[3,2]]

組み合わせ

combination.dart
List<List<int>> combination(List<int> list, int n) {
  return n == 1 
  ? list.map((el) => [el]).toList()
  : list.asMap().entries.expand((entry){
  	return combination(list.sublist(entry.key + 1), n - 1)
    	.map((el) => [entry.value] + el).toList();
  }).toList();
}

print(combination([1,2,3],2));

// expexted : [[1,2],[1,3],[2,3]]

考え方

以前書いたjavascriptと全く同じです。大した内容ではありませんが、気になる方は以下を参照ください。

JavaScriptで関数型っぽく順列組み合わせを書いてみた

4
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
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?