Skip to content

Instantly share code, notes, and snippets.

@nekoTheShadow
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nekoTheShadow/9d1de5469418a0437d7d to your computer and use it in GitHub Desktop.
Save nekoTheShadow/9d1de5469418a0437d7d to your computer and use it in GitHub Desktop.
Array.prototype.sliceByIndex = function(idxs){
var items = this;
var slicedVals = idxs.map(function(idx){
return items[idx];
});
return slicedVals;
}
var range = function(min,max){
var nums = [];
for (var num = min; num <= max; num++){
nums.push(num);
}
return nums;
}
Array.prototype.combination = function(n){
var items = this;
var length = items.length;
var idxs = range(0,length-1);
var idxPerms = idxs.map(function(idx){
return [idx];
});
for (var idxsIdx = 0; idxsIdx < n-1; idxsIdx++){
var nextIdxPerms = [];
idxPerms.forEach(function(idxPerm){
var lastIdx = idxPerm[idxsIdx];
var nextIdxs = idxs.filter(function(idx){
return lastIdx < idx;
});
nextIdxs.forEach(function(nextIdx){
var nextIdxPerm = idxPerm.slice(0);
nextIdxPerm.push(nextIdx);
nextIdxPerms.push(nextIdxPerm);
});
});
idxPerms = nextIdxPerms.slice(0);
}
perms = idxPerms.map(function(idxPerm){
return items.sliceByIndex(idxPerm);
});
return perms;
}
Array.prototype.repeatedCombination = function(n){
var items = this;
var length = items.length;
var idxs = range(0,length-1);
var idxPerms = idxs.map(function(idx){
return [idx];
});
for (var idxsIdx = 0; idxsIdx < n-1; idxsIdx++){
var nextIdxPerms = [];
idxPerms.forEach(function(idxPerm){
var lastIdx = idxPerm[idxsIdx];
var nextIdxs = idxs.filter(function(idx){
return lastIdx <= idx;
});
nextIdxs.forEach(function(nextIdx){
var nextIdxPerm = idxPerm.slice(0);
nextIdxPerm.push(nextIdx);
nextIdxPerms.push(nextIdxPerm);
});
});
idxPerms = nextIdxPerms.slice(0);
}
perms = idxPerms.map(function(idxPerm){
return items.sliceByIndex(idxPerm);
});
return perms;
}
var ary = ["a","b","c","d"];
var combs = ary.combination(3);
console.log(combs);
// =>[ [ 'a', 'b', 'c' ],
// [ 'a', 'b', 'd' ],
// [ 'a', 'c', 'd' ],
// [ 'b', 'c', 'd' ] ]
var repeatedCombs = ary.repeatedCombination(3);
console.log(repeatedCombs);
// =>[ [ 'a', 'a', 'a' ], [ 'a', 'a', 'b' ], [ 'a', 'a', 'c' ], [ 'a', 'a', 'd' ],
// [ 'a', 'b', 'b' ], [ 'a', 'b', 'c' ], [ 'a', 'b', 'd' ], [ 'a', 'c', 'c' ],
// [ 'a', 'c', 'd' ], [ 'a', 'd', 'd' ], [ 'b', 'b', 'b' ], [ 'b', 'b', 'c' ],
// [ 'b', 'b', 'd' ], [ 'b', 'c', 'c' ], [ 'b', 'c', 'd' ], [ 'b', 'd', 'd' ],
// [ 'c', 'c', 'c' ], [ 'c', 'c', 'd' ], [ 'c', 'd', 'd' ], [ 'd', 'd', 'd' ] ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment