mirror of
https://github.com/krahets/hello-algo.git
synced 2026-08-25 01:27:13 +00:00
Add ru version (#1865)
* Add Russian docs site baseline * Add Russian localized codebase * Polish Russian code wording * Update ru code translation. * Update code translation and chapter covers. * Fix pythontutor extraction. * Add README and landing page. * placeholder of profiles * Use figures of English version * Remove chapter paperbook
This commit is contained in:
@@ -0,0 +1,4 @@
|
||||
add_executable(array_hash_map array_hash_map.c)
|
||||
add_executable(hash_map_chaining hash_map_chaining.c)
|
||||
add_executable(hash_map_open_addressing hash_map_open_addressing.c)
|
||||
add_executable(simple_hash simple_hash.c)
|
||||
@@ -0,0 +1,215 @@
|
||||
/**
|
||||
* File: array_hash_map.c
|
||||
* Created Time: 2023-03-18
|
||||
* Author: Guanngxu (446678850@qq.com)
|
||||
*/
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
/* Размер хеш-таблицы по умолчанию */
|
||||
#define MAX_SIZE 100
|
||||
|
||||
/* Пара ключ-значение int->string */
|
||||
typedef struct {
|
||||
int key;
|
||||
char *val;
|
||||
} Pair;
|
||||
|
||||
/* Набор пар ключ-значение */
|
||||
typedef struct {
|
||||
void *set;
|
||||
int len;
|
||||
} MapSet;
|
||||
|
||||
/* Хеш-таблица на основе массива */
|
||||
typedef struct {
|
||||
Pair *buckets[MAX_SIZE];
|
||||
} ArrayHashMap;
|
||||
|
||||
/* Конструктор */
|
||||
ArrayHashMap *newArrayHashMap() {
|
||||
ArrayHashMap *hmap = malloc(sizeof(ArrayHashMap));
|
||||
for (int i=0; i < MAX_SIZE; i++) {
|
||||
hmap->buckets[i] = NULL;
|
||||
}
|
||||
return hmap;
|
||||
}
|
||||
|
||||
/* Деструктор */
|
||||
void delArrayHashMap(ArrayHashMap *hmap) {
|
||||
for (int i = 0; i < MAX_SIZE; i++) {
|
||||
if (hmap->buckets[i] != NULL) {
|
||||
free(hmap->buckets[i]->val);
|
||||
free(hmap->buckets[i]);
|
||||
}
|
||||
}
|
||||
free(hmap);
|
||||
}
|
||||
|
||||
/* Хеш-функция */
|
||||
int hashFunc(int key) {
|
||||
int index = key % MAX_SIZE;
|
||||
return index;
|
||||
}
|
||||
|
||||
/* Операция поиска */
|
||||
const char *get(const ArrayHashMap *hmap, const int key) {
|
||||
int index = hashFunc(key);
|
||||
const Pair *Pair = hmap->buckets[index];
|
||||
if (Pair == NULL)
|
||||
return NULL;
|
||||
return Pair->val;
|
||||
}
|
||||
|
||||
/* Операция добавления */
|
||||
void put(ArrayHashMap *hmap, const int key, const char *val) {
|
||||
Pair *Pair = malloc(sizeof(Pair));
|
||||
Pair->key = key;
|
||||
Pair->val = malloc(strlen(val) + 1);
|
||||
strcpy(Pair->val, val);
|
||||
|
||||
int index = hashFunc(key);
|
||||
hmap->buckets[index] = Pair;
|
||||
}
|
||||
|
||||
/* Операция удаления */
|
||||
void removeItem(ArrayHashMap *hmap, const int key) {
|
||||
int index = hashFunc(key);
|
||||
free(hmap->buckets[index]->val);
|
||||
free(hmap->buckets[index]);
|
||||
hmap->buckets[index] = NULL;
|
||||
}
|
||||
|
||||
/* Получить все пары ключ-значение */
|
||||
void pairSet(ArrayHashMap *hmap, MapSet *set) {
|
||||
Pair *entries;
|
||||
int i = 0, index = 0;
|
||||
int total = 0;
|
||||
/* Подсчитать число действительных пар ключ-значение */
|
||||
for (i = 0; i < MAX_SIZE; i++) {
|
||||
if (hmap->buckets[i] != NULL) {
|
||||
total++;
|
||||
}
|
||||
}
|
||||
entries = malloc(sizeof(Pair) * total);
|
||||
for (i = 0; i < MAX_SIZE; i++) {
|
||||
if (hmap->buckets[i] != NULL) {
|
||||
entries[index].key = hmap->buckets[i]->key;
|
||||
entries[index].val = malloc(strlen(hmap->buckets[i]->val) + 1);
|
||||
strcpy(entries[index].val, hmap->buckets[i]->val);
|
||||
index++;
|
||||
}
|
||||
}
|
||||
set->set = entries;
|
||||
set->len = total;
|
||||
}
|
||||
|
||||
/* Получить все ключи */
|
||||
void keySet(ArrayHashMap *hmap, MapSet *set) {
|
||||
int *keys;
|
||||
int i = 0, index = 0;
|
||||
int total = 0;
|
||||
/* Подсчитать число действительных пар ключ-значение */
|
||||
for (i = 0; i < MAX_SIZE; i++) {
|
||||
if (hmap->buckets[i] != NULL) {
|
||||
total++;
|
||||
}
|
||||
}
|
||||
keys = malloc(total * sizeof(int));
|
||||
for (i = 0; i < MAX_SIZE; i++) {
|
||||
if (hmap->buckets[i] != NULL) {
|
||||
keys[index] = hmap->buckets[i]->key;
|
||||
index++;
|
||||
}
|
||||
}
|
||||
set->set = keys;
|
||||
set->len = total;
|
||||
}
|
||||
|
||||
/* Получить все значения */
|
||||
void valueSet(ArrayHashMap *hmap, MapSet *set) {
|
||||
char **vals;
|
||||
int i = 0, index = 0;
|
||||
int total = 0;
|
||||
/* Подсчитать число действительных пар ключ-значение */
|
||||
for (i = 0; i < MAX_SIZE; i++) {
|
||||
if (hmap->buckets[i] != NULL) {
|
||||
total++;
|
||||
}
|
||||
}
|
||||
vals = malloc(total * sizeof(char *));
|
||||
for (i = 0; i < MAX_SIZE; i++) {
|
||||
if (hmap->buckets[i] != NULL) {
|
||||
vals[index] = hmap->buckets[i]->val;
|
||||
index++;
|
||||
}
|
||||
}
|
||||
set->set = vals;
|
||||
set->len = total;
|
||||
}
|
||||
|
||||
/* Вывести хеш-таблицу */
|
||||
void print(ArrayHashMap *hmap) {
|
||||
int i;
|
||||
MapSet set;
|
||||
pairSet(hmap, &set);
|
||||
Pair *entries = (Pair *)set.set;
|
||||
for (i = 0; i < set.len; i++) {
|
||||
printf("%d -> %s\n", entries[i].key, entries[i].val);
|
||||
}
|
||||
free(set.set);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
/* Инициализация хеш-таблицы */
|
||||
ArrayHashMap *hmap = newArrayHashMap();
|
||||
|
||||
/* Операция добавления */
|
||||
// Добавить пару (key, value) в хеш-таблицу
|
||||
put(hmap, 12836, "Сяо Ха");
|
||||
put(hmap, 15937, "Сяо Ло");
|
||||
put(hmap, 16750, "Сяо Суань");
|
||||
put(hmap, 13276, "Сяо Фа");
|
||||
put(hmap, 10583, "Сяо Я");
|
||||
printf("\nПосле добавления хеш-таблица имеет вид\nКлюч -> Значение\n");
|
||||
print(hmap);
|
||||
|
||||
/* Операция поиска */
|
||||
// Ввести в хеш-таблицу ключ key и получить значение value
|
||||
const char *name = get(hmap, 15937);
|
||||
printf("\nДля студенческого номера 15937 найдено имя %s\n", name);
|
||||
|
||||
/* Операция удаления */
|
||||
// Удалить пару (key, value) из хеш-таблицы
|
||||
removeItem(hmap, 10583);
|
||||
printf("\nПосле удаления 10583 хеш-таблица имеет вид\nКлюч -> Значение\n");
|
||||
print(hmap);
|
||||
|
||||
/* Обход хеш-таблицы */
|
||||
int i;
|
||||
|
||||
printf("\nОтдельный обход пар ключ-значение\n");
|
||||
print(hmap);
|
||||
|
||||
MapSet set;
|
||||
|
||||
keySet(hmap, &set);
|
||||
int *keys = (int *)set.set;
|
||||
printf("\nОтдельный обход ключей\n");
|
||||
for (i = 0; i < set.len; i++) {
|
||||
printf("%d\n", keys[i]);
|
||||
}
|
||||
free(set.set);
|
||||
|
||||
valueSet(hmap, &set);
|
||||
char **vals = (char **)set.set;
|
||||
printf("\nОбход только значений Value\n");
|
||||
for (i = 0; i < set.len; i++) {
|
||||
printf("%s\n", vals[i]);
|
||||
}
|
||||
free(set.set);
|
||||
|
||||
delArrayHashMap(hmap);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
/**
|
||||
* File: hash_map_chaining.c
|
||||
* Created Time: 2023-10-13
|
||||
* Author: SenMing (1206575349@qq.com), krahets (krahets@163.com)
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
// Предположить, что максимальная длина val равна 100
|
||||
#define MAX_SIZE 100
|
||||
|
||||
/* Пара ключ-значение */
|
||||
typedef struct {
|
||||
int key;
|
||||
char val[MAX_SIZE];
|
||||
} Pair;
|
||||
|
||||
/* Узел связного списка */
|
||||
typedef struct Node {
|
||||
Pair *pair;
|
||||
struct Node *next;
|
||||
} Node;
|
||||
|
||||
/* Хеш-таблица с цепочками */
|
||||
typedef struct {
|
||||
int size; // Число пар ключ-значение
|
||||
int capacity; // Вместимость хеш-таблицы
|
||||
double loadThres; // Порог коэффициента загрузки для запуска расширения
|
||||
int extendRatio; // Коэффициент расширения
|
||||
Node **buckets; // Массив корзин
|
||||
} HashMapChaining;
|
||||
|
||||
/* Конструктор */
|
||||
HashMapChaining *newHashMapChaining() {
|
||||
HashMapChaining *hashMap = (HashMapChaining *)malloc(sizeof(HashMapChaining));
|
||||
hashMap->size = 0;
|
||||
hashMap->capacity = 4;
|
||||
hashMap->loadThres = 2.0 / 3.0;
|
||||
hashMap->extendRatio = 2;
|
||||
hashMap->buckets = (Node **)malloc(hashMap->capacity * sizeof(Node *));
|
||||
for (int i = 0; i < hashMap->capacity; i++) {
|
||||
hashMap->buckets[i] = NULL;
|
||||
}
|
||||
return hashMap;
|
||||
}
|
||||
|
||||
/* Деструктор */
|
||||
void delHashMapChaining(HashMapChaining *hashMap) {
|
||||
for (int i = 0; i < hashMap->capacity; i++) {
|
||||
Node *cur = hashMap->buckets[i];
|
||||
while (cur) {
|
||||
Node *tmp = cur;
|
||||
cur = cur->next;
|
||||
free(tmp->pair);
|
||||
free(tmp);
|
||||
}
|
||||
}
|
||||
free(hashMap->buckets);
|
||||
free(hashMap);
|
||||
}
|
||||
|
||||
/* Хеш-функция */
|
||||
int hashFunc(HashMapChaining *hashMap, int key) {
|
||||
return key % hashMap->capacity;
|
||||
}
|
||||
|
||||
/* Коэффициент загрузки */
|
||||
double loadFactor(HashMapChaining *hashMap) {
|
||||
return (double)hashMap->size / (double)hashMap->capacity;
|
||||
}
|
||||
|
||||
/* Операция поиска */
|
||||
char *get(HashMapChaining *hashMap, int key) {
|
||||
int index = hashFunc(hashMap, key);
|
||||
// Обойти корзину; если найден key, вернуть соответствующее val
|
||||
Node *cur = hashMap->buckets[index];
|
||||
while (cur) {
|
||||
if (cur->pair->key == key) {
|
||||
return cur->pair->val;
|
||||
}
|
||||
cur = cur->next;
|
||||
}
|
||||
return ""; // Если key не найден, вернуть пустую строку
|
||||
}
|
||||
|
||||
/* Операция добавления */
|
||||
void put(HashMapChaining *hashMap, int key, const char *val);
|
||||
|
||||
/* Расширить хеш-таблицу */
|
||||
void extend(HashMapChaining *hashMap) {
|
||||
// Временно сохранить исходную хеш-таблицу
|
||||
int oldCapacity = hashMap->capacity;
|
||||
Node **oldBuckets = hashMap->buckets;
|
||||
// Инициализация новой хеш-таблицы после расширения
|
||||
hashMap->capacity *= hashMap->extendRatio;
|
||||
hashMap->buckets = (Node **)malloc(hashMap->capacity * sizeof(Node *));
|
||||
for (int i = 0; i < hashMap->capacity; i++) {
|
||||
hashMap->buckets[i] = NULL;
|
||||
}
|
||||
hashMap->size = 0;
|
||||
// Перенести пары ключ-значение из исходной хеш-таблицы в новую
|
||||
for (int i = 0; i < oldCapacity; i++) {
|
||||
Node *cur = oldBuckets[i];
|
||||
while (cur) {
|
||||
put(hashMap, cur->pair->key, cur->pair->val);
|
||||
Node *temp = cur;
|
||||
cur = cur->next;
|
||||
// Освободить память
|
||||
free(temp->pair);
|
||||
free(temp);
|
||||
}
|
||||
}
|
||||
|
||||
free(oldBuckets);
|
||||
}
|
||||
|
||||
/* Операция добавления */
|
||||
void put(HashMapChaining *hashMap, int key, const char *val) {
|
||||
// Когда коэффициент загрузки превышает порог, выполнить расширение
|
||||
if (loadFactor(hashMap) > hashMap->loadThres) {
|
||||
extend(hashMap);
|
||||
}
|
||||
int index = hashFunc(hashMap, key);
|
||||
// Обойти корзину; если встретился указанный key, обновить соответствующее val и вернуть
|
||||
Node *cur = hashMap->buckets[index];
|
||||
while (cur) {
|
||||
if (cur->pair->key == key) {
|
||||
strcpy(cur->pair->val, val); // Если встретился указанный key, обновить соответствующий val и вернуть
|
||||
return;
|
||||
}
|
||||
cur = cur->next;
|
||||
}
|
||||
// Если такого key нет, добавить пару ключ-значение в голову связного списка
|
||||
Pair *newPair = (Pair *)malloc(sizeof(Pair));
|
||||
newPair->key = key;
|
||||
strcpy(newPair->val, val);
|
||||
Node *newNode = (Node *)malloc(sizeof(Node));
|
||||
newNode->pair = newPair;
|
||||
newNode->next = hashMap->buckets[index];
|
||||
hashMap->buckets[index] = newNode;
|
||||
hashMap->size++;
|
||||
}
|
||||
|
||||
/* Операция удаления */
|
||||
void removeItem(HashMapChaining *hashMap, int key) {
|
||||
int index = hashFunc(hashMap, key);
|
||||
Node *cur = hashMap->buckets[index];
|
||||
Node *pre = NULL;
|
||||
while (cur) {
|
||||
if (cur->pair->key == key) {
|
||||
// Удалить из него пару ключ-значение
|
||||
if (pre) {
|
||||
pre->next = cur->next;
|
||||
} else {
|
||||
hashMap->buckets[index] = cur->next;
|
||||
}
|
||||
// Освободить память
|
||||
free(cur->pair);
|
||||
free(cur);
|
||||
hashMap->size--;
|
||||
return;
|
||||
}
|
||||
pre = cur;
|
||||
cur = cur->next;
|
||||
}
|
||||
}
|
||||
|
||||
/* Вывести хеш-таблицу */
|
||||
void print(HashMapChaining *hashMap) {
|
||||
for (int i = 0; i < hashMap->capacity; i++) {
|
||||
Node *cur = hashMap->buckets[i];
|
||||
printf("[");
|
||||
while (cur) {
|
||||
printf("%d -> %s, ", cur->pair->key, cur->pair->val);
|
||||
cur = cur->next;
|
||||
}
|
||||
printf("]\n");
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
/* Инициализация хеш-таблицы */
|
||||
HashMapChaining *hashMap = newHashMapChaining();
|
||||
|
||||
/* Операция добавления */
|
||||
// Добавить пару (key, value) в хеш-таблицу
|
||||
put(hashMap, 12836, "Сяо Ха");
|
||||
put(hashMap, 15937, "Сяо Ло");
|
||||
put(hashMap, 16750, "Сяо Суань");
|
||||
put(hashMap, 13276, "Сяо Фа");
|
||||
put(hashMap, 10583, "Сяо Я");
|
||||
printf("\nПосле добавления хеш-таблица имеет вид\nКлюч -> Значение\n");
|
||||
print(hashMap);
|
||||
|
||||
/* Операция поиска */
|
||||
// Ввести в хеш-таблицу ключ key и получить значение value
|
||||
char *name = get(hashMap, 13276);
|
||||
printf("\nДля студенческого номера 13276 найдено имя %s\n", name);
|
||||
|
||||
/* Операция удаления */
|
||||
// Удалить пару (key, value) из хеш-таблицы
|
||||
removeItem(hashMap, 12836);
|
||||
printf("\nПосле удаления студенческого номера 12836 хеш-таблица имеет вид\nКлюч -> Значение\n");
|
||||
print(hashMap);
|
||||
|
||||
/* Освободить память хеш-таблицы */
|
||||
delHashMapChaining(hashMap);
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
/**
|
||||
* File: hash_map_open_addressing.c
|
||||
* Created Time: 2023-10-6
|
||||
* Author: lclc6 (w1929522410@163.com)
|
||||
*/
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
/* Хеш-таблица с открытой адресацией */
|
||||
typedef struct {
|
||||
int key;
|
||||
char *val;
|
||||
} Pair;
|
||||
|
||||
/* Хеш-таблица с открытой адресацией */
|
||||
typedef struct {
|
||||
int size; // Число пар ключ-значение
|
||||
int capacity; // Вместимость хеш-таблицы
|
||||
double loadThres; // Порог коэффициента загрузки для запуска расширения
|
||||
int extendRatio; // Коэффициент расширения
|
||||
Pair **buckets; // Массив корзин
|
||||
Pair *TOMBSTONE; // Удалить метку
|
||||
} HashMapOpenAddressing;
|
||||
|
||||
// Объявление функции
|
||||
void extend(HashMapOpenAddressing *hashMap);
|
||||
|
||||
/* Конструктор */
|
||||
HashMapOpenAddressing *newHashMapOpenAddressing() {
|
||||
HashMapOpenAddressing *hashMap = (HashMapOpenAddressing *)malloc(sizeof(HashMapOpenAddressing));
|
||||
hashMap->size = 0;
|
||||
hashMap->capacity = 4;
|
||||
hashMap->loadThres = 2.0 / 3.0;
|
||||
hashMap->extendRatio = 2;
|
||||
hashMap->buckets = (Pair **)calloc(hashMap->capacity, sizeof(Pair *));
|
||||
hashMap->TOMBSTONE = (Pair *)malloc(sizeof(Pair));
|
||||
hashMap->TOMBSTONE->key = -1;
|
||||
hashMap->TOMBSTONE->val = "-1";
|
||||
|
||||
return hashMap;
|
||||
}
|
||||
|
||||
/* Деструктор */
|
||||
void delHashMapOpenAddressing(HashMapOpenAddressing *hashMap) {
|
||||
for (int i = 0; i < hashMap->capacity; i++) {
|
||||
Pair *pair = hashMap->buckets[i];
|
||||
if (pair != NULL && pair != hashMap->TOMBSTONE) {
|
||||
free(pair->val);
|
||||
free(pair);
|
||||
}
|
||||
}
|
||||
free(hashMap->buckets);
|
||||
free(hashMap->TOMBSTONE);
|
||||
free(hashMap);
|
||||
}
|
||||
|
||||
/* Хеш-функция */
|
||||
int hashFunc(HashMapOpenAddressing *hashMap, int key) {
|
||||
return key % hashMap->capacity;
|
||||
}
|
||||
|
||||
/* Коэффициент загрузки */
|
||||
double loadFactor(HashMapOpenAddressing *hashMap) {
|
||||
return (double)hashMap->size / (double)hashMap->capacity;
|
||||
}
|
||||
|
||||
/* Найти индекс корзины, соответствующий key */
|
||||
int findBucket(HashMapOpenAddressing *hashMap, int key) {
|
||||
int index = hashFunc(hashMap, key);
|
||||
int firstTombstone = -1;
|
||||
// Выполнять линейное пробирование и завершить при встрече с пустой корзиной
|
||||
while (hashMap->buckets[index] != NULL) {
|
||||
// Если встретился key, вернуть соответствующий индекс корзины
|
||||
if (hashMap->buckets[index]->key == key) {
|
||||
// Если ранее встретилась метка удаления, переместить пару ключ-значение на этот индекс
|
||||
if (firstTombstone != -1) {
|
||||
hashMap->buckets[firstTombstone] = hashMap->buckets[index];
|
||||
hashMap->buckets[index] = hashMap->TOMBSTONE;
|
||||
return firstTombstone; // Вернуть индекс корзины после перемещения
|
||||
}
|
||||
return index; // Вернуть индекс корзины
|
||||
}
|
||||
// Записать первую встретившуюся метку удаления
|
||||
if (firstTombstone == -1 && hashMap->buckets[index] == hashMap->TOMBSTONE) {
|
||||
firstTombstone = index;
|
||||
}
|
||||
// Вычислить индекс корзины; при выходе за конец вернуться к началу
|
||||
index = (index + 1) % hashMap->capacity;
|
||||
}
|
||||
// Если key не существует, вернуть индекс точки добавления
|
||||
return firstTombstone == -1 ? index : firstTombstone;
|
||||
}
|
||||
|
||||
/* Операция поиска */
|
||||
char *get(HashMapOpenAddressing *hashMap, int key) {
|
||||
// Найти индекс корзины, соответствующий key
|
||||
int index = findBucket(hashMap, key);
|
||||
// Если пара ключ-значение найдена, вернуть соответствующее val
|
||||
if (hashMap->buckets[index] != NULL && hashMap->buckets[index] != hashMap->TOMBSTONE) {
|
||||
return hashMap->buckets[index]->val;
|
||||
}
|
||||
// Если пары ключ-значение не существует, вернуть пустую строку
|
||||
return "";
|
||||
}
|
||||
|
||||
/* Операция добавления */
|
||||
void put(HashMapOpenAddressing *hashMap, int key, char *val) {
|
||||
// Когда коэффициент загрузки превышает порог, выполнить расширение
|
||||
if (loadFactor(hashMap) > hashMap->loadThres) {
|
||||
extend(hashMap);
|
||||
}
|
||||
// Найти индекс корзины, соответствующий key
|
||||
int index = findBucket(hashMap, key);
|
||||
// Если пара ключ-значение найдена, перезаписать val и вернуть
|
||||
if (hashMap->buckets[index] != NULL && hashMap->buckets[index] != hashMap->TOMBSTONE) {
|
||||
free(hashMap->buckets[index]->val);
|
||||
hashMap->buckets[index]->val = (char *)malloc(sizeof(strlen(val) + 1));
|
||||
strcpy(hashMap->buckets[index]->val, val);
|
||||
hashMap->buckets[index]->val[strlen(val)] = '\0';
|
||||
return;
|
||||
}
|
||||
// Если пары ключ-значение нет, добавить ее
|
||||
Pair *pair = (Pair *)malloc(sizeof(Pair));
|
||||
pair->key = key;
|
||||
pair->val = (char *)malloc(sizeof(strlen(val) + 1));
|
||||
strcpy(pair->val, val);
|
||||
pair->val[strlen(val)] = '\0';
|
||||
|
||||
hashMap->buckets[index] = pair;
|
||||
hashMap->size++;
|
||||
}
|
||||
|
||||
/* Операция удаления */
|
||||
void removeItem(HashMapOpenAddressing *hashMap, int key) {
|
||||
// Найти индекс корзины, соответствующий key
|
||||
int index = findBucket(hashMap, key);
|
||||
// Если пара ключ-значение найдена, заменить ее меткой удаления
|
||||
if (hashMap->buckets[index] != NULL && hashMap->buckets[index] != hashMap->TOMBSTONE) {
|
||||
Pair *pair = hashMap->buckets[index];
|
||||
free(pair->val);
|
||||
free(pair);
|
||||
hashMap->buckets[index] = hashMap->TOMBSTONE;
|
||||
hashMap->size--;
|
||||
}
|
||||
}
|
||||
|
||||
/* Расширить хеш-таблицу */
|
||||
void extend(HashMapOpenAddressing *hashMap) {
|
||||
// Временно сохранить исходную хеш-таблицу
|
||||
Pair **bucketsTmp = hashMap->buckets;
|
||||
int oldCapacity = hashMap->capacity;
|
||||
// Инициализация новой хеш-таблицы после расширения
|
||||
hashMap->capacity *= hashMap->extendRatio;
|
||||
hashMap->buckets = (Pair **)calloc(hashMap->capacity, sizeof(Pair *));
|
||||
hashMap->size = 0;
|
||||
// Перенести пары ключ-значение из исходной хеш-таблицы в новую
|
||||
for (int i = 0; i < oldCapacity; i++) {
|
||||
Pair *pair = bucketsTmp[i];
|
||||
if (pair != NULL && pair != hashMap->TOMBSTONE) {
|
||||
put(hashMap, pair->key, pair->val);
|
||||
free(pair->val);
|
||||
free(pair);
|
||||
}
|
||||
}
|
||||
free(bucketsTmp);
|
||||
}
|
||||
|
||||
/* Вывести хеш-таблицу */
|
||||
void print(HashMapOpenAddressing *hashMap) {
|
||||
for (int i = 0; i < hashMap->capacity; i++) {
|
||||
Pair *pair = hashMap->buckets[i];
|
||||
if (pair == NULL) {
|
||||
printf("NULL\n");
|
||||
} else if (pair == hashMap->TOMBSTONE) {
|
||||
printf("TOMBSTONE\n");
|
||||
} else {
|
||||
printf("%d -> %s\n", pair->key, pair->val);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
// Инициализация хеш-таблицы
|
||||
HashMapOpenAddressing *hashmap = newHashMapOpenAddressing();
|
||||
|
||||
// Операция добавления
|
||||
// Добавить пару (key, val) в хеш-таблицу
|
||||
put(hashmap, 12836, "Сяо Ха");
|
||||
put(hashmap, 15937, "Сяо Ло");
|
||||
put(hashmap, 16750, "Сяо Суань");
|
||||
put(hashmap, 13276, "Сяо Фа");
|
||||
put(hashmap, 10583, "Сяо Я");
|
||||
printf("\nПосле добавления хеш-таблица имеет вид\nКлюч -> Значение\n");
|
||||
print(hashmap);
|
||||
|
||||
// Операция поиска
|
||||
// Передать ключ key в хеш-таблицу и получить значение val
|
||||
char *name = get(hashmap, 13276);
|
||||
printf("\nДля студенческого номера 13276 найдено имя %s\n", name);
|
||||
|
||||
// Операция удаления
|
||||
// Удалить пару (key, val) из хеш-таблицы
|
||||
removeItem(hashmap, 16750);
|
||||
printf("\nПосле удаления 16750 хеш-таблица имеет вид\nКлюч -> Значение\n");
|
||||
print(hashmap);
|
||||
|
||||
// Уничтожить хеш-таблицу
|
||||
delHashMapOpenAddressing(hashmap);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* File: simple_hash.c
|
||||
* Created Time: 2023-09-09
|
||||
* Author: Gonglja (glj0@outlook.com)
|
||||
*/
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
/* Аддитивное хеширование */
|
||||
int addHash(char *key) {
|
||||
long long hash = 0;
|
||||
const int MODULUS = 1000000007;
|
||||
for (int i = 0; i < strlen(key); i++) {
|
||||
hash = (hash + (unsigned char)key[i]) % MODULUS;
|
||||
}
|
||||
return (int)hash;
|
||||
}
|
||||
|
||||
/* Мультипликативное хеширование */
|
||||
int mulHash(char *key) {
|
||||
long long hash = 0;
|
||||
const int MODULUS = 1000000007;
|
||||
for (int i = 0; i < strlen(key); i++) {
|
||||
hash = (31 * hash + (unsigned char)key[i]) % MODULUS;
|
||||
}
|
||||
return (int)hash;
|
||||
}
|
||||
|
||||
/* XOR-хеширование */
|
||||
int xorHash(char *key) {
|
||||
int hash = 0;
|
||||
const int MODULUS = 1000000007;
|
||||
|
||||
for (int i = 0; i < strlen(key); i++) {
|
||||
hash ^= (unsigned char)key[i];
|
||||
}
|
||||
return hash & MODULUS;
|
||||
}
|
||||
|
||||
/* Хеширование с циклическим сдвигом */
|
||||
int rotHash(char *key) {
|
||||
long long hash = 0;
|
||||
const int MODULUS = 1000000007;
|
||||
for (int i = 0; i < strlen(key); i++) {
|
||||
hash = ((hash << 4) ^ (hash >> 28) ^ (unsigned char)key[i]) % MODULUS;
|
||||
}
|
||||
|
||||
return (int)hash;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
char *key = "Hello Algo";
|
||||
|
||||
int hash = addHash(key);
|
||||
printf("Хеш суммы = %d\n", hash);
|
||||
|
||||
hash = mulHash(key);
|
||||
printf("Хеш произведения = %d\n", hash);
|
||||
|
||||
hash = xorHash(key);
|
||||
printf("XOR-хеш = %d\n", hash);
|
||||
|
||||
hash = rotHash(key);
|
||||
printf("Хеш с циклическим сдвигом = %d\n", hash);
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user