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.
public static class NumberHelper
{
public static int ClosestNumberInSequence(this int number, int interval)
{
var remainder = number % interval;
if (remainder == 0)
return number;
var start = number - remainder;
var next = start + interval;
return next;
}
}
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.
using Shouldly;
using Xunit;
namespace ClassLibrary1
{
public class Tests
{
[Fact]
public void Can_get_same_number_if_is_next_number_in_sequence()
{
0.ClosestNumberInSequence(4).ShouldBe(0);
4.ClosestNumberInSequence(4).ShouldBe(4);
8.ClosestNumberInSequence(4).ShouldBe(8);
12.ClosestNumberInSequence(4).ShouldBe(12);
4.ClosestNumberInSequence(3).ShouldBe(6);
}
[Fact]
public void Can_get_next_number_if_number_is_below_sequence()
{
3.ClosestNumberInSequence(4).ShouldBe(4);
54.ClosestNumberInSequence(4).ShouldBe(56);
}
}
public static class NumberHelper
{
public static int ClosestNumberInSequence(this int number, int interval)
{
var remainder = number % interval;
if (remainder == 0)
return number;
var start = number - remainder;
var next = start + interval;
return next;
}
}
}
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.