Skip to content

Instantly share code, notes, and snippets.

@77web
Created January 13, 2015 12:26
Show Gist options
  • Save 77web/23fe467c0c6a6be75898 to your computer and use it in GitHub Desktop.
Save 77web/23fe467c0c6a6be75898 to your computer and use it in GitHub Desktop.
配列をグルーピングするパターンを全列挙するやつ(js)試作品(未完成)
G = {
grouping: function(elements) {
var i,j,k = 0;
var groups= [];
for (i = 1; i <= elements.length; i++) { // i:分割後のグループ数
var grps = G.divideIntoGroups(elements, i);
for (j = 0; j < grps.length; j++) {
groups.push(grps[j]);
}
}
return groups;
},
divideIntoGroups: function(elements, groupCount) {
if (groupCount == 1) {
return [elements];
}
var i,j,k = 0;
var grps = [];
var _grps = [];
if (groupCount == 2) {
for (i = 1; i < (elements.length / 2); i++) { // i:一番小さいグループの要素数
_grps = G.makeTwoGroups(elements, i);
for (j = 0; j < _grps.length; j++) {
grps.push(_grps[j]);
}
}
return grps;
}
/* FIXME どうやったらいいか思いつかない…
for (i = 1; i < groupCount; i++) {
}
*/
return grps;
},
makeTwoGroups: function(elements, sizeOfSmallestGroup) {
var i,j,k = 0;
var firstGroups = [];
var _grps = [];
for (i = 0; i < elements.length; i++) {
_grps = G.func(elements, i, sizeOfSmallestGroup);
for (j = 0; j < _grps.length; j++) {
firstGroups.push(_grps[j]);
}
}
var grps = [];
var secondGroup = [];
for (i = 0; i < firstGroups.length; i++) {
secondGroup = [];
for (j = 0; j < elements.length; j++) {
if (-1 == firstGroups[i].indexOf(elements[j])) {
secondGroup.push(elements[j]);
}
}
grps.push([firstGroups[i], secondGroup]);
}
return grps;
},
func: function(elements, fixedKey, length, grps){
var i,j,k = 0;
var grp = 0;
var newGrps = [];
grps = grps || [[]];
for (i = 0; i < grps.length; i++) {
grp = grps[i].slice(0);
grp.push(elements[fixedKey]);
newGrps.push(grp);
}
if (newGrps[0].length == length) {
return newGrps;
}
var newGrps2 = [];
var _grps = [];
for (i = fixedKey + 1; i < elements.length; i++) {
_grps = G.func(elements, i, length, newGrps);
for (j = 0; j < _grps.length; j++) {
newGrps2.push(_grps[j]);
}
}
return newGrps2;
}
};
//console.debug(G.func(['A','B','C'], 0, 3));
//console.debug(G.makeTwoGroups(['A','B','C','D'], 2));
console.debug(G.divideIntoGroups(['A','B','C'], 3));
//console.debug(G.grouping(['A','B','C']));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment