usaa24/cv6/a_station.c

136 lines
2.7 KiB
C
Raw Permalink Normal View History

2024-11-08 12:06:45 +00:00
#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;
}
void destroy_station(struct station* station)
{
if (station == NULL)
{
return;
}
for (int i = 0; i < station->track_count; i++)
{
struct car* this = station->tracks[i];
while (this != NULL)
{
struct car* temp = this;
this = this->next;
free(temp);
}
}
free(station->tracks);
free(station);
}
int select_track(struct station* station, const char* target)
{
2024-11-08 12:17:47 +00:00
//DJB2 hash
unsigned int hash = 5381;
int c;
2024-11-08 12:06:45 +00:00
2024-11-08 12:17:47 +00:00
while ((c = *target++))
2024-11-08 12:06:45 +00:00
{
2024-11-08 12:17:47 +00:00
hash = hash * 33 + c;
2024-11-08 12:06:45 +00:00
}
2024-11-08 12:17:47 +00:00
2024-11-08 12:06:45 +00:00
return hash % station->track_count;
}
void add_target_capacity(struct station* station, const char* target, int capacity)
{
int stIndex = select_track(station, target);
struct car* start = station->tracks[stIndex];
struct car* this = start;
while (this != NULL)
{
if (strcmp(this->value, target) == 0)
{
this->capacity += capacity;
return;
}
this = this->next;
}
struct car* nCar = (struct car*)malloc(sizeof(struct car));
if (nCar == NULL)
{
return;
}
strncpy(nCar->value, target, TARGET_SIZE - 1);
nCar->value[TARGET_SIZE - 1] = '\0';
nCar->capacity = capacity;
nCar->next = start;
station->tracks[stIndex] = nCar;
}
int get_target_capacity(struct station* station,const char* target)
{
int indTr = select_track(station, target) % station->track_count;
struct car* this = station->tracks[indTr];
while (this != NULL)
{
if (strcmp(this->value, target) == 0)
{
return this->capacity;
}
this = this->next;
}
return 0;
}
int count_targets(struct station* station)
{
int count = 0;
for (int i = 0; i < station->track_count; i++)
{
struct car* current = station->tracks[i];
while (current != NULL)
{
count++;
current = current->next;
}
}
return count;
}
int count_capacity(struct station* station)
{
int res = 0;
for (int i = 0; i < station->track_count; i++)
{
struct car* current = station->tracks[i];
while (current != NULL)
{
res += current->capacity;
current = current->next;
}
}
return res;
}