pvjc26/du6/program.c
2026-04-24 10:30:33 +02:00

105 lines
2.9 KiB
C

#include "a_station.h"
#include <stdlib.h>
#include <string.h>
struct station* create_station(){
struct station* station = (struct station*)calloc(1,sizeof(struct station));
station->tracks = (struct car**)calloc(STATION_SIZE, sizeof(struct car*));
station->track_count = STATION_SIZE;
return station;
}
/* djb2 hash function by Dan Bernstein - deterministic and simple */
static unsigned long hash_str(const char *str) {
unsigned long hash = 5381;
int c;
while ((c = (unsigned char)*str++))
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
return hash;
}
void destroy_station(struct station* station){
if(!station) return;
if(station->tracks){
for(int i = 0; i < station->track_count; ++i){
struct car* cur = station->tracks[i];
while(cur){
struct car* next = cur->next;
free(cur);
cur = next;
}
}
free(station->tracks);
}
free(station);
}
int select_track(struct station* station, const char* target){
if(!station || !target) return 0;
unsigned long h = hash_str(target);
return (int)(h % (unsigned long)station->track_count);
}
void add_target_capacity(struct station* station,const char* target, int capacity){
if(!station || !target || capacity == 0) return;
int idx = select_track(station, target);
struct car* cur = station->tracks[idx];
struct car* prev = NULL;
while(cur){
if(strncmp(cur->value, target, TARGET_SIZE) == 0){
cur->capacity += capacity;
return;
}
prev = cur;
cur = cur->next;
}
/* not found -> create new record and append at head for simplicity */
struct car* node = (struct car*)calloc(1, sizeof(struct car));
if(!node) return; /* allocation failed */
strncpy(node->value, target, TARGET_SIZE - 1);
node->value[TARGET_SIZE-1] = '\0';
node->capacity = capacity;
node->next = station->tracks[idx];
station->tracks[idx] = node;
}
int get_target_capacity(struct station* station,const char* target){
if(!station || !target) return 0;
int idx = select_track(station, target);
struct car* cur = station->tracks[idx];
while(cur){
if(strncmp(cur->value, target, TARGET_SIZE) == 0){
return cur->capacity;
}
cur = cur->next;
}
return 0;
}
int count_targets(struct station* station){
if(!station) return 0;
int count = 0;
for(int i = 0; i < station->track_count; ++i){
struct car* cur = station->tracks[i];
while(cur){
count++;
cur = cur->next;
}
}
return count;
}
int count_capacity(struct station* station){
if(!station) return 0;
int total = 0;
for(int i = 0; i < station->track_count; ++i){
struct car* cur = station->tracks[i];
while(cur){
total += cur->capacity;
cur = cur->next;
}
}
return total;
}