Created
September 1, 2011 14:46
-
-
Save nwjsmith/1186320 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
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 |
Congrats, you have won the trophy. Now, you just to get better in FIFA,
-D...
Leandro.
On 11-09-01 2:57 PM, "thuva" ***@***.*** wrote:
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 :-)
``` ruby
def chunk(arr)
arr.inject([]) {|c, v| (v == (c.last || []).last) ? (c.last || []) << v : c
<< [v]; c}
end
```
This email and any files transmitted with it are confidential and intended solely for the recipient(s). If you are not the named addressee you should not disseminate, distribute, copy or alter this email. Any views or opinions presented in this email are solely those of the author and might not represent those of Score Media Inc. or any of its affiliates. Warning: Although Score Media Inc. has taken reasonable precautions to ensure no viruses are present in this email, the company cannot accept responsibility for any loss or damage arising from the use of this email or attachments.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 :-)