Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # group by x
- # def time(a_proc)
- # start = Time.now
- # a_proc.call
- # puts Time.now - start
- # end
- #
- # time(Proc.new { code_here })
- # time(Proc.new { more_code_here })
- # {'John' => [..], 'Linda' => [..]}
- def group_by(data, key)
- data.each_with_object({ grouped_data: {}, problems: {} }) do |datum, acc|
- key_value = datum[key]
- if key_value == nil
- problem_key = "missing_#{key}"
- acc[:problems][problem_key] ||= []
- acc[:problems][problem_key] << datum
- next
- end
- acc[:grouped_data][key_value] ||= []
- acc[:grouped_data][key_value] << datum
- acc
- end
- end
- # p group_by([{ name: 'John' }, { name: 'Linda' }, { name: 'Linda' }, { a: 1 }], :name)
- # {:grouped_data=>{"John"=>[{:name=>"John"}], "Linda"=>[{:name=>"Linda"}, {:name=>"Linda"}]}, :problems=>{"missing_name"=>[{:a=>1}]}}
- # sliding window
- def sliding_window(list, count)
- (0..list.size - count).map do |idx|
- # if idx + count >= list.size
- list[idx...(idx + count)]
- end
- end
- p sliding_window([1, 2, 3, 4], 2)
- p sliding_window([1, 2, 3, 4], 3)
- # [[1, 2, 3], [2, 3, 4]]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement