Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS 

Split array into smaller arrays of equal size

Split an array of elements into a set of smaller arrays of equal size. Extra elements are preferentially assigned to earlier arrays. If there are no elements in a given returned array it will be [] (empty array)

# use as standalone function
def chunk_array(array, pieces=2)
  len = array.length;
  mid = (len/pieces)
  chunks = []
  start = 0
  1.upto(pieces) do |i|
    last = start+mid
    last = last-1 unless len%pieces >= i
    chunks << array[start..last] || []
    start = last+1
  end
  chunks
end

# use as array.chunk
class Array
  def chunk(pieces=2)
    len = self.length;
    mid = (len/pieces)
    chunks = []
    start = 0
    1.upto(pieces) do |i|
      last = start+mid
      last = last-1 unless len%pieces >= i
      chunks << self[start..last] || []
      start = last+1
    end
    chunks
  end
end



Examples of use:

>> chunk_array [1,2,3,4,5,6], 2
=> [[1, 2, 3], [4, 5, 6]]

>> chunk_array [1,2,3,4,5,6], 3
=> [[1, 2], [3, 4], [5, 6]]

>> chunk_array [1,2,3,4,5,6], 4
=> [[1, 2], [3, 4], [5], [6]]

>> chunk_array [1,2,3,4,5,6,7,8,9,10], 4
=> [[1, 2, 3], [4, 5, 6], [7, 8], [9, 10]]

>> chunk_array [1,2,3], 4
=> [[1], [2], [3], []]

>> chunk_array [], 2
=> [[], []]


if you prefer the second form (more ruby-ish, but not always appropriate)

>> [1,2,3,4,5,6,7,8,9,10].chunk
=> [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]

>> [1,2,3,4,5,6,7,8,9,10].chunk 3
=> [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]


This is handy when used with a splat because you can do things like:

left, right = *chunk_array(all,2)

Database connection chunk

mysql_select_db($database_conname, $conname);

$query_name = "SELECT * FROM tablename ORDER BY column DESC LIMIT 0, 10";
$name = mysql_query($query_name, $conname) or die(mysql_error());
$row_name = mysql_fetch_assoc($conname);
$totalrows_name = mysql_num_rows($conname);

Split String into roughly equal-sized chunks.

Split a string into an array of roughly equal sized chunks based on a string or regular expression delimiter.
Delimiter is preserved in output.

class String
  def chunk_string(average_segment_size = 40, sclice_on = /\s+/)
    out = []
    slices_estimate = self.size.divmod(average_segment_size)
    slice_count = (slices_estimate[1] > 0 ? slices_estimate[0] + 1 : slices_estimate[0])
    slice_guess = self.size / slice_count
    previous_slice_location = 0
    (1..slice_count - 1).each do
      |i|
      slice_location = self.nearest_split(slice_guess * i, sclice_on)
      out << self.slice(previous_slice_location..slice_location)
      previous_slice_location = slice_location + 1
    end
    out << self.slice(previous_slice_location..self.size)
    out
  end

  def nearest_split(slice_start, slice_on)
    left_scan_location  = (self.slice(0..slice_start).rindex(slice_on)).to_i
    right_scan_location = (self.slice((slice_start+1)..self.size).index(slice_on)).to_i + slice_start
    ((slice_start - left_scan_location) < (right_scan_location - slice_start) ? left_scan_location : right_scan_location)
  end
end

chunk function

    split: chunk: segment: func [  ; subdivide ?
        {See: CLOS pg. 937. Not that mine works the same, but that was
        the inspiration.}
        series [series!]
        size   [integer!] "The size of the chunks (last chunk may be shorter)"
        /into  "split into a set number (size) of chunks (last chunk may be longer than others)."
        /local ct cur-piece result
    ][
        ct: either into [size] [round/down divide length? series size]
        if into [size: to-integer divide length? series size]
        result: copy []
        if zero? size [return result]
        parse series [
            ct [
                copy cur-piece size skip (append/only result cur-piece) mark:
            ]
        ]
        if any [into  not zero? remainder length? series size] [
            cur-piece: copy mark
            either into
                [append last result cur-piece]
                [append/only result cur-piece]
        ]
        result
    ]
« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS