Files
dslab/12.c
Amneesh Singh 6b6012ab05 exp 12: init
Signed-off-by: Amneesh Singh <natto@weirdnatto.in>
2022-12-27 22:12:08 +05:30

49 lines
949 B
C

#include <stdio.h>
#include <stdlib.h>
typedef struct Item item;
struct Item {
unsigned int key;
int value;
};
unsigned int hash(char *x, unsigned int n) {
const unsigned int offset = 2166136261;
unsigned int hash = 0;
for (unsigned int i = 0; i < n; x++, i++) {
hash *= offset;
hash ^= (*x);
}
return hash;
}
int search(item items[], int n, char *x, int xn) {
unsigned int key = hash(x, xn);
for (int i = 0; i < n; i++) {
if (items[i].key == key)
return items[i].value;
}
printf("Not found");
exit(1);
}
int main() {
int const SIZE = 4;
item items[SIZE];
items[0].key = hash("nita", 4);
items[0].value = 99;
items[1].key = hash("amaang", 5);
items[1].value = -129;
items[2].key = hash("unreal", 6);
items[2].value = 4;
items[3].key = hash("alpaviraam", 10);
items[3].value = 10000;
char x[] = "unreal";
printf("Value for string %s is: %d", x, search(items, SIZE, x, 6));
}