I'm trying to program a poker calculator for myself and I have a for loop that goes 5 levels deep.
To do this I have nested for loops one right after the other. I'm looking for a way to simply use 1 loop (or function) that can just tell how many levels deep I want to go. For this example the answer is 5 but for other examples it may be a higher(much higher) number where this would be cumbersome. I think recursion is a way to do it I just don't know how to set it up(don't really understand recursion). Thank you for your help it's greatly appreciated.
for(var i=0; i < deck.length; i++){
for(var j=i+1; j<deck.length; j++){
for(var k=j+1; k<deck.length;k++){
for(var m=k+1; m<deck.length;m++){
for(var n=m+1; n<deck.length;n++){
combo = deck[i];
combo += deck[j];
combo += deck[k];
combo += deck[m];
combo += deck[n];
bighands.push(combo);
}
}
}
}
}
It works, I just want a better/more general way to do it.
You could take a recursive approach.
function getHands(array, size, right = []) {
return array.reduce((r, v, i, a) => {
var temp = [...right, v];
if (temp.length === size) {
r.push(temp.join(' '));
} else {
r.push(...getHands(a.slice(i + 1), size, temp));
}
return r;
}, []);
}
var deck = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
bighands = getHands(deck, 5);
console.log(bighands.length);
console.log(bighands);
.as-console-wrapper { max-height: 100% !important; top: 0; }