Ladders* - pls help

You have N equal little cubes. You can stack several cubes on top of each other to build a tower. You can also place several towers next to each other to build a ladder. The heights of the towers within a ladder must be strictly increasing. Using 6 cubes you can build a ladder of three towers with heights 1 2 and 3. Overall, there are four ways to build a ladder out of 6 cubes:
6 (a single tower by itself is a ladder)
1 5
2 4
1 2 3

Input 6

Output 4


How to write code so that the variable k was inside the function ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

int k = 0;

void NumberOfLadders(int n, int firtsTowerHeight)
{
    ++k;
    for (int i = n + 1; i < (firtsTowerHeight + 1) / 2; ++i)
    {
       NumberOfLadders(i, firtsTowerHeight - i);
    }
}

 
int main()
{
    int n;
    std::cin >> n;
    NumberOfLadders(0, n);
    std::cout << k << "\n";
}
Hello kizhvac kampazitr,

If I were to put "k" anywhere I would put "k"in main and pass it to the function by reference. void NumberOfLadders(int n, int firtsTowerHeight, int& k). But I do not see any use for "k" other than a counter right now.

Your bigger problem is that void NumberOfLadders(int n, int firtsTowerHeight) appears to be a recursive function with no way out, so it will be an endless loop until the stack runs out of memory.

Take look at these links:

http://www.cplusplus.com/articles/D2N36Up4/
http://www.cplusplus.com/forum/articles/2231/

There are more available if you do a search here on "recursion".

Hope that helps,

Andy
Thanks !
wrоte like this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

int NumberOfLadders(int n, int firtsTowerHeight)
{
	int result = 1;
	for(int i = n + 1; i < (firtsTowerHeight + 1) / 2; ++i) 
        result += NumberOfLadders(i, firtsTowerHeight - i);
	return (n > firtsTowerHeight) ? 0 : result;
}

 
int main()
{
	int n;
	std::cin >> n;
    std::cout << NumberOfLadders(0, n) << "\n";
}
Topic archived. No new replies allowed.