How do I find the first two consecutive elements in my array of numbers?

前端 未结 5 788
长发绾君心
长发绾君心 2021-01-25 06:06

Using Ruby 2.4, I have an array of unique, ordered numbers, for example

[1, 7, 8, 12, 14, 15]

How do I find the first two elements whose differ

5条回答
  •  广开言路
    2021-01-25 06:52

    Here are three more ways.

    #1

    def first_adjacent_pair(arr)
      (arr.size-2).times { |i| return arr[i, 2] if arr[i+1] == arr[i].next }
      nil
    end
    
    first_adjacent_pair [1, 7, 8, 12, 14, 15] #=> [7,8]
    first_adjacent_pair [1, 7, 5, 12, 14, 16] #=> nil
    

    #2

    def first_adjacent_pair(arr)
      enum = arr.to_enum # or arr.each
      loop do
        curr = enum.next
        nxt = enum.peek
        return [curr, nxt] if nxt == curr.next
      end
      nil
    end
    

    enum.peek raises a StopIteration exception when the enumerator enum has generated its last element with the preceding enum.next. The exception is handled by Kernel#loop by breaking out of the loop, after which nil is returned. See also Object#to_enum, Enumerator#next and Enumerator#peek.

    #3

    def first_adjacent_pair(arr)
      a = [nil, arr.first] 
      arr.each do |n|
        a.rotate!
        a[1] = n
        return a if a[1] == a[0] + 1
      end
      nil
    end
    

    See Array#rotate!.

提交回复
热议问题