I have been given a rather odd requirement to fulfill for a particular solution. The requirement is to write a function given the current number, to find the next consecutive number that excludes numbers with two or more consecutive 6s.
So far I have the following code (in C#) which I tested with a few inputs and it works. I know it’s not the most efficient solution but it does the job, I just want to see if there’s a more efficient way of doing this. The way I go about it is by converting the number into a string and using a simple regular expression to see if the next sequence is a valid one given the requirement. Also I am aware that it will throw a error once the number reaches its (2^31) – 1 limit, but at the moment that’s not an issue.
public int GetNextSequenceNumber(int currentSequenceNumber)
{
var nextSequenceCandidate = currentSequenceNumber + 1;
var strNum = nextSequenceCandidate.ToString();
if (IsValidSequenceNumber(strNum))
{
return nextSequenceCandidate;
}
else
{
do
{
strNum = (++nextSequenceCandidate).ToString();
} while (!IsValidSequenceNumber(strNum));
return nextSequenceCandidate;
}
}
private bool IsValidSequenceNumber(string sequenceNumber)
{
return !Regex.IsMatch(sequenceNumber, "[6]{2,}");
}
I’m thinking there’s another way where one would use division and the modulus operation to find out the digits position and increment that just as needed. Any input is appreciated, thanks!
The most efficient solution that I see would actually use string replacement, but this works only if you are incrementing and returning all values of the sequence. Just replace
66by67.If any starting number is allowed, you will have to append just as many
0s as there were digits after the first occurrence of66in your number string.