# Problems with Recursion...

• 11-16-2011, 12:49 PM
AmazingDude
Problems with Recursion...
Hi.
I've got small problem with my recursive function. My task sounds like this:

A builder wishes to build a (three-dimensional) pyramid. Each layer is
comprised of square blocks. The top layer comprises a single block, the next
layer comprises four blocks (2 x 2 blocks). The next expands so that each side
is 3 blocks long. The central block is not inserted so the layer comprises 8
blocks. Each additional layer adds another block to the edge and only lays the
outer blocks.

1. Write a series of tests in Q3Test that would ensure a function calculated
the correct number of blocks required based on the above specification.
Document (using comments) the test cases that you are going to use.
2. Write a recursive function that will perform the calculations and run your
tests against the method

Problem is with second question. My code seems not working correctly and i can't determine the problem. I am posting my code bellow:

public int PBR( int layersN ) {
if (layersN < 1)
return 0;
else
return layersN == 1 ? 1 : 2*PBR( layersN-1 )-PBR( layersN-2 )+4;
}

When i run test and make layersN = 3, I expect answer 13, but BlueJ gives me answer 15. Cant determine where is mistake so I would be really grateful if somebody will help me.

Thx
AmazingDude :(handshake):
• 11-16-2011, 01:49 PM
JosAH
Re: Problems with Recursion...

kind regards,

Jos
• 11-16-2011, 02:11 PM
AmazingDude
Re: Problems with Recursion...
Yes i know and I checked that post already, but there is no answer to my question. I would like to know why my function is not working, i don't need to know why another persons function problem. All what I need is to find a place in function which cause mistake, and i just cant see it... This is my question.

Thx
AmazingDude:(handshake):
• 11-16-2011, 02:19 PM
JosAH
Re: Problems with Recursion...
Not just layersN == 1 is an exception to the rule, also layersN == 2 is an exception, because that layer doesn't contain four more bricks than the previous layer. See my version of the code in the other thread. (I started at layersN == 0, you start at layersN == 1)

kind regards,

Jos
• 11-16-2011, 04:39 PM
AmazingDude
Re: Problems with Recursion...
Indeed mate, you right... How could I miss that... :frusty:

Thx for the help. :(y):
Amazing dude :(handshake):