1
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.

jsで配列を分解した全パターンを取得する

Posted at

#やりたいこと
わかりやすく言葉で説明できないので、完成イメージをかきます!

console.log(allSubArray([1,2,3]);
/* 
[
[[1], [2], [3]], 
[[1, 2], [3]],
[[1], [2, 3]],
[[1, 2, 3]]
] 

(順番の入れ替え([[1, 3], [2]]など)は考慮しません)
*/

何に使うの?とか言わないでください :)

#考え方
###再帰使えるかな・・・

const allSubArray(array) => {
     // 再帰終了条件
    if(array.length === 0) return [[]];

    cosnt result = [];
    // array = [1,2,3,4]とする
    /* 最初は0番目の要素[1]とそれ以外[2,3,4]に分割して考える */
    const subArrays = allSubArray([2,3,4]);
    // subArrays = [[[2], [3], [4]], [[2,3],[4]], [[2],[3,4]], [[2,3,4]] ] が期待される

    // [1]とsbuArraysの各要素をくっつけたものをresultにpush
    /* 期待されるresultは
   [
       [[1], [2], [3], [4]],
       [[1], [2,3], [4]],
       [[1], [2], [3,4]],
       [[1], [2,3,4]]
     ]
   */

  /* 次に、1番目までのの要素[1, 2]とそれ以外[3,4]に分割して考える*/
  /* 今感じで行けるか・・・? */

}

#やってみよう


const allSubArray = (array) => {
    // 再帰終了条件
    if(array.length === 0) return [[]];


    const result = [];
    // array = [1,2,3,4]とする
    /* 最初は0番目の要素[1]とそれ以外[2,3,4]に分割して考える */
    for(let i = 1; i <= array.length; i++) {
      const fixedArray = array.slice(0, i);  //i=1の時:fixedArray = [1], i=2の時:fixedArray =[1,2]
      const otherArray = array.slice(i); //i=1の時:otherArray = [2,3,4]

      // i=1の時:subArrays = [[[2], [3], [4]], [[2,3],[4]], [[2],[3,4]], [[2,3,4]] ] が期待される
      const subArrays = allSubArray(otherArray);
      for(const subArray of subArrays) {
        result.push([fixedArray].concat(subArray));
      }
    }
    return result;
}

#実行結果

できてる!!(何に使うんだろう)

1
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
1
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?