Compare commits

...

2 Commits

6 changed files with 124 additions and 0 deletions

View File

@@ -0,0 +1,8 @@
int greatest_common_divisor(int num1, int num2) {
while (num2 != 0) {
int temp = num2;
num2 = num1 % num2;
num1 = temp;
}
return num1;
}

46
trick/hash-structure.cpp Normal file
View File

@@ -0,0 +1,46 @@
#include <vector>
#include <tuple>
#include <unordered_set>
template<typename T>
struct VectorHash {
static void has_combine(size_t& seed, const T& v) {
seed ^= hash<T>{}(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
size_t operator() (const std::vector<T>& vec) const {
size_t seed = 0;
for (const T& v : vec) {
has_combine(seed, v);
}
return seed;
}
};
struct TupleHash {
template<typename T>
static void hash_combine(size_t& seed, const T& v) {
seed ^= hash<T>{}(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
template<typename Tuple, size_t Index = 0>
static void hash_tuple(size_t& seed, const Tuple& t) {
if constexpr (Index < tuple_size_v<Tuple>) {
hash_combine(seed, get<Index>(t));
hash_tuple<Tuple, Index + 1>(seed, t);
}
}
template<typename... Ts>
size_t operator()(const std::tuple<Ts...>& t) const {
size_t seed = 0;
hash_tuple(seed, t);
return seed;
}
};
int main() {
std::unordered_set<std::vector<int>, VectorHash<int>> hash_set1;
std::unordered_set<std::tuple<int, int, int>, TupleHash> hash_set2;
return 0;
}

View File

@@ -0,0 +1,29 @@
#include <vector>
#include <string>
int knuth_morris_pratt(const std::string text, const std::string pattern) {
int n = text.length(), m = pattern.length();
std::vector<int> next(m, 0);
for (int i = 1, j = 0; i < m; i++) {
while (j > 0 && pattern[i] != pattern[j]) {
j = next[j - 1];
}
if (pattern[i] == pattern[j]) {
j++;
}
next[i] = j;
}
for (int i = 0, j = 0; i < n; i++) {
while (j > 0 && text[i] != pattern[j]) {
j = next[j - 1];
}
if (text[i] == pattern[j]) {
j++;
}
if (j == m) {
return i - m + 1;
}
}
return -1;
}

View File

@@ -0,0 +1,17 @@
#include <vector>
bool primality_check(int n) {
std::vector<bool> is_prime(n + 1, true);
if (n <= 2) {
return false;
}
is_prime[0] = is_prime[1] = false;
for (int i = 2; i * i <= n; i++) {
if (is_prime[i]) {
for (int j = i * i; j <= n; j += i) {
is_prime[j] = false;
}
}
}
return is_prime[n];
}

View File

@@ -0,0 +1,11 @@
long long quick_pow(int base, int power) {
long long ans = 1;
while (power > 0) {
if (power & 1) {
ans *= base;
}
base *= base;
power >>= 1;
}
return ans;
}

13
trick/split-text.cpp Normal file
View File

@@ -0,0 +1,13 @@
#include <vector>
#include <string>
std::vector<std::string> split(std::string target, std::string pattern) {
std::vector<std::string> res;
size_t start = 0, next = 0;
while ((next = target.find(pattern, start)) != std::string::npos) {
res.push_back(target.substr(start, next - start));
start = next + pattern.length();
}
res.push_back(target.substr(start));
return res;
}