Home > Software design >  Implement an algorithm to summarize the number of items within buckets of ranges
Implement an algorithm to summarize the number of items within buckets of ranges

Time:09-17

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?

CodePudding user response:

Your code seems to rely on buckets being both non overlapping AND adjacent.

The code below only requires that each "bucket" array be in ascending order. As it is (with the "break" commented) it doesn't require the numbers to be in any order, and the buckets can overlap, etc.

HTH

function summarize(array, buckets) {
 
    const results = new Array(buckets.length).fill(0);
    for (i in array) {
        for (j in buckets) {
            if (array[i] >= buckets[j][0] && array[i] <= buckets[j][1]) {
                results[j]  ;
                // break;
            }
        }
    }

    return results;
}

CodePudding user response:

summarize=(array,buckets)=>buckets.map(x=>array.filter(y=>y>=x[0]&&y<=x[1]).length)
  • Related