Algorithms / Generate repeated combinatorial
Posted On 12.25.2021
The algorithm is simple:
- Find the right most element less than n
- Increase it
- Set the other right the same
It can be implemented as following:
const next = (r) => {
let n = r.length;
for (let i = n - 1; i >= 0; i--) {
if (r[i] < n) {
r[i]++;
for (let j = i; j < n; j++) {
r[j] = r[i];
}
return r;
}
}
return null;
};
And here’s how we would use it:
let gen = next([0, 0, 0, 0]);
while (gen != null) {
console.log(gen);
gen = next(gen);
}