Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def counts(nums, maxes)
- total = 0
- total_array = []
- maxes.each do |m|
- nums.each do |n|
- if n <= m
- total += 1
- end
- end
- total_array.push(total)
- total = 0
- end
- total_array
- end
- nums = [2,10,5,4,8]
- maxes = [3,1,7,8]
- print counts(nums, maxes) => # [1,0,3,4]
- # Explanation:
- # 1. maxes[0] >= nums[0]
- # 2. maxes[1] >= 0
- # 3. maxes[2] >= nums[0], nums[2], nums[3]
- # 4. maxes[3] >= nums[0], nums[2], nums[3], nums[4]
- def counts(numbers, maxima)
- maxima.map do |max|
- numbers.count { |n| n <= max }
- end
- end
- def counts(numbers, maxima)
- sorted = numbers.sort
- maxima.map do |max|
- index = sorted.bsearch_index { |n| n > max } # note inverted condition
- index || sorted.size
- end
- end
- def counts(numbers, maxima)
- # create an array of [value, index] tuples, sorted (descending) by value
- pairs = maxima.each_with_index.sort_by(&:first).reverse
- result = pairs.each_with_object({numbers: numbers, counts: []}) do |(max, index), memo|
- memo[:numbers].select! { |n| n <= max } # note in-place modification
- memo[:counts] << [memo[:numbers].size, index]
- end
- result[:counts].sort_by(&:last).map(&:first)
- end
- def counts(numbers, maxima)
- pairs = maxima.each_with_index.sort_by(&:first).reverse
- # create a copy, since we'll be modifying it
- search_space = numbers.dup
- counts = pairs.map do |max, index|
- search_space.select! { |n| n <= max } # note in-place modification
- [search_space.size, index]
- end
- counts.sort_by(&:last).map(&:first)
- end
- def counts(numbers, maxima)
- search_space = numbers.sort
- pairs = maxima.each_with_index.sort_by(&:first).reverse
- result = pairs.each_with_object({search_space: search_space, counts: []}) do |(max, index), memo|
- count = memo[:search_space].bsearch_index { |n| n > max }
- count ||= memo[:search_space].size
- memo[:search_space].slice!(0, count)
- memo[:counts] << [count, index]
- end
- result[:counts].sort_by(&:last).map(&:first)
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement