95 lines
2.4 KiB
C
95 lines
2.4 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){
|
||
|
for(int i = 0; i < station->track_count; i++){
|
||
|
struct car* this = station->tracks[i];
|
||
|
while(this != NULL){
|
||
|
struct car* delete = this;
|
||
|
this = delete->next;
|
||
|
free(delete);
|
||
|
}
|
||
|
}
|
||
|
free(station->tracks);
|
||
|
free(station);
|
||
|
|
||
|
}
|
||
|
|
||
|
int select_track(struct station* station, const char* target){
|
||
|
unsigned int hash = 0;
|
||
|
for(int i = 0; target[i] != '\0'; i++){
|
||
|
hash = target[i] + (hash << 6) + (hash << 16) - hash;
|
||
|
}
|
||
|
if(hash < 0 || hash > station->track_count){
|
||
|
hash = hash % station->track_count;
|
||
|
}
|
||
|
return hash;
|
||
|
}
|
||
|
|
||
|
void add_target_capacity(struct station* station,const char* target, int capacity){
|
||
|
int track = select_track(station, target);
|
||
|
struct car* start = station->tracks[track];
|
||
|
while(start != NULL){
|
||
|
int x = strcmp(start->value, target);
|
||
|
if(x == 0){
|
||
|
start->capacity = start->capacity + capacity;
|
||
|
return;
|
||
|
}
|
||
|
start = start->next;
|
||
|
}
|
||
|
struct car* newcar = calloc(1, sizeof(struct car));
|
||
|
strcpy(newcar->value, target);
|
||
|
newcar->capacity = capacity;
|
||
|
newcar->next = start;
|
||
|
station->tracks[track] = newcar;
|
||
|
if(newcar->next){
|
||
|
return;
|
||
|
}
|
||
|
return;
|
||
|
|
||
|
}
|
||
|
|
||
|
int get_target_capacity(struct station* station,const char* target){
|
||
|
int track = select_track(station, target);
|
||
|
struct car* start = station->tracks[track];
|
||
|
while(start != NULL){
|
||
|
int x = strcmp(start->value, target);
|
||
|
if(x == 0){
|
||
|
return start->capacity;
|
||
|
}
|
||
|
start = start->next;
|
||
|
}
|
||
|
return 0;
|
||
|
}
|
||
|
|
||
|
int count_targets(struct station* station){
|
||
|
int targets = 0;
|
||
|
for(int i = 0; i < STATION_SIZE; i++){
|
||
|
if(station->tracks[i] != NULL){
|
||
|
targets++;
|
||
|
}
|
||
|
}
|
||
|
return targets;
|
||
|
}
|
||
|
|
||
|
int count_capacity(struct station* station){
|
||
|
int capacity = 0;
|
||
|
for(int i = 0; i < STATION_SIZE; i++){
|
||
|
struct car* this = station->tracks[i];
|
||
|
if(this != NULL){
|
||
|
capacity = capacity + this->capacity;
|
||
|
this = this->next;
|
||
|
}
|
||
|
}
|
||
|
return capacity;
|
||
|
}
|
||
|
|