locrizak
locrizak

Reputation: 12281

Making number ranges adapt to the smallest and largest numbers

I have two numbers (for this example lets say 695 is the smallest and 36000 is the largest). Currently once I know the min and the max I divide the difference by ten and then cycle it through a loop to crate the ranges. It looks something like this:

$min = (int)$min-1;
$max = (int)$max;
$diff = ($max - $min) / 10;
$range = array();
for ( $i=1; $i<10; $i++){
  $range[] = array(
    "low"=>($i==1? $min: ($i*$diff) + $min),
    "high"=>($i+1)*$diff + $min
  );
}

This works great when the numbers are 695-36000. When the numbers get close together it becomes a little cumbersome to have 10 ranges. For example, the min is 34000 and the max is 36000 the ranges would be 34000-34200, 34200-34400, etc, etc.

Ideally if 695-36000 is 10 different ranges than 34000-36000 would be one range.

What would be an easy way to calculate how many ranges should show up and what those ranges should be?

Upvotes: 1

Views: 158

Answers (1)

ghbarratt
ghbarratt

Reputation: 11711

Here is something to consider:

$diff = ($max - $min) / 10;
$range_max = 2000;
if($diff>$range_max) $range_size = $range_max;
else $range_size = $diff;
$creep = ($max-$min-$range_size)/9-$diff;

$range = array();
for($i=0; $i<10; $i++) {
  $range[] = array (
    'low'  => (int)(($diff+$creep)*$i+$min),
    'high' => (int)(($diff+$creep)*$i+$min+$range_size)
  );  
}

Upvotes: 1

Related Questions