This is a task to be done in C. Can you tell me how to approach this?
A train has a length of n meters. It is made up of individual compartments of 1 or 2 meters in length. How many different combinations of such compartments exist for a train of a given length? Write a function Train (n) that computes this.
Start with the simplest cases and look for regularities.
Train (1)is obviously 1: (1).Train (2)is obviously 2: (1 1) and (2).Train (3)is 3: (1 1 1), (1 2), and (2 1). The first two can be combined into conjoining (1) with (1 1) resp (2). The latter are exactly the combinations ofTrain (2). So,Train (3)isTrain (2) + 1.Train (4)is 5: (1 1 1 1) (1 1 2) (1 2 1) (2 1 1) (2 2). Again, we can combine the first as (1) with (1 1 1), (1 2), and (2 1), which are the combinations ofTrain (3). The last are (2) conjoined with (1 1) and (2), which are the combinations ofTrain (2). So,Train (4)isTrain (3) + Train (2). Now, looking back atTrain (3), we see that the+ 1isTrain (1).Now it seems clear that
Train (n)is alwaysTrain (n - 1) + Train (n - 2). That is exactly the definition of the Fibonacci sequence.Now, let us see how that is translated to C.
The function skeleton:
Traintakes one integer argument and returns an integer:The definition we worked out:
This will recurse infinitely, so we need to stop it at the base case. One base case is clear:
Train (1)is 1:This is still not enough. Imagine what
Train (2)does: it will calculateTrain (1) + Train (0).Train (1)is no problem, butTrain (0)will calculateTrain (-1) + Train (-2), which again recurses infinitely. So, we need another base case:Train (2)is 2.This works, but we can simplify the base cases:
If you now just paste that last code snippet into your homework without working through the “too long, didn’t read” preliminaries, I have successfully undermined your education, and you will never learn to program. You are welcome.
This is not the best way to calculate Fibonacci numbers. Why? How should you modify the code to avoid duplication of effort? Are there different approaches imaginable? Which ones?