This seems so obvious , but I cannot find a way to do this.
I think there even is a regular PHP function to do this, but even that one stays well hidden after 1,5 hours of intensive Google searches.
What I want
- A function that takes a string as input.
- Checks that string for the number of times it has alphabetical orderded sequences of more than 3 characters:
- returns true if a sequence of more than 3 has been found.
Example
"youlookgreatbcdetoday" => has "bcde" in it … so has to return true
"youlookgreatklmtoday" => only has "klm" in it … so that has to return false
"youlookgreattoday" => has no alphabetically ordered sequences in it, so returns false
Possible usecase
- password strength checker
- wordgame
- …
disclaimer: I wish I already had some code to show you, but I literally have nothing yet.
Only thing I could come up with was to split the string up in an array and do some magic on the array … but even then I got stuck.
Hope one of you will save me 🙂
So, let’s start off with a trivial implementation using a loop and a counter (for increasing only):
So, how does it work? Basically, it loops through, and checks to see if the
ord(ascii number) of the character is one more than the one before it. If so, it increases the count parameter. Otherwise, it sets it to 1 (since we already processed that character). Then, if$countis ever more or equal to the number requested, we know we found a sequence, and can return…So, now let’s check in both directions:
Now, it’ll return true for
abcdanddcba…Now, here’s a far simpler solution:
And there you go. We use the property that if we add a decreasing number to each position, consecutive sequences will appear as the same number. And that’s exactly how this works.
And here’s the same theory applied to both directions: