PHP 中数字范围的计算
首先,感谢您花时间阅读我的问题。
我正在尝试编写脚本,但遇到了一个很难解决的问题。我正在处理一对数字(例如 1000 和 2000),并且我有一个数字对数组:
$pairs = array(
array(800, 1100),
array(1500, 1600),
array(1900, 2100)
)
我想要找到的是如何获取数字对未涵盖的范围(介于 1000 和 2000 之间) 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)
)
您知道执行此操作的最佳方法是什么吗?
先感谢您。
and first of all, thank you for taking the time to read my question.
I am trying to write a script, and I've come across an issue which I am finding hard to solve. I am working with a pair of numbers (for example, 1000 and 2000), and I have an array of pairs of numbers:
$pairs = array(
array(800, 1100),
array(1500, 1600),
array(1900, 2100)
)
What I am trying to find, is how to get the ranges not covered by the number pairs, between 1000 and 2000. In this example, 1000-1100 is covered by array(800, 1100), 1500-1600 is covered by array(1500, 1600) and 1900-2000 is covered by array(1900, 2100), which leaves me with 1101-1499 and 1599-1899 left to cover. I hope I am being clear enough.
What I am wondering is how I would make PHP return to me an array of the ranges not covered by the $pairs variable. In this example it would return:
array(
array(1101, 1499),
array(1599, 1899)
)
Do you have any idea what would be the best way to do this?
Thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,首先你必须定义问题:
如果对未排序,请首先对它们进行排序:
如果允许重叠范围,请将对列表转换为不重叠的集合。这里有一个关于如何做到这一点的建议:
现在不应该有任何重叠的对,因此问题变得更简单,因为您还得到了一个排序数组。
希望有帮助。
Well, firstly you have to define the problem:
If pairs aren't sorted, first sort them:
If overlapping ranges are allowed, transform the list of pairs to a non-overlapping set. Here's one suggestion on how to do that:
Now there shouldn't be any overlapping pairs so the problem becomes a little simpler as you've also got a sorted array.
Hope that helps.
我会做类似的事情:
这只是一个想法,但重点是:
假设您有一个大细分市场(从 1000 到 2000 个)和一个小细分市场。你想要得到大的那些未被小的覆盖的每一部分。想象一下你有一支笔!
初始化开始。迭代您拥有的每个“小部分”。如果你(严格地)在开始之后,那么就会有一个“洞”,所以你必须记住从开始到当前片段的开头。
希望这会有所帮助,并且这是正确的!
I would do something like that:
This is only an idea, but here is the point:
Consider you have a big segment (from 1000 to 2000) and small one. You want to get each segments of the big one that are not covered by the small one. Imagine you have a pen!
Init the beginning. Iterate on each "small segment" you have. If you are after (strictly) the beginning, then there is a "hole", so you must memorise than from begin to the beginning of the current segment.
Hope this helps, and that this is correct!
找出数组差异
有关我们稍后将使用的集合的元数据:
最终输出:
结果:
Find the array difference
Metadata about the sets we'll use later:
Final output:
Result: