在PHP中计算数字范围

3

首先,感谢您抽出时间阅读我的问题。

我正在尝试编写一个脚本,但遇到了一个难以解决的问题。我正在处理一对数字(例如1000和2000),并且我有一组数字对的数组:

$pairs = array(
    array(800, 1100),
    array(1500, 1600),
    array(1900, 2100)
)

我要找的是如何获取1000到2000之间未被数字对覆盖的范围。在这个例子中,1000-1100被数组(800, 1100)覆盖,1500-1600被数组(1500,1600)覆盖,1900-2000被数组(1900,2100)覆盖,这意味着1101-1499和1599-1899仍未覆盖。希望我表述清楚了。
我想知道如何让PHP返回一个未被$pairs变量覆盖的范围数组。在这个例子中,它会返回:
array(
    array(1101, 1499),
    array(1599, 1899)
)

你有什么想法来最好地完成这个任务吗?

提前感谢你。

3个回答

4

首先,你需要定义问题:

  1. 这些对是否已排序?
  2. 这些对是否重叠?
  3. 你想要找到特定范围的缺失区间(看起来是这种情况)?

如果这些对没有排序,首先对它们进行排序:

usort($pairs, 'cmp_pair');

function cmp_pair($a, $b) {
  if ($a[0] == $b[0]) {
    if ($a[1] == $b[1]) {
      return 0;
    } else {
      return $a[1] < $b[1] ? -1 : 1;
    }
  } else {
    return $a[0] < $b[0] ? -1 : 1;
  }
}

如果允许重叠的范围,请将这个范围对列表转换为一个不重叠的集合。以下是如何实现的建议:

$prev = false;
$newpairs = array();
foreach ($pairs as $pair) {
  if ($prev) {
    // this also handles the case of merging two ranges
    // eg 100-199 with 200 to 250 to 100-250
    if ($prev[1] >= $pair[0]-1) {
      $prev = array($prev[0], max($prev[1], $pair[1]));
    } else {
      $newpairs[] = $prev;
    }
  }
  $prev = $pair;
}
$pairs = $newpairs;

现在不应该有任何重叠的对,因此问题变得更简单,因为您还拥有一个排序后的数组。
function missing($start, $end, $pairs) {
  $missing = array();
  $prev = false;
  foreach ($pairs as $pair) {
    // if the current pair starts above the end, we're done
    if ($pair[0] > $end) {
      break;
    }

    // we can ignore any pairs that end before the start
    if ($pair[1] < $start) {
      continue;
    }

    // if the pair encompasses the whole range, nothing is missing
    if ($pair[0] <= $start && $pair[1] >= $end) {
      break;
    }

    // if this is our first overlapping pair and it starts above
    // the start we can backfill the missing range
    if ($pair[0] > $start && !$missing) {
      $missing[] = array($start, $pair[0]);
    }

    // compare this pair to the previous one (if there is one) and
    // fill in the missing range
    if ($prev) {
      $missing[] = array($prev[1]+1, $pair[0]-1);
    }

    // set the previous
    $prev = $pair;
  }

  // if this never got set the whole range is missing
  if (!$prev) {
    $missing[] = array($start, $end);

  // if the last overlapping range ended before the end then
  // we are missing a range from the end of it to the end of
  // of the relevant range
  } else if ($prev[1] < $end) {
    $missing[] = array($prev[1]+1, $end);
  }

  // done!
  return $missing;
}

希望这能有所帮助。

1
这个答案对我非常有效,谢谢 :) 我唯一需要纠正的是 "if ($prev)..." 应该放在 if ($pair[0} > $start && !$missing) 之前,因为对于 800-1100,函数只设置了 $prev,这意味着当它到达第二对时,它仍然认为它是第一对(因此从 1000-1500 的所有内容都被视为缺失)。非常感谢您的帮助,cletus :) - Bruno De Barros

0
我会这样做:
begin = 1000
end   = 2000
uncovered = ()
foreach pairs as pair
  if (pair[0] > begin)
    push (uncovered, begin, pair[0])
    begin = pair[1]
  end if
end foreach

这只是一个想法,但关键在于: 考虑你有一个大段(从1000到2000)和一个小段。你想要获取大段中每个未被小段覆盖的片段。想象一下你有一支笔!

从开始初始化。迭代每个你拥有的“小段”。如果你在当前段的开始之后(严格地),那么就会有一个“洞”,所以你必须记住从开始到当前段的开始。

希望这可以帮助你,并且这是正确的!


0
// your original arrays of integers
$pairs = array(
    array(800, 1100),
    array(1500, 1600),
    array(1900, 2100)
);

// first, normalize the whole thing into a giant list of integers that
// are included in the array pairs, combine and sort numerically
$numbers_in_pairs = array();
foreach($pairs as $set) {
    $numbers_in_pairs = array_merge($numbers_in_pairs, range($set[0], $set[1]));
}
sort($numbers_in_pairs);

// find the min
$min = $numbers_in_pairs[0];

// find the max
$max = $numbers_in_pairs[count($numbers_in_pairs)-1];

找出数组的差异。
// create an array of all numbers inclusive between the min and max
$all_numbers = range($min, $max);

// the numbers NOT included in the set can be found by doing array_diff
// between the two arrays, we need to sort this to assure no errors when
// we iterate over it to get the maxes and mins
$not_in_set = array_diff($all_numbers, $numbers_in_pairs);
sort($not_in_set);

我们稍后将使用的集合的元数据:

// gather metadata about the numbers that are not inside the set
// $not_in_set_meta['min'] = lowest integer
// $not_in_set_meta['max'] = highest integer
// $not_in_set_meta['mins'] = min boundary integer
// $not_in_set_meta['maxes'] = max boundary integer
$not_in_set_meta = array();
for($i=0;$i<count($not_in_set);$i++) {
    if ($i == 0) {
        $not_in_set_meta['min'] = $not_in_set[$i];
        $not_in_set_meta['mins'][] = $not_in_set[$i];
    } else if ($i == count($not_in_set)-1 ) {
        $not_in_set_meta['max'] = $not_in_set[$i];
        $not_in_set_meta['maxes'][] = $not_in_set[$i];
    } else {
        // in the event that a number stands alone
        // that it can be BOTH the min and the max
        if (($not_in_set[$i+1] - $not_in_set[$i]) > 1) {
            $not_in_set_meta['maxes'][] = $not_in_set[$i];
        }
        if (($not_in_set[$i] - $not_in_set[$i-1]) > 1) {
            $not_in_set_meta['mins'][] = $not_in_set[$i];
        }
    }
}

最终输出:

// The final variable which we'll dump the ranges not covered into:
$non_sets = array();

while(count($not_in_set_meta['mins']) > 0 && count($not_in_set_meta['maxes'])) {
    $non_sets[] = array(array_shift($not_in_set_meta['mins']), 
                        array_shift($not_in_set_meta['maxes']));
}
// print it out:
print var_export($non_sets);

结果:

array (
  0 => 
  array (
    0 => 1101,
    1 => 1499,
  ),
  1 => 
  array (
    0 => 1601,
    1 => 1899,
  ),
)

?>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接