ruby 检查数组的所有元素是否在方向上交替

i5desfxk  于 11个月前  发布在  Ruby
关注(0)|答案(2)|浏览(75)

在Ruby中,我需要检查数组中的所有元素是否在方向上交替,即,前导和后继是否大于或小于每个元素。
给定以下数组,结果必须如所示

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

字符串
我想出了下面的代码,这似乎工作,但它的漂亮或简单的理解。

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


有什么建议可以简化检查?

tzcvj98z

tzcvj98z1#

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

字符串
现在让我们试着打印

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

h9a6wy2h

h9a6wy2h2#

.只是因为@Rajagopalan已经采取了each_cons

def alt(arr)
  return true if arr.size < 3
  prev = arr[1]<=>arr[0]
  return false if prev.zero?
  (2..arr.size-1).all? do |i|
    prev = -prev
    (arr[i]<=>arr[i-1]) == prev
  end
end

个字符

相关问题