Added generic hashmaps and 2 examples using them

This commit is contained in:
cannoli-fruit 2026-07-11 14:58:42 -04:00
commit 0b34fb93a6
3 changed files with 164 additions and 0 deletions

25
examples/hm_basic.c Normal file
View file

@ -0,0 +1,25 @@
#include <stdio.h>
#define LAZY_IMPL
#include "../lazy.h"
void printHmIdx(void *hm, int k) {
typedef Lz_HM(int,int) HM;
HM map = *(HM*)hm;
if (lz_hm_exists(map,k)) {
printf("hm[%d] = %d\n", k, lz_hm_get(map,k));
} else {
printf("hm[%d] = <N/A>\n", k);
}
}
int main() {
Lz_HM(int, int) hm;
lz_hm_init(hm);
lz_hm_add(hm, 1, 2);
lz_hm_add(hm, 2, 4);
printf("Hello World!\n");
printHmIdx(&hm, 1);
printHmIdx(&hm, 3);
}

33
examples/hm_findsumpair.c Normal file
View file

@ -0,0 +1,33 @@
#include <stdio.h>
#define LAZY_IMPL
#include "../lazy.h"
// This is some CS problem I heard of
// You need to find any two indecies in the array which add to k
// Hashmaps are the main way to solve this better than O(n^2)
int main() {
int vals[] = {7, 12, 25, 30, 43, 60, 1000, 50, 38, 62, 50};
int N = sizeof(vals)/sizeof(vals[0]);
int K = 100;
Lz_HM(int,size_t) LUT;
lz_hm_init(LUT);
for (size_t i = 0; i < N; ++i) {
lz_hm_add(LUT, vals[i], i);
}
for (size_t i = 0; i < N; ++i) {
int v = vals[i];
int other = K-v;
if (lz_hm_exists(LUT, other)) {
size_t otherIdx = lz_hm_get(LUT, other);
if (otherIdx == i) continue;
printf("Found pair: idx: %zu, %zu, vals %d, %d\n",
i, otherIdx,
v, other);
break;
}
}
return 0;
}