Created
November 25, 2014 07:17
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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