Advertisement
Guest User

Untitled

a guest
Jun 18th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. # group by x
  2. # def time(a_proc)
  3. # start = Time.now
  4. # a_proc.call
  5. # puts Time.now - start
  6. # end
  7. #
  8. # time(Proc.new { code_here })
  9. # time(Proc.new { more_code_here })
  10.  
  11. # {'John' => [..], 'Linda' => [..]}
  12.  
  13. def group_by(data, key)
  14. data.each_with_object({ grouped_data: {}, problems: {} }) do |datum, acc|
  15. key_value = datum[key]
  16. if key_value == nil
  17. problem_key = "missing_#{key}"
  18. acc[:problems][problem_key] ||= []
  19. acc[:problems][problem_key] << datum
  20. next
  21. end
  22. acc[:grouped_data][key_value] ||= []
  23. acc[:grouped_data][key_value] << datum
  24. acc
  25. end
  26. end
  27.  
  28. # p group_by([{ name: 'John' }, { name: 'Linda' }, { name: 'Linda' }, { a: 1 }], :name)
  29. # {:grouped_data=>{"John"=>[{:name=>"John"}], "Linda"=>[{:name=>"Linda"}, {:name=>"Linda"}]}, :problems=>{"missing_name"=>[{:a=>1}]}}
  30.  
  31. # sliding window
  32. def sliding_window(list, count)
  33. (0..list.size - count).map do |idx|
  34. # if idx + count >= list.size
  35. list[idx...(idx + count)]
  36. end
  37. end
  38.  
  39. p sliding_window([1, 2, 3, 4], 2)
  40. p sliding_window([1, 2, 3, 4], 3)
  41. # [[1, 2, 3], [2, 3, 4]]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement