简体   繁体   中英

Check if the digits in a number are in ascending order

I have a string that represents a number as such:

445123966682

In that number there are 3 digits that are in ascending order: 123 I want to write a rule that checks any numerical string I give it to see if there are 3 or more numbers in ascending or descending order.

True: 445123 or 445987 False: 192837 or 97531

I presume the best way is to use a RegEx check, but I am not the best at RegEx. The only other option I can think of is to either iterate the characters and check or cast the number to an integer and use modulo + division to grab each digit off of the number and compare with the next number in the series.

Edit Sorry, I meant contiguous order. 123 is valid, 135 is not.

With regexp, it's kind of trivial:

/012|123|234|345|456|567|678|789|987|876|765|654|543|432|321|210/

It's dumb, but the problem is simple enough that the dumb solution is the best one.

I am not too sure you can use RegExp here, as the problem is more complex as it may appear. You need 3 numbers in direct or reverse order. It seems like you can have a lot of combinations to put into the regexp.

I suggest to design a simple buffer and a lookout window. Buffer size may equal to the lookout windows size. You put a symbol in a buffer and check the lookout window for the next few symbols. Step-by-step you can add complexity to such algorithm to remember the place, length etc.

I think this is how I would approach the problem:

public bool TestForAscending()
    {
        var regex = new Regex(@"(\d)(?=(\d{2}))");

        var target = "120847212340876";

        var matches = regex.Matches(target);

        List<string> groups = new List<string>();

        foreach( Match m in matches )
        {
            groups.Add(m.Groups[1].Value + m.Groups[2].Value);
        }

        return groups.Any(x => IsAscending(x));
    }

    public static bool IsAscending(string x)
    {
        if (x.Length == 1)
        {
            return true;
        }

        int last = int.Parse(x.Last().ToString());
        int prev = int.Parse(x[x.Length - 2].ToString());

        return last == prev + 1 && IsAscending(x.Substring(0, x.Length - 1));
    }

Here you have a regex that will return every 3 digit group from the target string (you can change how many consecutive digits you want to test by adjusting the quantifier in the regex). The catch with this regex is that it breaks up the pair among 2 groups, so to get the full number, you have to concat group 1 and group 2. But that's easy. After that, you just write a little method to test if the number is ascending (I chose recursive).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM