Last active
August 17, 2021 10:13
-
-
Save grumpitect/63880cb5bcc41f0b3783bb75161508c7 to your computer and use it in GitHub Desktop.
non recursive k-combination
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
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