高级农民
- 积分
- 2724
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2017-6-18
- 最后登录
- 1970-1-1
|
第一题是打印一个分形(fractal),分形具有递归结构,当前n的某个坐标上的字符可以由n - 1子分形的某个对应字符平移(复杂的还可以旋转拉伸——也就是affine transform)得到。
. .и
写了一份参考代码:
- #include <iostream>
- #include <memory>
- . .и
- class Shape {
- public:
- virtual ~Shape() {} ..
- virtual int GetNumRows() const = 0; ..
- virtual int GetNumCols() const = 0;
- virtual char GetCell(int row, int col) const = 0;
- static std::unique_ptr<Shape> Create(int degree);
- };
- // 最基础的三角形
- class BaseTriangle : public Shape {
- public:
- int GetNumRows() const override { return 2; }-baidu 1point3acres
- int GetNumCols() const override { return 4; }
- . 1point3acres.com
- char GetCell(int row, int col) const override {. 1point 3acres
- constexpr char kShape[2][4] = {. Χ
- {' ', '/', '\\', ' ' }, {'/', '_', '_', '\\' }};.google и
- return kShape[row][col];
- }
- };
- // 否则是一个递归分形,某个位置的字符可以依靠平移坐标再通过子分形计算
- class TriangleFractal : public Shape {
- public:
- TriangleFractal(int degree)
- : sub_fractal_(Shape::Create(degree - 1)),
- half_num_rows_(sub_fractal_->GetNumRows()),
- half_num_cols_(sub_fractal_->GetNumCols()),
- half_half_num_cols_(half_num_cols_ / 2),
- num_rows_(half_num_rows_ * 2),.--
- num_cols_(half_num_cols_ * 2) {}
- int GetNumRows() const override { return num_rows_; }
- int GetNumCols() const override { return num_cols_; }
- char GetCell(int row, int col) const override {
- // 上面部分
- if (row < half_num_rows_) {
- if (col >= half_half_num_cols_ &&
- col < half_num_cols_ + half_half_num_cols_) {
- return sub_fractal_->GetCell(row, col - half_half_num_cols_);
- }
- return ' ';
- }
- // 左下部分
- if (col < half_num_cols_) {
- return sub_fractal_->GetCell(row - half_num_rows_, col);
- }
- // 右下部分
- return sub_fractal_->GetCell(row - half_num_rows_, col - half_num_cols_); ..
- }
- private:
- const std::unique_ptr<Shape> sub_fractal_;
- const int half_num_rows_;
- const int half_num_cols_;
- const int half_half_num_cols_;
- const int num_rows_;
- const int num_cols_;.--
- };
- std::unique_ptr<Shape> Shape::Create(int degree) {
- // 要求degree大于等于1,这里就不做check了
- if (degree == 1) {
- return std::make_unique<BaseTriangle>();
- }
- return std::make_unique<TriangleFractal>(degree);
- } ..
- void PrintShape(int degree) {.1point3acres
- std::unique_ptr<Shape> shape = Shape::Create(degree);
- for (int i = 0; i < shape->GetNumRows(); ++i) {
- for (int j = 0; j < shape->GetNumCols(); ++j) {
- std::cout << shape->GetCell(i, j);
- }
- std::cout << "\n";
- }.google и
- }. 1point3acres
- . Waral dи,
- int main(int argc, char* argv[]) {.google и
- for (int n = 1; n < 5; ++n) {
- std::cout << "n = " << n << "\n";
- PrintShape(n);. 1point 3 acres
- std::cout << "\n";.google и
- }
- return 0;
- }. ----
复制代码 |
|