Hello! I'm pretty new to programming, and I'm trying to understand how I would write a recursive function that counts the possible combinations of steps one might take if they have the choice of taking 1 or 2 steps at a time. I'd like the only argument to be the number of steps they would climb. I think I understand what the base case should be, but that's about it (I did find another thread discussing something similar, posted a couple years ago, but I had a hard time understanding it). Any clues or other help would be much appreciated! Thank you!
1 2 3 4 5 6 7 8 9 10 11
int CountWays(int steps)
{
if (steps == 0)
{
return 0;
}
else
{
?
}
}
If there's some way to do this without adding more arguments, that's what I'm looking for.
I'm not sure my solution is correct, but it's agreeing with the # of ways for the cases of 4,5,6 or 7 stairs as enumerated by hand.
The counts I get by hand are:
n ways
4 5
5 8
6 13
7 21
My base case: If( n < 3 ) return n;
Reason is this covers the cases for either 0, 1 or 2 stairs, which = n.
For 3 or more stairs, the # of ways = #ways if n-1 stairs are left + #ways if n-2 stairs are left.
Not sure how to explain any further without showing my code, except to say it's just 2 lines.
EDIT: Removed my code.
Did not see cires' post.
I have seen 2 different ways to seed the Fibonnaci sequence. Either 0, 1 or 1, 1
ie. F(0) = 0 or F(0)=1
The 1st seed method gives the desired sequence.
BTW you missed the F(6)=8 and F(5)=8 cases in your listings.
Seeding with 0, 1 would offset it in the opposite direction I'd like to. And I'm not sure how I would change the seed anyway. I would want to seed the sequence with 1, 2 somehow if that's the way to go about this.
EDIT: OK, never mind about me not knowing how to seed it. When I seed it with 1, 2 I get results one offset too far. 4 comes out 8, 5 comes out 13 etc.
EDIT: THANK YOU, THANK YOU, THANK YOU! Seeding it with 1, 1 is exactly what I wanted! I just corrected this:
This seems to work just the way I want it to, except for when steps = 0. Then it returns 1. Other than that, every other number seems to work like it should.
I read it, I guess I'm just confused as to what you mean by "!= S(0) + S(1)" In my program S(2) = 2, S(1) = 1, and S(0) = 1. Every input above 0 works like I want it to.
We have a case which doesn't match the Fib sequence either way we seed it.
We require:
CountWays(0) = 0
CountWays(1) = 1
CountWays(2) = 2
No Fib sequence is 0, 1, 2,... because 2 != 0 + 1
The reason for my base case is that it works for these first 3 cases whereas no fib sequence does.
Does that make any better sense?