2022-09-18

Implement an algorithm to summarize the number of items within buckets of ranges

I am trying to write a function that takes an array of numbers (always ascendingly sorted) and an array of buckets where each bucket is a tuple (array of two items) that represents a range (no overlaps). Every adjacent tuple only diff by 1. For example, [[0, 59], [60, 90]]. And they are always sorted.

For example,

summarize( [0, 10, 60, 120],[[0, 59], [60, 90]]) gives us [2, 1] because within [0, 59] there are two elements 0 and 10 and between [60, 90] there is one element 60.

Here is my attempt:

function summarize(array, buckets) {
  let i = 0
  const results = Array.from({ length: buckets.length }, () => 0)
  for (const item of array) {
    if (item >= buckets[i][0] && item <= buckets[i][1]) results[i]++
    else if (item > buckets[i][1] && i !== buckets.length - 1) {
      if (item <= buckets[i + 1][0]) {
        results[i + 1]++
        i++
        if (i === buckets.length) break
      }
    }
  }

  return results
}

The code seems to be working but it looks not clean and brittle. I wonder if there is another way to do it?



No comments:

Post a Comment