順列組み合わせ JavaScript(ES2015)

順列組み合わせ JavaScript(ES2015):

https://qiita.com/higuma/items/5af4e62bdf4df42ce673

を参考にJavaScript(ES2015)での順列組み合わせ関数を作成したのでメモとして残しておく。

以下のコードの解説の再帰処理の流れが非常に参考になった。
https://qiita.com/higuma/items/5af4e62bdf4df42ce673#%E3%82%B3%E3%83%BC%E3%83%89%E3%81%AE%E8%A7%A3%E8%AA%AC


メイン

// pre: 1st half of array 
// post: 2nd half of array 
const permutation = ({ result = [], pre = [], post, n = post.length }) => { 
  if (n > 0) { 
    post.forEach((_, i) => { 
      const rest = [...post]; 
      const elem = rest.splice(i, 1); 
      permutation({ result, pre: [...pre, ...elem], post: rest, n: n - 1}); 
    }); 
  } else { 
    result.push(pre); 
  } 
  return result; 
}; 
 
const array = [0, 1, 2, 3]; 
const results = permutation({ post: array }); 
console.log(results); 
 
const results2 = permutation({ post: array, n: 2 }); 
console.log(results2); 


結果

[ [ 0, 1, 2, 3 ], 
  [ 0, 1, 3, 2 ], 
  [ 0, 2, 1, 3 ], 
  [ 0, 2, 3, 1 ], 
  [ 0, 3, 1, 2 ], 
  [ 0, 3, 2, 1 ], 
  [ 1, 0, 2, 3 ], 
  [ 1, 0, 3, 2 ], 
  [ 1, 2, 0, 3 ], 
  [ 1, 2, 3, 0 ], 
  [ 1, 3, 0, 2 ], 
  [ 1, 3, 2, 0 ], 
  [ 2, 0, 1, 3 ], 
  [ 2, 0, 3, 1 ], 
  [ 2, 1, 0, 3 ], 
  [ 2, 1, 3, 0 ], 
  [ 2, 3, 0, 1 ], 
  [ 2, 3, 1, 0 ], 
  [ 3, 0, 1, 2 ], 
  [ 3, 0, 2, 1 ], 
  [ 3, 1, 0, 2 ], 
  [ 3, 1, 2, 0 ], 
  [ 3, 2, 0, 1 ], 
  [ 3, 2, 1, 0 ] ] 
[ [ 0, 1 ], 
  [ 0, 2 ], 
  [ 0, 3 ], 
  [ 1, 0 ], 
  [ 1, 2 ], 
  [ 1, 3 ], 
  [ 2, 0 ], 
  [ 2, 1 ], 
  [ 2, 3 ], 
  [ 3, 0 ], 
  [ 3, 1 ], 
  [ 3, 2 ] ] 


参考

https://qiita.com/s-katsumasa/items/7b8ce83df22467f74c51

にも書いてあるが、Rubyの場合 Array#permutation があるが、JSでは同等のものはなさそう。

instance method Array#permutation (Ruby 2.5.0)
https://docs.ruby-lang.org/ja/latest/method/Array/i/permutation.html

コメント

このブログの人気の投稿

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)