在 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
有什么建议如何简化检查吗?
现在让我们尝试打印
...只是因为@Rajagopalan 已经采取了
each_cons
,