Appendix: Hexagram Divination Code

Backend code that simulates the manual yarrow stalk divination process

function divideStalks(stalks: number) {
  const left = Math.floor(Math.random() * (stalks - 1)) + 1;
  const right = stalks - left;
  return [left, right];
}

function countByFours(pile: number) {
  return pile % 4 === 0 ? 4 : pile % 4;
}

function yarrowStalkLine() {
  let stalks = 49; // Start with 49 stalks (one set aside)

  // First division
  let [left, right] = divideStalks(stalks);
  right -= 1; // Take one from right pile
  const sum1 = countByFours(left) + countByFours(right) + 1;

  let remaining = stalks - sum1;

  // Second division
  [left, right] = divideStalks(remaining);
  const sum2 = countByFours(left) + countByFours(right);

  remaining = remaining - sum2;

  // Third division
  [left, right] = divideStalks(remaining);
  const sum3 = countByFours(left) + countByFours(right);

  const total = sum1 + sum2 + sum3;

  if (total === 25) {
      return 6; // Old Yin
  } else if (total === 21) {
      return 7; // Young Yang
  } else if (total === 17) {
      return 8; // Young Yin
  } else { // total === 13
      return 9; // Old Yang
  }
}

export function castHexagram() {
  return Array(6).fill(null).map(() => yarrowStalkLine());
}
  1. divideStalks(stalks): Simulates dividing the stalks into two random piles.

  2. countByFours(pile): Simulates counting out stalks in groups of four and returning the remainder.

  3. yarrowStalkLine(): Performs the entire process for generating one line:

    • Does the first division, setting aside one stalk.

    • Performs the second and third divisions.

    • Calculates the total and returns the appropriate line value.

  4. castHexagram(): Calls yarrowStalkLine() six times to generate a complete hexagram.

This implementation closely replicates the traditional yarrow stalk method, including:

  • Starting with 49 stalks

  • Performing three divisions for each line

  • Calculating the results based on the sums of these divisions

The probabilities generated by this method will match those of the traditional yarrow stalk method:

  • 6 (Old Yin): 1/16 chance

  • 7 (Young Yang): 5/16 chance

  • 8 (Young Yin): 7/16 chance

  • 9 (Old Yang): 3/16 chance

Last updated