freeCodeCamp Challenge Guide: Problem 199: Iterative Circle Packing

Problem 199: Iterative Circle Packing


Problem Explanation

  • Placing three circles that are the same size and as big as they can be without overlapping inside a bigger circle leaves four gaps
  • The first iteration of adding more circles, puts another maximum sized circle in each gap
  • Each iteration after that fills the gaps left over with another maximum sized circle
  • In this challenge you need to find the area not filled after n iterations

Solutions

Solution 1 (Click to Show/Hide)
function iterativeCirclePacking(n) {
  let k1 = 1;
  let k0 = k1 * (3 - 2 * Math.sqrt(3));
  let a0 = 1 / (k0 * k0);
  let a1 = 3 / (k1 * k1);
  a1 += 3 * getArea(k0, k1, k1, n);
  a1 += getArea(k1, k1, k1, n);
  let final = ((a0 - a1) / a0).toFixed(8);
  
  return parseFloat(final);
  function getArea(k1, k2, k3, depth) {
      if (depth == 0) return 0.0;
      let k4 = k1 + k2 + k3 + 2 * Math.sqrt(k1 * k2 + k2 * k3 + k3 * k1);
      let a = 1 / (k4 * k4);
      a += getArea(k1, k2, k4, depth - 1);
      a += getArea(k2, k3, k4, depth - 1);
      a += getArea(k3, k1, k4, depth - 1);
      return a;
  }
}