Programming is easy, but math can be hard at times. In this post, we’ll write some C# code that will help us determine the next number in an interval sequence.
The Problem
Let’s say we have a number, and we also have an interval. Including the original number itself, what is the next logical number in the sequence by interval?
Let’s use some numbers, and the problem will become more evident.
Start | Interval | Next |
---|---|---|
0 | 4 | 0 |
3 | 4 | 4 |
4 | 4 | 4 |
8 | 4 | 8 |
54 | 4 | 56 |
Our parameters for our problem include: The starting number and the interval.
The Solution
Our handy modulus (%)
operator will save the day here. Let’s look at the solution.
The steps we are taking include:
- Determine if the starting number is already in the sequence.
- If so, return the starting value itself.
- If not, find the previous number.
- Add the interval to the earlier integer of the sequence.
- Return the result.
- Make $$$
Let’s see how we can use this extension method in some tests powered by XUnit and Shouldly.
There we have it! Not sure who would need this, but I had fun solving the problem. If you have a better solution, please leave it in the comments, and I may include it in this post.