// You have a function rand7() that generates a random integer from 1 to 7. Use it to write a function rand5() that generates a random integer from 1 to 5.

extern int rand7(void);
int rand5(void) {
  static int randpool = 0;
  static int i = 0;
  int result;

  if (i == 0) { // assert(randpool == 0)
    // refill the entropy pool
    for (i = 0; i < 5; i++) randpool = randpool*7 + (rand7()-1);  // same packing as arithmetic encoding
    i = 7;
  }

  // 5 occurences of 0..6 are the same number of bits as 7 occurences of 0..4

  i -= 1; // extract 7 randoms from the entropy pool
  result = (randpool%5) + 1; // 1-based
  randpool = randpool/5;
  return result;
}
