PREV INDEX NEXT

Author: Unknown
Subject: Garbage values on Binpack?
Date: Wednesday, 12 Feb 2020, 23:30:00

In my implementation of best fit, I originally didn't have an int variable to return the number of bins needed (I was just returning 0 until I had figured out the for loops to properly place items in bins. The code looks like this:

int bestfit(int items[], int length, int size) {

	int bins[length];

	int max = 0;

	int maxj = 0;

	//int maxbins = 0;
	//printf("maxbins: %d\n", maxbins);

	for(int i = 0; i < length; i++) {

		for(int j = 0; j < length; j++) {
			//printf("first j: %d\n", j);

			if(items[i] + bins[j] <= size) {

				if(items[i] + bins[j] > max) {

					max = items[i] + bins[j];

					maxj = j;

					printf("My new max index for item %d is %d, and the max is %d\n", items[i], maxj, max);

				}


			}

			if(j == length - 1) {

				bins[maxj] = items[i] + bins[maxj];
				max = 0;

				printf("I am putting item with size %d at bin %d\n", items[i], maxj);


				break;
			}
		}


	}

The code worked initially (as in, from my print statements, I could see that the items were being placed in the proper bins), but when I tried to add the variable maxbins to contain the number of bins needed, the mere declaration and initialization of the variable shifted all of my bins by 4, even without using the variable elsewhere in the function, or even returning it. Does this have to do with garbage values? Or that combined with how arrays work in C? For reference, my main function I was using to test looks like this:

int main(int argc, char *argv[]){


	//test code
	int items[] = {10, 4, 7, 3, 8, 4, 2};

	//int ff = firstfit(items, INTLENGTH(items), 10);

	int bf = bestfit(items, INTLENGTH(items), 10);

	printf("best fit: %d bins\n", bf);

	//first fit test
	//printf("first fit: %d bins\n", ff);

	//printf("array length: %d", INTLENGTH(items));

	//end of test code

}
PREV INDEX NEXT