Skip to content

Instantly share code, notes, and snippets.

@nwjsmith
Created September 1, 2011 14:46
Show Gist options
  • Save nwjsmith/1186320 to your computer and use it in GitHub Desktop.
Save nwjsmith/1186320 to your computer and use it in GitHub Desktop.
describe '#chunk' do
def chunk(arr)
arr.inject([]) do |chunks, elem|
current_sequence = chunks.last || []
if elem == current_sequence.last
current_sequence << elem
else
chunks << [elem]
end
chunks
end
end
it 'chunks an array of equal elements into an array of one array' do
chunk([1,1]).should == [ [1,1] ]
end
it 'chunks an array of different elements into different arrays' do
chunk([1,2]).should == [ [1], [2] ]
end
it 'chunks an array with contiguous sets of elements into an array of arrays of those sets' do
chunk([1,1,1,2,2,1,1,2,2,2]).should == [ [1,1,1], [2,2], [1,1] , [2,2,2] ]
end
it 'chunks an array with an odd number of elements properly' do
chunk([1,1,1,2,2,1,1,2,2]).should == [ [1,1,1], [2,2], [1,1] , [2,2] ]
end
end
@lsantos
Copy link

lsantos commented Sep 1, 2011

this is my solution:

describe '#chunk' do
  def chunk(arr)
    c = arr.cycle
    c.next
    counter = 0

    arr.inject([[]]) do |results, element|
      counter += 1
      results.last << element

      if (element != c.next && counter < arr.length)
        results << []   
      end

      results
    end  

  end

  it 'chunks an array of equal elements into an array of one array' do
    chunk([1,1]).should == [ [1,1] ]
  end

  it 'chunks an array of different elements into different arrays' do
    chunk([1,2]).should == [ [1], [2] ]
  end

  it 'chunks an array with contiguous sets of elements into an array of arrays of those sets' do
    chunk([1,1,1,2,2,1,1,2,2,2]).should == [ [1,1,1], [2,2], [1,1] , [2,2,2] ]
  end

  it 'chunks an array with an odd number of elements properly' do
    chunk([1,1,1,2,2,1,1,2,2]).should == [ [1,1,1], [2,2], [1,1] , [2,2] ]
  end
end

@ffernand
Copy link

ffernand commented Sep 1, 2011

def chunk(arr):
    c = [[arr[0]]] if arr else [[]]
    for x in arr[1:]:
        if x in c[-1]: c[-1].append(x)
        else: c.append([x])
    return c

@sutherland
Copy link

Totally obfuscated one-liner:

def chunk(arr)
  arr.inject([[arr.shift]]) { |c, v| c.last.include?(v) ? c.last << v : c << [v]; c }
end

@thuva
Copy link

thuva commented Sep 1, 2011

Jonathan, I can't let you beat me (this is not FIFA). Here's my one-liner and it handles the case where the input is an empty array :-)

def chunk(arr)
  arr.inject([]) {|c, v| (v == (c.last || []).last) ? (c.last || []) << v : c << [v]; c}
end

@lsantos
Copy link

lsantos commented Sep 1, 2011 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment