Search code examples
ruby

Check if all elements of an array alternate in direction


In Ruby, I need to check if all the elements of an array alternate in direction, i.e., if the predecessor and successor are greater or lesser than each element.

Giving the following arrays, the outcome must be as indicated

[1,3,2,4,3]  # => true
[3,2,4,3,5]  # => true
[1,2,3,1,3]. # => false 
[1,2,2,1,3]. # => false

I came out with the following code, which seems to work, but it's pretty or simple to understand.

array.each_cons(2)     # get subsequent couple of items
  .map {|a,b| b-a}.    # get the difference between first and second
  .map {|n| n <=> 0}   # get the sign (-1/+1)
  .each_cons(2)        # get couple of signs
  .map {|a,b| a+b}     # sum each couple
  .uniq == [0]         # return true if all the couple are 0

Any suggestion how to simplify the check?


Solution

  • def alternate_direction?(arr)
      return true if arr.size < 3
      arr.each_cons(3) do |prev, curr, succ|
        return false unless (curr > prev && curr > succ) || (curr < prev && curr < succ)
      end
      true
    end
    

    Let us try to print now

    puts alternate_direction?([1,3,2,4,3])  # => true
    puts alternate_direction?([3,2,4,3,5])  # => true
    puts alternate_direction?([1,2,3,1,3])  # => false
    puts alternate_direction?([1,2,2,1,3])  # => false