2

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.

JWits87
  • 31
  • 3

2 Answers2

2

Using generators this can be achieved quite elegantly:

  function* loop(depth, start, times, prev = []) {
    if(depth <= 0) {
      yield prev;
     return;
    }

    for(let current = start; current < times; current++) {
      yield* loop(depth - 1, current + 1, times, [...prev, current]);
    }
  }

Usable as:

  for(const [j, k, l, m] of loop(4, /*times from*/ 0, /* till*/ 5)) {
    //...
  }

The above will iterate the same way your for loops do, for sure you can do much more with generators, for example directly generating the combos:

  const identity = _ => _;

  function* take(n, of, mapper = identity, prev = []) {
    if(!of.length) return;

    if(prev.length >= n) {
       yield mapper(prev);
       return;
    }

    for(let i = 0; i < of.length; i++) {
       yield* take(n, of slice(i + 1), mapper, [...prev, of[i]]);
    }
 }

 for(const combo of take(4, /*of*/ deck, it => it.reduce((a, b) => a + b))) {
   //...
 }

Or if you directly need an array

 function toArray(iterator) {
    let result = [], value;
    while(!({ value } = iterator.next()).done) result.push(value);
    return result;
 }

 const combos = toArray(take(4, /*of*/ deck, it => it.reduce((a, b) => a + b)));
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392