Add the initial EN translation for C++ code (#1346)

This commit is contained in:
Yudong Jin
2024-05-06 13:31:46 +08:00
committed by GitHub
parent 9e4017b3fb
commit 8e60d12151
111 changed files with 6993 additions and 9 deletions

View File

@@ -0,0 +1,6 @@
add_executable(hash_map hash_map.cpp)
add_executable(array_hash_map_test array_hash_map_test.cpp)
add_executable(hash_map_chaining hash_map_chaining.cpp)
add_executable(hash_map_open_addressing hash_map_open_addressing.cpp)
add_executable(simple_hash simple_hash.cpp)
add_executable(built_in_hash built_in_hash.cpp)

View File

@@ -0,0 +1,110 @@
/**
* File: array_hash_map.cpp
* Created Time: 2022-12-14
* Author: msk397 (machangxinq@gmail.com)
*/
#include "../utils/common.hpp"
/* Key-value pair */
struct Pair {
public:
int key;
string val;
Pair(int key, string val) {
this->key = key;
this->val = val;
}
};
/* Hash table based on array implementation */
class ArrayHashMap {
private:
vector<Pair *> buckets;
public:
ArrayHashMap() {
// Initialize an array, containing 100 buckets
buckets = vector<Pair *>(100);
}
~ArrayHashMap() {
// Free memory
for (const auto &bucket : buckets) {
delete bucket;
}
buckets.clear();
}
/* Hash function */
int hashFunc(int key) {
int index = key % 100;
return index;
}
/* Query operation */
string get(int key) {
int index = hashFunc(key);
Pair *pair = buckets[index];
if (pair == nullptr)
return "";
return pair->val;
}
/* Add operation */
void put(int key, string val) {
Pair *pair = new Pair(key, val);
int index = hashFunc(key);
buckets[index] = pair;
}
/* Remove operation */
void remove(int key) {
int index = hashFunc(key);
// Free memory and set to nullptr
delete buckets[index];
buckets[index] = nullptr;
}
/* Get all key-value pairs */
vector<Pair *> pairSet() {
vector<Pair *> pairSet;
for (Pair *pair : buckets) {
if (pair != nullptr) {
pairSet.push_back(pair);
}
}
return pairSet;
}
/* Get all keys */
vector<int> keySet() {
vector<int> keySet;
for (Pair *pair : buckets) {
if (pair != nullptr) {
keySet.push_back(pair->key);
}
}
return keySet;
}
/* Get all values */
vector<string> valueSet() {
vector<string> valueSet;
for (Pair *pair : buckets) {
if (pair != nullptr) {
valueSet.push_back(pair->val);
}
}
return valueSet;
}
/* Print hash table */
void print() {
for (Pair *kv : pairSet()) {
cout << kv->key << " -> " << kv->val << endl;
}
}
};
// See test case in array_hash_map_test.cpp

View File

@@ -0,0 +1,52 @@
/**
* File: array_hash_map_test.cpp
* Created Time: 2022-12-14
* Author: msk397 (machangxinq@gmail.com)
*/
#include "./array_hash_map.cpp"
/* Driver Code */
int main() {
/* Initialize hash table */
ArrayHashMap map = ArrayHashMap();
/* Add operation */
// Add key-value pair (key, value) to the hash table
map.put(12836, "Ha");
map.put(15937, "Luo");
map.put(16750, "Suan");
map.put(13276, "Fa");
map.put(10583, "Ya");
cout << "\nAfter adding, the hash table is\nKey -> Value" << endl;
map.print();
/* Query operation */
// Enter key to the hash table, get value
string name = map.get(15937);
cout << "\nEnter student ID 15937, found name " << name << endl;
/* Remove operation */
// Remove key-value pair (key, value) from the hash table
map.remove(10583);
cout << "\nAfter removing 10583, the hash table is\nKey -> Value" << endl;
map.print();
/* Traverse hash table */
cout << "\nTraverse key-value pairs Key->Value" << endl;
for (auto kv : map.pairSet()) {
cout << kv->key << " -> " << kv->val << endl;
}
cout << "\nIndividually traverse keys Key" << endl;
for (auto key : map.keySet()) {
cout << key << endl;
}
cout << "\nIndividually traverse values Value" << endl;
for (auto val : map.valueSet()) {
cout << val << endl;
}
return 0;
}

View File

@@ -0,0 +1,29 @@
/**
* File: built_in_hash.cpp
* Created Time: 2023-06-21
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* Driver Code */
int main() {
int num = 3;
size_t hashNum = hash<int>()(num);
cout << "The hash value of integer " << num << " is " << hashNum << "\n";
bool bol = true;
size_t hashBol = hash<bool>()(bol);
cout << "The hash value of boolean " << bol << " is " << hashBol << "\n";
double dec = 3.14159;
size_t hashDec = hash<double>()(dec);
cout << "The hash value of decimal " << dec << " is " << hashDec << "\n";
string str = "Hello algorithm";
size_t hashStr = hash<string>()(str);
cout << "The hash value of string " << str << " is " << hashStr << "\n";
// In C++, the built-in std:hash() only provides hash values for basic data types
// Hash value calculation for arrays and objects must be implemented manually
}

View File

@@ -0,0 +1,46 @@
/**
* File: hash_map.cpp
* Created Time: 2022-12-14
* Author: msk397 (machangxinq@gmail.com)
*/
#include "../utils/common.hpp"
/* Driver Code */
int main() {
/* Initialize hash table */
unordered_map<int, string> map;
/* Add operation */
// Add key-value pair (key, value) to the hash table
map[12836] = "Ha";
map[15937] = "Luo";
map[16750] = "Suan";
map[13276] = "Fa";
map[10583] = "Ya";
cout << "\nAfter adding, the hash table is\nKey -> Value" << endl;
printHashMap(map);
/* Query operation */
// Enter key to the hash table, get value
string name = map[15937];
cout << "\nEnter student ID 15937, found name " << name << endl;
/* Remove operation */
// Remove key-value pair (key, value) from the hash table
map.erase(10583);
cout << "\nAfter removing 10583, the hash table is\nKey -> Value" << endl;
printHashMap(map);
/* Traverse hash table */
cout << "\nTraverse key-value pairs Key->Value" << endl;
for (auto kv : map) {
cout << kv.first << " -> " << kv.second << endl;
}
cout << "\nIterate through Key->Value using an iterator" << endl;
for (auto iter = map.begin(); iter != map.end(); iter++) {
cout << iter->first << "->" << iter->second << endl;
}
return 0;
}

View File

@@ -0,0 +1,150 @@
/**
* File: hash_map_chaining.cpp
* Created Time: 2023-06-13
* Author: krahets (krahets@163.com)
*/
#include "./array_hash_map.cpp"
/* Chained address hash table */
class HashMapChaining {
private:
int size; // Number of key-value pairs
int capacity; // Hash table capacity
double loadThres; // Load factor threshold for triggering expansion
int extendRatio; // Expansion multiplier
vector<vector<Pair *>> buckets; // Bucket array
public:
/* Constructor */
HashMapChaining() : size(0), capacity(4), loadThres(2.0 / 3.0), extendRatio(2) {
buckets.resize(capacity);
}
/* Destructor */
~HashMapChaining() {
for (auto &bucket : buckets) {
for (Pair *pair : bucket) {
// Free memory
delete pair;
}
}
}
/* Hash function */
int hashFunc(int key) {
return key % capacity;
}
/* Load factor */
double loadFactor() {
return (double)size / (double)capacity;
}
/* Query operation */
string get(int key) {
int index = hashFunc(key);
// Traverse the bucket, if the key is found, return the corresponding val
for (Pair *pair : buckets[index]) {
if (pair->key == key) {
return pair->val;
}
}
// If key not found, return an empty string
return "";
}
/* Add operation */
void put(int key, string val) {
// When the load factor exceeds the threshold, perform expansion
if (loadFactor() > loadThres) {
extend();
}
int index = hashFunc(key);
// Traverse the bucket, if the specified key is encountered, update the corresponding val and return
for (Pair *pair : buckets[index]) {
if (pair->key == key) {
pair->val = val;
return;
}
}
// If the key is not found, add the key-value pair to the end
buckets[index].push_back(new Pair(key, val));
size++;
}
/* Remove operation */
void remove(int key) {
int index = hashFunc(key);
auto &bucket = buckets[index];
// Traverse the bucket, remove the key-value pair from it
for (int i = 0; i < bucket.size(); i++) {
if (bucket[i]->key == key) {
Pair *tmp = bucket[i];
bucket.erase(bucket.begin() + i); // Remove key-value pair
delete tmp; // Free memory
size--;
return;
}
}
}
/* Extend hash table */
void extend() {
// Temporarily store the original hash table
vector<vector<Pair *>> bucketsTmp = buckets;
// Initialize the extended new hash table
capacity *= extendRatio;
buckets.clear();
buckets.resize(capacity);
size = 0;
// Move key-value pairs from the original hash table to the new hash table
for (auto &bucket : bucketsTmp) {
for (Pair *pair : bucket) {
put(pair->key, pair->val);
// Free memory
delete pair;
}
}
}
/* Print hash table */
void print() {
for (auto &bucket : buckets) {
cout << "[";
for (Pair *pair : bucket) {
cout << pair->key << " -> " << pair->val << ", ";
}
cout << "]\n";
}
}
};
/* Driver Code */
int main() {
/* Initialize hash table */
HashMapChaining map = HashMapChaining();
/* Add operation */
// Add key-value pair (key, value) to the hash table
map.put(12836, "Ha");
map.put(15937, "Luo");
map.put(16750, "Suan");
map.put(13276, "Fa");
map.put(10583, "Ya");
cout << "\nAfter adding, the hash table is\nKey -> Value" << endl;
map.print();
/* Query operation */
// Enter key to the hash table, get value
string name = map.get(13276);
cout << "\nEnter student ID 13276, found name " << name << endl;
/* Remove operation */
// Remove key-value pair (key, value) from the hash table
map.remove(12836);
cout << "\nAfter removing 12836, the hash table is\nKey -> Value" << endl;
map.print();
return 0;
}

View File

@@ -0,0 +1,171 @@
/**
* File: hash_map_open_addressing.cpp
* Created Time: 2023-06-13
* Author: krahets (krahets@163.com)
*/
#include "./array_hash_map.cpp"
/* Open addressing hash table */
class HashMapOpenAddressing {
private:
int size; // Number of key-value pairs
int capacity = 4; // Hash table capacity
const double loadThres = 2.0 / 3.0; // Load factor threshold for triggering expansion
const int extendRatio = 2; // Expansion multiplier
vector<Pair *> buckets; // Bucket array
Pair *TOMBSTONE = new Pair(-1, "-1"); // Removal mark
public:
/* Constructor */
HashMapOpenAddressing() : size(0), buckets(capacity, nullptr) {
}
/* Destructor */
~HashMapOpenAddressing() {
for (Pair *pair : buckets) {
if (pair != nullptr && pair != TOMBSTONE) {
delete pair;
}
}
delete TOMBSTONE;
}
/* Hash function */
int hashFunc(int key) {
return key % capacity;
}
/* Load factor */
double loadFactor() {
return (double)size / capacity;
}
/* Search for the bucket index corresponding to key */
int findBucket(int key) {
int index = hashFunc(key);
int firstTombstone = -1;
// Linear probing, break when encountering an empty bucket
while (buckets[index] != nullptr) {
// If the key is encountered, return the corresponding bucket index
if (buckets[index]->key == key) {
// If a removal mark was encountered earlier, move the key-value pair to that index
if (firstTombstone != -1) {
buckets[firstTombstone] = buckets[index];
buckets[index] = TOMBSTONE;
return firstTombstone; // Return the moved bucket index
}
return index; // Return bucket index
}
// Record the first encountered removal mark
if (firstTombstone == -1 && buckets[index] == TOMBSTONE) {
firstTombstone = index;
}
// Calculate the bucket index, return to the head if exceeding the tail
index = (index + 1) % capacity;
}
// If the key does not exist, return the index of the insertion point
return firstTombstone == -1 ? index : firstTombstone;
}
/* Query operation */
string get(int key) {
// Search for the bucket index corresponding to key
int index = findBucket(key);
// If the key-value pair is found, return the corresponding val
if (buckets[index] != nullptr && buckets[index] != TOMBSTONE) {
return buckets[index]->val;
}
// If key-value pair does not exist, return an empty string
return "";
}
/* Add operation */
void put(int key, string val) {
// When the load factor exceeds the threshold, perform expansion
if (loadFactor() > loadThres) {
extend();
}
// Search for the bucket index corresponding to key
int index = findBucket(key);
// If the key-value pair is found, overwrite val and return
if (buckets[index] != nullptr && buckets[index] != TOMBSTONE) {
buckets[index]->val = val;
return;
}
// If the key-value pair does not exist, add the key-value pair
buckets[index] = new Pair(key, val);
size++;
}
/* Remove operation */
void remove(int key) {
// Search for the bucket index corresponding to key
int index = findBucket(key);
// If the key-value pair is found, cover it with a removal mark
if (buckets[index] != nullptr && buckets[index] != TOMBSTONE) {
delete buckets[index];
buckets[index] = TOMBSTONE;
size--;
}
}
/* Extend hash table */
void extend() {
// Temporarily store the original hash table
vector<Pair *> bucketsTmp = buckets;
// Initialize the extended new hash table
capacity *= extendRatio;
buckets = vector<Pair *>(capacity, nullptr);
size = 0;
// Move key-value pairs from the original hash table to the new hash table
for (Pair *pair : bucketsTmp) {
if (pair != nullptr && pair != TOMBSTONE) {
put(pair->key, pair->val);
delete pair;
}
}
}
/* Print hash table */
void print() {
for (Pair *pair : buckets) {
if (pair == nullptr) {
cout << "nullptr" << endl;
} else if (pair == TOMBSTONE) {
cout << "TOMBSTONE" << endl;
} else {
cout << pair->key << " -> " << pair->val << endl;
}
}
}
};
/* Driver Code */
int main() {
// Initialize hash table
HashMapOpenAddressing hashmap;
// Add operation
// Add key-value pair (key, val) to the hash table
hashmap.put(12836, "Ha");
hashmap.put(15937, "Luo");
hashmap.put(16750, "Suan");
hashmap.put(13276, "Fa");
hashmap.put(10583, "Ya");
cout << "\nAfter adding, the hash table is\nKey -> Value" << endl;
hashmap.print();
// Query operation
// Enter key to the hash table, get value val
string name = hashmap.get(13276);
cout << "\nEnter student ID 13276, found name " << name << endl;
// Remove operation
// Remove key-value pair (key, val) from the hash table
hashmap.remove(16750);
cout << "\nAfter removing 16750, the hash table is\nKey -> Value" << endl;
hashmap.print();
return 0;
}

View File

@@ -0,0 +1,66 @@
/**
* File: simple_hash.cpp
* Created Time: 2023-06-21
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* Additive hash */
int addHash(string key) {
long long hash = 0;
const int MODULUS = 1000000007;
for (unsigned char c : key) {
hash = (hash + (int)c) % MODULUS;
}
return (int)hash;
}
/* Multiplicative hash */
int mulHash(string key) {
long long hash = 0;
const int MODULUS = 1000000007;
for (unsigned char c : key) {
hash = (31 * hash + (int)c) % MODULUS;
}
return (int)hash;
}
/* XOR hash */
int xorHash(string key) {
int hash = 0;
const int MODULUS = 1000000007;
for (unsigned char c : key) {
hash ^= (int)c;
}
return hash & MODULUS;
}
/* Rotational hash */
int rotHash(string key) {
long long hash = 0;
const int MODULUS = 1000000007;
for (unsigned char c : key) {
hash = ((hash << 4) ^ (hash >> 28) ^ (int)c) % MODULUS;
}
return (int)hash;
}
/* Driver Code */
int main() {
string key = "Hello algorithm";
int hash = addHash(key);
cout << "Additive hash value is " << hash << endl;
hash = mulHash(key);
cout << "Multiplicative hash value is " << hash << endl;
hash = xorHash(key);
cout << "XOR hash value is " << hash << endl;
hash = rotHash(key);
cout << "Rotational hash value is " << hash << endl;
return 0;
}