Last active
February 4, 2021 03:56
-
-
Save RojjaCebolla/a6ac4dc13b94a08c8ed08c9e040f51f5 to your computer and use it in GitHub Desktop.
Magical c++ snippets
This file contains 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
//discards all input in the standard input stream up to and including the first newline. | |
#include <limits> | |
cin.ignore(numeric_limits<streamsize>::max(), '\n'); | |
//This is a string of special characters that clears the terminal on both linux and windows. | |
cout << "\033[2J\033[1;1H"; | |
//This rolls a random number, but I'm not happy with it | |
//because it seems to segfault if it's passed a negative number | |
//for now, force anything less than 1 to become 1. | |
int rng(int number) { | |
if (number < 1) { | |
cout << endl << number << " is less than 1!!! (minor bug)\n"; | |
number = 1; | |
} | |
random_device dev; | |
mt19937 rng(dev()); | |
uniform_int_distribution<int> dist{1, number}; | |
// return true if the difference between a and b is extremely close, | |
// or within 0.1% percent of the larger of a and b | |
bool approximatelyEqualAbsRel(double a, double b, double absEpsilon = 1e-12, double relEpsilon = 0.001) | |
{ | |
// Check if the numbers are really close -- needed when comparing numbers near zero. | |
double diff{ std::abs(a - b) }; | |
if (diff <= absEpsilon) | |
return true; | |
// Otherwise fall back to Knuth's algorithm | |
return (diff <= (std::max(std::abs(a), std::abs(b)) * relEpsilon)); | |
} | |
return dist(rng); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment