Drill

ProblemsTypeScript › reporting

Bucket some readings

mediumreportingTypeScript

A chart needs counts per band rather than raw readings — how many orders fell between 0 and 9, 10 and 19, and so on.

histogram(values: list<int>, bucketSize: int) → map<string, int>

Solve it in the editor →

Where you start

function histogram(values: number[], bucketSize: number): Record<string, number> {
  
}

Worked examples

CallResult
histogram([0,5,10,15,23], 10){"0":2,"10":2,"20":1}
histogram([9,10], 10){"0":1,"10":1}
histogram([1,2,3], 1){"1":1,"2":1,"3":1}
histogram([1,2], 0){}

Hint

Integer-divide by the bucket size, multiply back, and that is the bucket name.

Reference solution in TypeScript
function histogram(values: number[], bucketSize: number): Record<string, number> {
  if (bucketSize <= 0) return {};
  const result: Record<string, number> = {};
  for (const v of values) {
    const k = String(Math.floor(v / bucketSize) * bucketSize);
    result[k] = (result[k] || 0) + 1;
  }
  return result;
}

The same problem in another language

More reporting problems in TypeScript