Skip to content

Instantly share code, notes, and snippets.

@grumpitect
Last active August 17, 2021 10:13
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 grumpitect/63880cb5bcc41f0b3783bb75161508c7 to your computer and use it in GitHub Desktop.
Save grumpitect/63880cb5bcc41f0b3783bb75161508c7 to your computer and use it in GitHub Desktop.
non recursive k-combination
const N = 7;
const M = 4;
const positions = [];
for (let i = 0; i < M; i += 1) {
positions.push(i);
}
const set = [];
for (let i = 0; i < N; i += 1) {
set[i] = i + 1;
}
let hasChange = false;
do {
const result = positions.map(p => set[p]);
console.log(result);
// This code works like a calculator
// it tries to increment the latest positional value, if it succeeds,
// then it resets all the remaining positions to be in sequential order.
// if it fails to increment a position it will try to increment the previous position and so on.
hasChange = false;
for (let i = M - 1; i >= 0; i -= 1) {
if (positions[i] - i + M < N) {
positions[i] += 1;
hasChange = true;
for (let j = i + 1; j < M; j += 1) {
positions[j] = positions[j - 1] + 1;
}
break;
}
}
} while(hasChange);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment