Skip to content

Instantly share code, notes, and snippets.

@adi89
Created November 25, 2014 07:17
Show Gist options
  • Select an option

  • Save adi89/fdb5349e3adbefc15691 to your computer and use it in GitHub Desktop.

Select an option

Save adi89/fdb5349e3adbefc15691 to your computer and use it in GitHub Desktop.
Given an array of unsorted positive ints, write a function that finds runs of 3 consecutive numbers (ascending or descending) and returns the indices where such runs begin. If no such runs are found, return an empty array.
# jotted this quick
def consecutive(array)
index_collection = []
array.each_with_index do |integer, index|
if consecutive_forwards(array, integer, index) || consecutive_backwards(array, integer, index)
index_collection.push(index)
end
end
index_collection
end
def consecutive_backwards(array, integer, index)
(array[ index + 1 ] == integer - 1 ) && (array[ index + 2 ] == integer - 2)
end
def consecutive_forwards(array, integer, index)
(array[ index + 1 ] == integer + 1 ) && (array[ index + 2 ] == integer + 2)
end
consecutive([1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment