Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #
- # Challenge/Array_gather.rb
- # by IceDragon
- # dc 28/05/2013
- # dm 28/05/2013
- # vr 1.0.0
- # Aim: Write an Array method which groups elements based on condition
- # EG. if an array [1,2,3,4,1,3,5,6,7,4,1,9,0] was given
- # it'd return [1,1,1],[2],[3,3],[4,4],[5],[6],[7],[9],[0]
- # Completion Time: 30 Minutes
- array = [1,2,3,4,1,3,5,6,7,4,1,9,0]
- module Enumerable
- ##
- # group_by { |a, b| condition_for_grouping }
- def group_by
- result = []
- src = dup
- while (x = src.shift)
- result.push((a = []).push(x))
- src.reject! { |y| (a.push(y); true) if yield(x, y) }
- end
- return result
- end
- ##
- # gather
- def gather(&block)
- sort.group_by(&(block || (->(a, b){ a == b })))
- end
- end
- if $0 == __FILE__
- p array.gather
- end
Advertisement
Add Comment
Please, Sign In to add comment