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
def generate_combinations(array, r) | |
n = array.length | |
indices = (0...r).to_a | |
final = (n - r...n).to_a | |
while indices != final | |
yield indices.map {|k| array[k]} | |
i = r - 1 | |
while indices[i] == n - r + i | |
i -= 1 | |
end | |
indices[i] += 1 | |
(i + 1...r).each do |j| | |
indices[j] = indices[i] + j - i | |
end | |
end | |
yield indices.map {|k| array[k]} | |
end |
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
function generateCombinations(array, r, callback) { | |
function equal(a, b) { | |
for (var i = 0; i < a.length; i++) { | |
if (a[i] != b[i]) return false; | |
} | |
return true; | |
} | |
function values(i, a) { | |
var ret = []; | |
for (var j = 0; j < i.length; j++) ret.push(a[i[j]]); | |
return ret; | |
} | |
var n = array.length; | |
var indices = []; | |
for (var i = 0; i < r; i++) indices.push(i); | |
var final = []; | |
for (var i = n - r; i < n; i++) final.push(i); | |
while (!equal(indices, final)) { | |
callback(values(indices, array)); | |
var i = r - 1; | |
while (indices[i] == n - r + i) i -= 1; | |
indices[i] += 1; | |
for (var j = i + 1; j < r; j++) indices[j] = indices[i] + j - i; | |
} | |
callback(values(indices, array)); | |
} |
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
function generateCombinations(array, r, callback) { | |
var n = array.length; | |
var indices = $R(0, r, true).toArray(); | |
var final = $R(n - r, n, true).toArray(); | |
while (indices.all(function(v, k) {return final[k] == v;})) { | |
callback(indices.map(function(k) {return array[k];})); | |
var i = r - 1; | |
while (indices[i] == n - r + i) i -= 1; | |
indices[i] += 1; | |
for (var j = i + 1; j < r; j++) indices[j] = indices[i] + j - i; | |
} | |
callback(indices.map(function(k) {return array[k];})); | |
} |