Skip to content

Instantly share code, notes, and snippets.

@hoguej
Created June 6, 2013 01:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hoguej/5718646 to your computer and use it in GitHub Desktop.
Save hoguej/5718646 to your computer and use it in GitHub Desktop.
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]]
@bostonaholic
Copy link

Here's my implementation. Just a bit shorter. LMK!

# DISCLAIMER: I did not perf test this.
def pieces_two(count)
  buckets = []
  offset = 0
  count.times do |c|
    buckets << self[offset..(self.size-1)].take(self.size / count)
    offset += (self.size / count)
  end
  buckets
end

a = [1,2,3,4,5,6,7,8,9,10]
a.pieces_two(2) #[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
a.pieces_two(5) #[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]

What do you want to do with this scenario?

a.pieces(3)     #[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
a.pieces_two(3) #[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

@hoguej
Copy link
Author

hoguej commented Jun 6, 2013

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.

@bostonaholic
Copy link

@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