Advertisement
Guest User

Untitled

a guest
Mar 30th, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. def counts(nums, maxes)
  2. total = 0
  3. total_array = []
  4.  
  5. maxes.each do |m|
  6. nums.each do |n|
  7. if n <= m
  8. total += 1
  9. end
  10. end
  11.  
  12. total_array.push(total)
  13.  
  14. total = 0
  15. end
  16.  
  17. total_array
  18. end
  19.  
  20. nums = [2,10,5,4,8]
  21. maxes = [3,1,7,8]
  22.  
  23. print counts(nums, maxes) => # [1,0,3,4]
  24.  
  25. # Explanation:
  26.  
  27. # 1. maxes[0] >= nums[0]
  28. # 2. maxes[1] >= 0
  29. # 3. maxes[2] >= nums[0], nums[2], nums[3]
  30. # 4. maxes[3] >= nums[0], nums[2], nums[3], nums[4]
  31.  
  32. def counts(numbers, maxima)
  33. maxima.map do |max|
  34. numbers.count { |n| n <= max }
  35. end
  36. end
  37.  
  38. def counts(numbers, maxima)
  39. sorted = numbers.sort
  40. maxima.map do |max|
  41. index = sorted.bsearch_index { |n| n > max } # note inverted condition
  42. index || sorted.size
  43. end
  44. end
  45.  
  46. def counts(numbers, maxima)
  47. # create an array of [value, index] tuples, sorted (descending) by value
  48. pairs = maxima.each_with_index.sort_by(&:first).reverse
  49.  
  50. result = pairs.each_with_object({numbers: numbers, counts: []}) do |(max, index), memo|
  51. memo[:numbers].select! { |n| n <= max } # note in-place modification
  52. memo[:counts] << [memo[:numbers].size, index]
  53. end
  54.  
  55. result[:counts].sort_by(&:last).map(&:first)
  56. end
  57.  
  58. def counts(numbers, maxima)
  59. pairs = maxima.each_with_index.sort_by(&:first).reverse
  60.  
  61. # create a copy, since we'll be modifying it
  62. search_space = numbers.dup
  63.  
  64. counts = pairs.map do |max, index|
  65. search_space.select! { |n| n <= max } # note in-place modification
  66. [search_space.size, index]
  67. end
  68.  
  69. counts.sort_by(&:last).map(&:first)
  70. end
  71.  
  72. def counts(numbers, maxima)
  73. search_space = numbers.sort
  74. pairs = maxima.each_with_index.sort_by(&:first).reverse
  75.  
  76. result = pairs.each_with_object({search_space: search_space, counts: []}) do |(max, index), memo|
  77. count = memo[:search_space].bsearch_index { |n| n > max }
  78. count ||= memo[:search_space].size
  79. memo[:search_space].slice!(0, count)
  80. memo[:counts] << [count, index]
  81. end
  82.  
  83. result[:counts].sort_by(&:last).map(&:first)
  84. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement