diff options
author | Alexandre Jesus <adbjesus@gmail.com> | 2016-08-22 16:35:31 +0100 |
---|---|---|
committer | Alexandre Jesus <adbjesus@gmail.com> | 2016-08-22 16:35:31 +0100 |
commit | 3c8f9385498611df123d5f07d0e52035b568d415 (patch) | |
tree | 790528ae70db81429d6cec0fd7892ac130535d7b /src/common.c | |
parent | 66cfb031dfa81fcb083335a709cb4bd561faccb2 (diff) | |
download | libuknapsack-3c8f9385498611df123d5f07d0e52035b568d415.tar.gz libuknapsack-3c8f9385498611df123d5f07d0e52035b568d415.zip |
Initial code
Diffstat (limited to 'src/common.c')
-rw-r--r-- | src/common.c | 88 |
1 files changed, 88 insertions, 0 deletions
diff --git a/src/common.c b/src/common.c new file mode 100644 index 0000000..92bd467 --- /dev/null +++ b/src/common.c @@ -0,0 +1,88 @@ +#include <stdlib.h> +#include <stdio.h> +#include <math.h> +#include "structs.h" +#include "common.h" + +struct data * input(char fp[]){ + int i,j; + FILE *f; + struct data * d = (struct data *)malloc(sizeof(struct data)); + + f = fopen(fp,"r"); + j = fscanf(f,"%ld",&(d->N)); + if(j!=1){ + printf("Error reading data\n"); + exit(0); + } + d->items = (struct item *)malloc(d->N*sizeof(struct item)); + for(i=0;i<d->N;++i){ + j = fscanf(f,"%lf %lf",&(d->items[i].p),&(d->items[i].w)); + d->allp += d->items[i].p; + d->allw += d->items[i].w; + } + + fclose(f); + return d; +} + +int cmp_items_ratio(const void * a, const void * b){ + struct item c = *(struct item *)a; + struct item d = *(struct item *)b; + if(c.p / c.w < d.p / d.w){ + return 1; + } + return -1; +} + +void print_data(struct data * d){ + int i; + printf("### PRINTING DATA - BEGINNING ###\n"); + printf("N:\t%ld\n\n",d->N); + printf("Profit\tWeight\n"); + for(i=0;i<d->N;++i){ + printf("%.02f\t%.02f\n",d->items[i].p,d->items[i].w); + } + printf("### PRINTING DATA - ENDING ###\n"); +} + +void print_front(struct front_item * b){ + while(b!=NULL){ + printf("%.02f\t%.02f\n",b->i.p,b->i.w); + b = b->next; + } +} + +void free_data(struct data * d){ + free(d->items); + free(d); +} + +void free_front(struct front_item * b){ + struct front_item * tmp; + for(;b!=NULL;){ + tmp = b; + b = b->next; + free(tmp); + } +} + +struct front_item * new_front_item(double p, double w, struct front_item * prev, struct front_item * next){ + struct front_item * f = (struct front_item *)malloc(sizeof(struct front_item)); + f->i.p = p; + f->i.w = w; + f->next = next; + f->prev = prev; + + return f; +} + +double dist_items(struct item * a, struct item * b){ + return sqrt((a->p - b->p)*(a->p - b->p) + (a->w - b->w)*(a->w - b->w)); +} + +int len_front(struct front_item * f){ + int N; + for(N=0;f!=NULL;f=f->next,N++); + return N; +} |