Created
January 23, 2014 17:11
-
-
Save umezo/8582650 to your computer and use it in GitHub Desktop.
全ての順列を生成する関数
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 与えられたリストの全ての並び順を生成して返す | |
* ex) makeOrder( [1,2,3] ) -> [ [1,2,3], | |
* [1,3,2], | |
* [2,3,1], | |
* [2,1,3], | |
* [3,1,2], | |
* [3,2,1]] | |
* | |
* @param {Array} | |
* @return {Array<Array>} | |
*/ | |
function makeOrder( list ){ | |
//要素がなければ並び順は作れない | |
if( list.length === 0 ){ | |
return null; | |
} | |
//再帰にありがちな固定return | |
if( list.length === 1 ){ | |
return [ [ list[0] ] ]; | |
} | |
var //生成された並び順を格納する配列 | |
result = [], | |
//一時変数 ループ中の先頭要素 | |
head, | |
//一時変数 ループ内で破壊的にlistを弄りたいため | |
cloneList; | |
for( var i = 0 , n = list.length; i<n ; i++ ){ | |
//listをクローン | |
cloneList = list.concat([]); | |
//準々に先頭要素を交代していく | |
head = cloneList.splice( i,1 ); | |
//先頭要素以外で全ての並び順を生成する (再帰) | |
remainList = makeOrder( cloneList ); | |
//生成されたルートに先頭要素を足す | |
for( var j = 0 , m = remainList.length ; j<m ; j++ ){ | |
remainList[j].unshift( head[0] ); | |
result.push( remainList[j] ); | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment