Created
November 27, 2012 16:02
-
-
Save raldred/4155079 to your computer and use it in GitHub Desktop.
Unique array combination generation
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
Compare.prototype.getCombinations = function(arr) { | |
var r = 2; | |
var pool = arr; | |
var n = pool.length; | |
if(r > n) { | |
return; | |
} | |
var indices = [0,1]; | |
var res = []; | |
var tmp = []; | |
for(var i = 0;i < indices.length;i++) { | |
tmp.push(pool[indices[i]]); | |
} | |
res.push(tmp); | |
(function() { | |
while(true) { | |
var reversed_ind = [1,0]; | |
var i; | |
for(i = 0;i<reversed_ind.length;i++) { | |
if(indices[reversed_ind[i]] != (reversed_ind[i] + n - r)) | |
break; | |
if(i==reversed_ind.length-1) { | |
return res; | |
} | |
} | |
indices[reversed_ind[i]] += 1; | |
var tmp = [0,1].slice(reversed_ind[i]+1,r); | |
for(var j = 0;j<tmp.length;j++) { | |
indices[tmp[j]] = indices[tmp[j]-1] + 1; | |
} | |
var tmp = []; | |
for(var x = 0; x < indices.length;x++) { | |
tmp.push(pool[indices[x]]); | |
} | |
res.push(tmp); | |
} | |
})(); | |
return res; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment