Created
June 6, 2013 01:16
-
-
Save hoguej/5718646 to your computer and use it in GitHub Desktop.
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
class Array | |
def pieces( count ) | |
indexes = self.piece_indexes( count ) | |
indexes.map{ |index| self[*index] } | |
end | |
def piece_indexes( pieces_count ) | |
chunk_size = self.size / pieces_count | |
chunk_size = 1 if chunk_size < 1 | |
pieces_count = self.size if pieces_count > self.size | |
indexes = [] | |
(0..pieces_count - 1).each do |p| | |
start_index = p * chunk_size | |
indexes << [start_index, chunk_size] | |
end | |
return indexes | |
end | |
end | |
# usage | |
a = [1,2,3,4,5,6,7,8,9,10] | |
a.pieces(2) #[[1,2,3,4,5],[6,7,8,9,10]] | |
a.pieces(5) #[[1,2],[3,4],[5,6],[7,8],[9,10]] |
good question. we could just throw it onto the end of the last one...
but then, the last one can be as much as count - 1 extra items. that could be a big deal where n is big. the sub-arrays should be no more than 1 size different than any other... will have to think about that implementation, in the morning.
@saterus just schooled us all "Just stay in Enumerable"
def pieces(count)
self.each_slice(self.count / count).take(count)
end
The take(count)
at the end I added to remove the extra collections caused by irregular pieces like pieces(3)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's my implementation. Just a bit shorter. LMK!
What do you want to do with this scenario?