3

I came up with the following regex as a way to check for data that consists of only a set of digits in contiguous sequence in ascending or descending order.

Obvious constraints: the string will be between 2 and 10 digits long, since one digit is not a sequence and more than ten digits would have to repeat. Other code will ensure that the input consists of nothing but digits. (e.g. /\A\d{2,}\z/)

Examples:

  • '012', '9876' and '56' should match
  • '7', '013', '6554' and '09' should not

I think this does the job:

/(?:\A(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)|\d(?!\d)){2,}\z)|
 (?:\A(?:1(?=0)|2(?=1)|3(?=2)|4(?=3)|5(?=4)|6(?=5)|7(?=6)|8(?=7)|9(?=8)|\d(?!\d)){2,}\z)/x

Here's the question: Can you see a more concise or beautiful way to express this in a Ruby-compatible regex?

Obviously, a couple of nested loops would be a non-regex solution to the same problem.

if num.length > 1
  [Proc.new { |n| n + 1 }, Proc.new { |n| n - 1 }].each do |p|
    is_sequential = true
    (0..num.length - 2).each do |i|
      if p.call(num[i].ord) != num[i + 1].ord
        is_sequential = false
        break
      end
    end
    return 'Number is sequential' if is_sequential
  end
end

Care to make that any tighter or more beautiful?

6
  • 1
    There are some better answers here: stackoverflow.com/questions/5682940/… Oct 23, 2013 at 19:33
  • 1
    Regexes are good for detecting patterns, but not for doing anything with the values of what it finds. Oct 23, 2013 at 20:35
  • This is a poor use of a regex. Use the pattern to find groups of digits, then tear them apart and see if they match your rules using regular logic. Oct 23, 2013 at 21:38
  • @Andy, what you say is true, but not applicable: detecting a pattern is exactly what I want to do in this case. The problem is that it's a pattern that cannot easily be expressed as a regex. Oct 24, 2013 at 15:19
  • The regex /\A(\d)\1+\z/ can be used to find strings consisting only of the same digit. I hope that wouldn't be described as a "poor use of a regex." From one perspective finding 55555 and 54321 don't feel so far apart. Let's imagine for a moment that \1 can be used as a backreference within #{} interpolated into a regex. (It can't, afaict.) If it could, this regex would do what I'm looking for, I think: /\A(?:(\d)(?=#{\1+1})|\d(?!\d)){2,}\z (and similar for descending sequences). By asking the question I was hoping to learn more about what a regex can do. Thanks! Oct 24, 2013 at 15:42

7 Answers 7

3
def isseq( s )
  1 < s.length && !!( '0123456789'[s] || '9876543210'[s] )
end

[ '012', '9876', '56', '7', '013', '6554', '09' ].each do |test|
  puts "#{test} #{isseq(test)}"
end

outputs:

012 true
9876 true
56 true
7 false
013 false
6554 false
09 false

Credit goes to tihom for the super_string idea and the Tin Man for using str[s].

1
  • The common thread in these answers (@Matt, @Cary and @tihom) is the insight that instead of matching the present string to some pre-known pattern, you can invert the question and match some pre-known string to the current string-as-a-pattern. Eye-opening. Nicely done! Oct 24, 2013 at 16:06
2
super_string = "0123456789"

'012'.scan(/\d{2,10}/).
map{|x| super_string.include?(x) || super_string.reverse.include?(x) }.
uniq == [true]
#=> true

'013'.scan(/\d{2,10}/).map{|x| super_string.include?(x) || super_string.reverse.include?(x) }.uniq == [true]
#=> false

Note: This returns true if the given string has (10n+1) digits for n > 0 if all digits except last are in sequence. It can be modified to return false if that is not the required output.

2

For a given initial digit and string length there are only two possible valid strings. Just generate them both and make a comparison.

def sequential_num(num)

  return false if num =~ /\D/ or num.length <= 1

  initial = num[0]
  range = (num.length - 1)

  final = (initial.ord + range).chr
  return true if final <= '9' and num == (initial..final).to_a.join

  final = (initial.ord - range).chr
  return true if final >= '0' and num == (final..initial).to_a.reverse.join

  return false
end


%w/ 012 9876 56 7 013 6554 09 /.each do |num|
  puts '%-4s %s' % [ num, sequential_num(num) ? 'match' : 'no match' ]
end

output

012  match
9876 match
56   match
7    no match
013  no match
6554 no match
09   no match
1
  • I like your analysis that "For a given initial digit and string length there are only two possible valid strings." Nice! Oct 24, 2013 at 15:49
2

Edit: I misread the question. Initially I had:

$10 says you're going to slap your forehead.

s = str.split('')
sorted = s.sort
sorted == s || sorted == s.reverse

I changed my solution to:

  s = "0123456789"
  s.include?(str) || s.reverse.include?(str)

but then saw @Matt had already given this solution.

I hereby retract my offer of a wager.

6
  • 1
    Add a bunch of no-ops because everyone else seems to think it'd take a lot more code. :-) Oct 23, 2013 at 21:41
  • 013 should not match so 96321 should also not match, the digits need to be in order and sequence..right?
    – tihom
    Oct 23, 2013 at 21:49
  • @the (aka Sn): looks like you misread the question too. If that was your upvote, best to undue it. Oct 23, 2013 at 22:41
  • 1
    For fun, s.include?(str) is the same as !!s[str], but not as fast. Oct 23, 2013 at 23:24
  • @the I saw !! for the first time a few days ago. Initially I thought it was an unfamiliar operator. s[str] || s.reverse[str], which evaluates to str or nil, would often work, but probably not the best programming practice. Oct 24, 2013 at 0:37
2

Dan, sometimes thought is needed about where to put what when doing a pattern match. The interesting thing here is that '0123456789 9876543210' is a string containing every possible correct answer. Once we have validated our input as all digits, length>1, it is proper to use a pattern match to see if the data occurs in the universe of solutions. I speak Perl pretty well, so I'll stick with that. This is the general test:

So $nstring is verified numeric, length>1.

print "$nstring matches!\n" if '0123456789 9876543210' =~ /$nstring/;

Or a trivial program auditing for a suitable string then testing:

while (<STDIN>) 
{
    chomp;
    next if not /^[0-9]{2,}$/;
    $nstring=$_;
    $matches='0123456789 9876543210' =~ /$nstring/?"matches":"does not match";
    print "$nstring $matches!\n";
}                                    
1
  • I think that was one of the key insights from several of these answers, Steve, that the regex could be made of the more dynamic part of the equation, and the thing you really want to match against could sit in the static string side of the =~ or match operator. I also like that you put a space in the middle to enable a single-match operation. That requires, of course, that the target string must already be known to be all digits: otherwise '9 9' would match. Nicely done! Oct 29, 2013 at 13:48
2

Here is an attempt at a non-regex functional solution in elixir:

#!/usr/bin/env elixir

defmodule Seq do

  def is_seq(list) when match([x, y | t], list), do: is_desc(list) || is_asc(list)
  def is_seq(_), do: false

  def is_desc([first, second | tail]), do: second == first - 1 && is_desc [second | tail]
  def is_desc(_), do: true

  def is_asc([first, second | tail]), do: second == first + 1 && is_asc [second | tail]
  def is_asc(_), do: true

  def test() do
    ['012', '9876', '56', '7', '013', '6554', '09', '012345678', '01234678'] |> Enum.map &is_seq/1
  end
end

Seq.test |> IO.inspect
1
  • I like the way that Elixir lets you pattern-match on multiple head-elements of the list. That makes it easy to handle every element while still considering them in pairs, like each_cons does in Ruby. I wonder if you could DRY this up with a tiny function to encapsulate the + or - operation. I haven't read far enough in the Elixir book yet to learn whether an anonymous function can somehow call itself. Can it? Nov 5, 2013 at 16:59
1

I think regex's are not a great idea for this job. Our problem can be reduced to "the absolute value of the difference between every number should only be one", Simply:

irb(main):052:0> s
=> "2345678"
irb(main):053:0> pairs = s.chars.zip(s[1..10].chars).select {|i| i[0] and i[1]}
=> [["2", "3"], ["3", "4"], ["4", "5"], ["5", "6"], ["6", "7"], ["7", "8"]]
irb(main):054:0> pairs.all? {|i| (i[0].to_i - i[1].to_i).abs == 1}
=> true

The rest of the requirements can be implemented via simple checks like "23647".chars.uniq!.

Edit: No need for checks, if the set have repeating numbers, our main requirement fails too.

5
  • 1
    I learned about each_cons from the link in the first comment on my original question. Using that, your second line could be pairs = s.chars.each_cons(2). This isn't quite the same because pairs is now an enumerator instead of an array. However, the enumerator supports the call to all?. Oct 24, 2013 at 16:13
  • However, two nits: 1. A single digit appears to true. And 2. "121" appears to be valid, but should fail for the purposes of the original question. It appears that a combination of these two lines should do the trick: s.chars.each_cons(2).all? {|c, d| c.ord - d.ord == 1} and s.chars.each_cons(2).all? {|c, d| d.ord - c.ord == 1}. And there's probably a way to DRY those up. Oct 24, 2013 at 16:20
  • Try this version: [-> ary { ary }, -> ary { ary.reverse }].each { |lambda| return 'Number is sequential' if num_string.chars.each_cons(2).map(&lambda).all? { |c, d| c.ord - d.ord == 1 } } if num_string.length > 1. Insert line-breaks to taste. ;-) (Can't have multi-line comments here, apparently.) Oct 24, 2013 at 17:43
  • This version is slower than some of the options posted by others above (about 3.25 seconds for my test loop vs 2.0 seconds for some other implementations). I would hazard a guess that it is slower because it manipulates all the characters in the string before beginning to test for sequentiality, while other versions manage to fail the test and return after considering only the first couple of characters. Oct 24, 2013 at 17:51
  • Agreed. After seeing other solutions, my solution is the least elegant one. but I think with each_cons, method you mentioned, this could be written more elegantly, since our zip` function is not so effective. I'll try to write a better version when I go home.
    – utdemir
    Oct 24, 2013 at 19:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.