I've found that the data passed to my mxWeight function is wrong but i cant seem to detect where it is. And i the totalweight keeps exceeding the limit. Please help, thanks.
Code:
/* Main */
int main()
{
int maxCnr;
int file = 0;
double maxWeight;
char filename[50];
char choice;
FILE *input;
List *list = lst_new();
printf("********************** WELCOME TO SHIPMANAGER **********************\n\n");
printf("Please enter the maximum number of containers the ship can carry: ");
scanf("%i", &maxCnr);
printf("\nPlease enter the maximum weight the ship can carry: ");
scanf("%lf", &maxWeight);
do {
printf("\nEnter the filename (.txt): ");
scanf("%s", &filename);
input = fopen(filename, "r");
if (input == NULL)
{
file = 0;
printf("File does not exist. \n");
}
else
{
printf("File located.\n");
file = 1;
}
}while(file == 0);
readContainer(list,filename);
mxCnr(&list, maxCnr);
mxWeight(&list, maxWeight);
printContainers(list);
}
/* ensure that the container does not exceed the maximum number */
void mxCnr(List **list, int mCnr)
{
Container *tmpContainer;
List *max = lst_new();
int i = 0;
for (tmpContainer = lst_first(*list); i<mCnr; tmpContainer = lst_next(*list))
{
Node *previous = NULL;
Node *current = max->head;
if (max->size == 0)
lst_add(max, tmpContainer);
else
{
Node *newNode = node_new(tmpContainer, NULL);
current = max->head;
while (node_getNext(current) != NULL)
{
previous = current;
current = node_getNext(current);
}
if (previous == NULL)
{
node_setNext(newNode, max->head);
max->head = newNode;
}
else
{
max->tail->next = newNode;
max->tail = newNode;
}
max->size++;
}
i++;
}
lst_delete(*list);
*list = max;
}
/* function to calculate the total weight and to ensure that the weight does not exceed the maximum weight */
void mxWeight(List **list, double mWeight)
{
Container *tmpContainer;
List *maxW = lst_new();
double totalweight= 0;
printf("maxweight :%lf ", mWeight);
for (tmpContainer = lst_first(*list); totalweight<=mWeight; tmpContainer = lst_next(*list))
{
Node *current = maxW->head;
Node *previous = NULL;
printf("maxweight :%lf ", mWeight);
if (maxW->size == 0)
{
lst_add(maxW, tmpContainer);
}
else
{
Node *newNode = node_new(tmpContainer, NULL);
current = maxW->head;
while (node_getNext(current) != NULL && totalweight <= mWeight)
{
previous = current;
current = node_getNext(current);
totalweight = totalweight + cnr_getWeight(node_getData(current));
printf("%lf ", cnr_getWeight(node_getData(current)));
}
if (previous == NULL)
{
node_setNext(newNode, maxW->head);
maxW->head = newNode;
}
else
{
maxW->tail->next = newNode;
maxW->tail = newNode;
}
maxW->size++;
}
}
printf("Total weight: %lf", totalweight);
lst_delete(*list);
*list = maxW;
}