Last active
December 17, 2015 21:39
-
-
Save SteveBenner/5676588 to your computer and use it in GitHub Desktop.
Subdivide a list into sub-lists of specified length
This file contains 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
# @param [Array<Integer>] List of sizes of the partitions self will be subdivided into | |
# @return [Object] Array containing self divided into one or more sub-arrays of size n | |
# @example | |
# [1,2,3].subdv [1] #=> [[1]] | |
# [1,2,3].subdv [3] #=> [[1,2,3]] | |
# [1,2,3].subdv [1,2] #=> [[1],[2,3]] | |
# [1,2,3].subdv [1,2] #=> [[1],[2,3]] | |
# [1,2,3].subdv [1,1,1] #=> [[1],[2],[3]] | |
# [1,2,3].subdv [1,2,1] #=> [[1],[2,3],[]] | |
def subdv(arr) | |
arr.reduce([]) { |ret, n| ret << self.slice!(0..n-1) } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment