Need help debugging my code
Hey, I was presented with a problem that goes like this:
You have to find out how many blocks of the same height you can stack in a pyramid way. The "pyramid" must be built in a way that a block A on top of a block B has smaller or equal sides. You can turn the blocks to make them fit.
The site will give you an input, with a pre determined format, that is:
Quote:
3
100 100
1000 2000
2000 500
0
The first line determines how many blocks you're given (you're given n blocks), the next n lines are the sides of the block and the last line must be a zero.
There can be more that one pyramid:
Quote:
3
100 100
1000 2000
2000 500
6
3 4
5 7
7 5
1 5
4 4
10 2
0
I hope you can understand the problem I just described. If not please say.
So what I'm doing is finding the areas of the blocks and sorting them from bigger to smaller. If the block with the second biggest area has smaller or equal sides than the one with the biggest area the number of blocks in the pile increases.
If one of the sizes of the top block is bigger than the ones of the smaller one you go and compare the first with the third one and so on.
Here's the code I have so far, it's just crashing and closing. Some of the variable names in it are in portuguese, but I don't beleive that it will be difficult for you to understand the code.
Code:
#include <stdio.h>
int main ()
{
FILE *fp;
int start = 1, num, arrayX[100], arrayY[100], arrayArea[100], i, x, y, n;
int maiorArea = -1, velhoY = 0, velhoX = 0, novoX, novoY, teste = 1, numeroBlocos;
fp = fopen("entrada.txt", "r");
if (!fp)
{
printf("Erro ao ler o arquivo!");
return 1;
}
while (true)
{
if (start)
{
fscanf(fp, "%d", num);
if (!num || feof(fp))
{
fclose(fp);
return 0;
}
!start;
} else {
numeroBlocos = 0;
for (i = 0; i < num; i++)
{
fscanf(fp, "%d %d", arrayX[i], arrayY[i]);
arrayArea[i] = arrayX[i] * arrayY[i];
}
while (num-- > 0)
{
for (n = 0; n <= i; n++)
{
if (arrayArea[n] > maiorArea && maiorArea != n)
maiorArea = n;
}
arrayArea[maiorArea] = 0;
novoX = arrayX[maiorArea];
novoY = arrayY[maiorArea];
if ((velhoX == 0 && velhoY == 0) || (novoX <= velhoX && novoY <= velhoY) || (novoX <= velhoY && novoY >= velhoX))
{
velhoX = novoX;
velhoY = novoY;
numeroBlocos++;
}
}
printf("Teste %d\n %d\n\n", teste++, numeroBlocos);
velhoX = velhoY = 0;
!start;
}
}
fclose(fp);
return 0;
}
Oh and the output must follow this rule:
Teste n // test n (n being the pyramid id)
x // x is the number of blocks that can be stacked according to the rules
// empty line
-----------------------------------
By the way I'd like to know how do you guys debug your code... Do you disassemble it? Is there a way to debug the code in C language?
Thank you for your help.