Skip to content

Commit

Permalink
add main
Browse files Browse the repository at this point in the history
  • Loading branch information
archibate committed Jan 1, 2022
1 parent 8843408 commit 73bd8c2
Show file tree
Hide file tree
Showing 2 changed files with 93 additions and 26 deletions.
25 changes: 5 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,27 +16,12 @@

## 评分规则

- 完成作业基本要求 50 分(详见下方"作业要求")
- 能够在 PR 描述中用自己的话解释 25 分
- 代码格式规范、能够跨平台 5 分
- 有自己独特的创新点 20 分
- 明显抄袭现象 -100 分
- 加速了多少倍,就是多少分!

## 作业要求

修改 main.cpp,改良其中的双链表类 `List`
修改 main.cpp,改良其中的多体引力求解器

- 避免函数参数不必要的拷贝 5 分
- 修复智能指针造成的问题 10 分
- 改用 `unique_ptr<Node>` 10 分
- 实现拷贝构造函数为深拷贝 15 分
- 说明为什么可以删除拷贝赋值函数 5 分
- 改进 `Node` 的构造函数 5 分

并通过 `main()` 函数中的基本测试。

## 关于内卷

如果你把 List 改成了基于迭代器的,或是作为模板 `List<int>`
只要是在 **满足作业要求的基础** 上,这是件好事!
老师会酌情加分,视为“独特的创新点”,但最多不超过 20 分。
- 不得使用多线程
- 不得做算法复杂度优化
- 可以针对编译器和平台优化,这次不必跨平台
94 changes: 88 additions & 6 deletions main.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,88 @@
#include <cstdio>

int main() {
printf("Hello, world!\n");
return 0;
}
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <chrono>
#include <cmath>

float frand() {
return (float)rand() / RAND_MAX * 2 - 1;
}

struct Star {
float px, py, pz;
float vx, vy, vz;
float mass;
};

std::vector<Star> stars;

void init() {
for (int i = 0; i < 48; i++) {
stars.push_back({
frand(), frand(), frand(),
frand(), frand(), frand(),
frand() + 1,
});
}
}

float G = 0.001;
float eps = 0.001;
float dt = 0.01;

void step() {
for (auto &star: stars) {
for (auto &other: stars) {
float dx = other.px - star.px;
float dy = other.py - star.py;
float dz = other.pz - star.pz;
float d2 = dx * dx + dy * dy + dz * dz + eps * eps;
d2 *= sqrt(d2);
star.vx += dx * other.mass * G * dt / d2;
star.vy += dy * other.mass * G * dt / d2;
star.vz += dz * other.mass * G * dt / d2;
}
}
for (auto &star: stars) {
star.px += star.vx * dt;
star.py += star.vy * dt;
star.pz += star.vz * dt;
}
}

float calc() {
float energy = 0;
for (auto &star: stars) {
float v2 = star.vx * star.vx + star.vy * star.vy + star.vz * star.vz;
energy += star.mass * v2 / 2;
for (auto &other: stars) {
float dx = other.px - star.px;
float dy = other.py - star.py;
float dz = other.pz - star.pz;
float d2 = dx * dx + dy * dy + dz * dz + eps * eps;
energy -= other.mass * star.mass * G / sqrt(d2) / 2;
}
}
return energy;
}

template <class Func>
long benchmark(Func const &func) {
auto t0 = std::chrono::steady_clock::now();
func();
auto t1 = std::chrono::steady_clock::now();
auto dt = std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0);
return dt.count();
}

int main() {
init();
printf("Initial energy: %f\n", calc());
auto dt = benchmark([&] {
for (int i = 0; i < 100000; i++)
step();
});
printf("Final energy: %f\n", calc());
printf("Time elapsed: %ld ms\n", dt);
return 0;
}

0 comments on commit 73bd8c2

Please sign in to comment.