78 lines
2.2 KiB
C
78 lines
2.2 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;
|
|
}
|
|
|
|
void destroy_station(struct station* station){
|
|
free(station->tracks);
|
|
free(station);
|
|
}
|
|
|
|
int select_track(struct station* station, const char* target){
|
|
if(!station || station->track_count == 0)
|
|
return 0;
|
|
|
|
int hash_result = (int)strlen(target) % station->track_count;
|
|
struct car* current = station->tracks[hash_result];
|
|
|
|
while(current != NULL && abs(strcmp(station->tracks[hash_result]->value, target))){
|
|
hash_result = (hash_result * 2 + 1) % station->track_count;
|
|
current = station->tracks[hash_result];
|
|
}
|
|
|
|
return hash_result;
|
|
}
|
|
|
|
void add_target_capacity(struct station* station,const char* target, int capacity){
|
|
if(!station || station->track_count == 0)
|
|
return;
|
|
|
|
int myTrack = select_track(station, target);
|
|
|
|
struct car* uniqueCar = station->tracks[myTrack];
|
|
if(!uniqueCar) {
|
|
uniqueCar = (struct car *) calloc(1, sizeof(struct car));
|
|
uniqueCar->capacity = 0;
|
|
strcpy(uniqueCar->value, target);
|
|
uniqueCar->next = NULL;
|
|
}
|
|
uniqueCar->capacity += capacity;
|
|
station->tracks[myTrack] = uniqueCar;
|
|
}
|
|
|
|
int get_target_capacity(struct station* station,const char* target){
|
|
if(!station || station->track_count == 0 || station->tracks[select_track(station, target)] == NULL)
|
|
return 0;
|
|
|
|
return station->tracks[select_track(station, target)]->capacity;
|
|
}
|
|
|
|
int count_targets(struct station* station){
|
|
if(!station || station->track_count == 0)
|
|
return 0;
|
|
|
|
int numberOfTargets = 0;
|
|
for(int i = 0; i < station->track_count; i++)
|
|
numberOfTargets += (station->tracks[i] == NULL) ? 0 : 1;
|
|
|
|
return numberOfTargets;
|
|
}
|
|
|
|
int count_capacity(struct station* station){
|
|
if(!station || station->track_count == 0)
|
|
return 0;
|
|
|
|
int totalCapacity = 0;
|
|
for(int i = 0; i < station->track_count; i++)
|
|
totalCapacity += (station->tracks[i] == NULL) ? 0 : station->tracks[i]->capacity;
|
|
|
|
return totalCapacity;
|
|
}
|
|
|