I am trying to write an algorithm that generates all lottery combinations recursively.
Here is a none recursive variation that can be used to get C(max,6). e.g. c(7,6)
let min = 1;
let max = 7;
let lotteryNum = 0;
let outputString = [];
for (let a = min; a <= max - 5; a++) {
for (let b = a + 1; b <= max - 4; b++) {
for (let c = b + 1; c <= max - 3; c++) {
for (let d = c + 1; d <= max - 2; d++) {
for (let e = d + 1; e <= max - 1; e++) {
for (let f = e + 1; f <= max; f++) {
lotteryNum++
outputString.push(format([a, b, c, d, e, f]) +
" <= " + lotteryNum + "\n");
}
}
}
}
}
}
function format(n) {
n.forEach((v, i) => {
n[i] = v < 10 ? '0' + v : '' + v;
});
return n.join(' ');
}
console.log(outputString.join(''));
outputs
01 02 03 04 05 06 <= 1
01 02 03 04 05 07 <= 2
01 02 03 04 06 07 <= 3
01 02 03 05 06 07 <= 4
01 02 04 05 06 07 <= 5
01 03 04 05 06 07 <= 6
02 03 04 05 06 07 <= 7
I tried writing a recursive algorithm so I could get C(max,length) as the above is hard-coded to C(max,6) and came up with the below, but I am not sure how to get the params needed to build the combination string as above.
function doRec(min, max, offset) {
if (offset >= 0) {
for (let a = min; a <= max - offset; a++) {
doRec(a + 1, max, offset - 1);
}
} else {
// how to create outputString params?
}
}
doRec(1, 7, 5);
Bonus question, is there a straight forward way to mathematically convert a lottery combination to an integer and vice versa as opposed to using the brute force method above?
e.g. from the output above
01 02 03 04 05 06 <=> this is lottery number 1
02 03 04 05 06 07 <=> this is lottery number 7
so something like getLotteryNumber('02 03 04 05 06 07') returns 7 in this case.