Created
July 10, 2020 10:00
-
-
Save Lakhan-Nad/c4c081e1ff66b3495ad01a453407e8d2 to your computer and use it in GitHub Desktop.
Based and inspired by 3Blue1Brown's Pi Collisions Video.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Includes | |
| #include <iostream> | |
| class Box { | |
| private: | |
| long double x, v, m, w; | |
| public: | |
| Box(long double wx, long double mx) { | |
| w = wx; | |
| m = mx; | |
| }; | |
| Box() = default; | |
| Box(Box &b) = default; | |
| Box(Box &&b) = default; | |
| void place(long double xx) { x = xx; } | |
| void setVel(long double vx) { v = vx; } | |
| void move() { x += v; } | |
| void reverse() { v *= -1; } | |
| bool hitByLeftWall(long double xx) { return (x <= xx); } | |
| bool hitByRightWall(long double xx) { return (x + w >= xx); } | |
| bool collideByLeft(const Box &b) { return !(x + w < b.x); } | |
| bool collideByRight(const Box &b) { return !(x > b.x + b.w); } | |
| bool impossible(const Box &b) { return (v > 0 && b.v > 0 && b.v > v); } | |
| friend void bounce(Box &, Box &); | |
| }; | |
| void bounce(Box &a, Box &b) { | |
| long double v1 = a.v; | |
| long double v2 = b.v; | |
| long double sum = a.m + b.m; | |
| b.v = (2 * a.m * v1 + (b.m - a.m) * v2) / sum; | |
| a.v = (2 * b.m * v2 + (a.m - b.m) * v1) / sum; | |
| } | |
| long double powTimesTen(int x) { | |
| long double res = 1.00; | |
| long double p = 10.00; | |
| while (x > 0) { | |
| if (x & 1) { | |
| res *= p; | |
| } | |
| p *= p; | |
| x /= 2; | |
| } | |
| return res; | |
| } | |
| long double powByTen(int x) { | |
| long double res = 1.00; | |
| long double p = 10.00; | |
| while (x > 0) { | |
| if (x & 1) { | |
| res /= p; | |
| } | |
| p *= p; | |
| x /= 2; | |
| } | |
| return res; | |
| } | |
| int main() { | |
| const long double leftWall = 0; | |
| const long double rightWall = 1e18; | |
| long long count = 0; | |
| int times; | |
| // digits | |
| std::cin >> times; | |
| Box block1 = Box(10.00, powByTen(times)); | |
| Box block2 = Box(10.00, powTimesTen(times)); | |
| block1.place(20.00); | |
| block1.setVel(0.00); | |
| block2.place(40.00); | |
| block2.setVel(-1.00 * powByTen(times)); | |
| while (!block1.impossible(block2)) { | |
| block1.move(); | |
| block2.move(); | |
| if (block1.collideByLeft(block2)) { | |
| bounce(block1, block2); | |
| count++; | |
| } | |
| if (block1.hitByLeftWall(leftWall)) { | |
| block1.reverse(); | |
| count++; | |
| } | |
| } | |
| std::cout << count; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment