6.3 コッホ曲線

なかなか再帰脳になれず。。なお座標計算は本書を参照しました。プログラミングコンテストって、ここまで数学の知識を問われるんですかね?

#include <iostream>
#include <vector>
#include <cmath>

using namespace std;

struct P {
  double x;
  double y;
  P(double x, double y) : x(x) , y(y) {
  };
};

static inline void printP(const P& p) {
  cout << fixed << p.x << " " << p.y << endl; 
}

static inline double toRadian(double degree) {
  return degree / 180 * M_PI;
}

static inline void koch(int d, const P& p1, const P& p2) {
  if (d == 0) {
    return;
  }
  
  P s(p1.x + (p2.x - p1.x) / 3, p1.y + (p2.y - p1.y) / 3);
  P t(p1.x + 2 * ((p2.x - p1.x) / 3), p1.y + 2 * ((p2.y - p1.y) / 3));
  P u(
    (t.x - s.x) * cos(toRadian(60.0)) - (t.y - s.y) * sin(toRadian(60.0)) + s.x,
    (t.x - s.x) * sin(toRadian(60.0)) + (t.y - s.y) * cos(toRadian(60.0)) + s.y);
 
  koch(d - 1, p1, s);
  printP(s);
  koch(d - 1, s, u);
  printP(u);
  koch(d - 1, u, t);
  printP(t);
  koch(d - 1, t, p2);
}

int main() {
  int n;
  cin >> n;

  P p1(0.0, 0.0), p2(100.0, 0);

  printP(p1);
  koch(n, p1, p2);
  printP(p2);
  
  return 0;
}