JavaScriptで配列と抜き取り数を与えると全ての順列、組合せを配列で返す関数です。
関数
順列
function junretsu(balls, nukitorisu){
var arrs, i, j, zensu, results, parts;
arrs = [];
zensu = balls.length;
if(zensu < nukitorisu){
return;
}else if(nukitorisu == 1){
for(i = 0; i < zensu; i ++){
arrs[i] = [balls[i]];
}
}else{
for(i = 0; i < zensu; i ++){
parts = balls.slice(0);
parts.splice(i, 1)[0];
results = junretsu(parts, nukitorisu - 1);
for(j = 0; j < results.length; j ++){
arrs.push([balls[i]].concat(results[j]));
}
}
}
return arrs;
}
var arrs, i, j, zensu, results, parts;
arrs = [];
zensu = balls.length;
if(zensu < nukitorisu){
return;
}else if(nukitorisu == 1){
for(i = 0; i < zensu; i ++){
arrs[i] = [balls[i]];
}
}else{
for(i = 0; i < zensu; i ++){
parts = balls.slice(0);
parts.splice(i, 1)[0];
results = junretsu(parts, nukitorisu - 1);
for(j = 0; j < results.length; j ++){
arrs.push([balls[i]].concat(results[j]));
}
}
}
return arrs;
}
組合せ
function kumiawase(balls, nukitorisu){
var arrs, i, j, zensu, kumis;
arrs = [];
zensu = balls.length;
if(zensu < nukitorisu){
return;
}else if(nukitorisu == 1){
for(i = 0; i < zensu; i++){
arrs[i] = [balls[i]];
}
}else{
for(i = 0; i < zensu - nukitorisu + 1; i ++){
kumis = kumiawase(balls.slice(i + 1), nukitorisu - 1);
for(j = 0; j < kumis.length; j ++){
arrs.push([balls[i]].concat(kumis[j]));
}
}
}
return arrs;
}
var arrs, i, j, zensu, kumis;
arrs = [];
zensu = balls.length;
if(zensu < nukitorisu){
return;
}else if(nukitorisu == 1){
for(i = 0; i < zensu; i++){
arrs[i] = [balls[i]];
}
}else{
for(i = 0; i < zensu - nukitorisu + 1; i ++){
kumis = kumiawase(balls.slice(i + 1), nukitorisu - 1);
for(j = 0; j < kumis.length; j ++){
arrs.push([balls[i]].concat(kumis[j]));
}
}
}
return arrs;
}
使い方
配列を与えるとそれを並び変えた配列を、また配列として返します。結果はリテラルで書いてありますが実際は配列です。
順列
arrs = [1, 2, 3, 4];
results = junretsu(arrs, 3);
results = junretsu(arrs, 3);
結果
[[1,2,3],[1,2,4],[1,3,2],[1,3,4],[1,4,2],[1,4,3],[2,1,3],[2,1,4],[2,3,1],[2,3,4],[2,4,1],[2,4,3],[3,1,2],[3,1,4],[3,2,1],[3,2,4],[3,4,1],[3,4,2],[4,1,2],[4,1,3],[4,2,1],[4,2,3],[4,3,1],[4,3,2]]
組合せ
arrs = [1, 2, 3, 4];
results = kumiawase(arrs, 3);
results = kumiawase(arrs, 3);
結果
[[1,2,3],[1,2,4],[1,3,4],[2,3,4]]
コメント