我正在搜索算法来解决以下问题:
我有一组数字
(e.g 100,74,104,76,29,79,98,33,201)
我希望将彼此相邻的数字分组(相差x)
例如x = 10应该输出:
[(100,104,98) (74,76,79) (33,29) (201)]
不幸的是,我不知道该怎么做。
编辑:我有很多创意。算法不一定非常有效,只需要正常工作。
其中一个是:
- A) Picking first number, comparing its size with all the other numbers
- B) If the condition is complied, saving it in another set and deleting it from the input set
- C) Select the next element that isn't deleted and Start at A (Proceed until input set is empty)
您怎么看?
答案 0 :(得分:3)
这是我的第一张照片(来自评论)。我会编辑这篇文章,因为我会有更好的想法。
算法:
Input (a) a list L (b) a number x, the maximum gap
1) Sort the list
2) Take as many elements from the list as you can without exceeding the gap
3) Create a new group
4) If there are no more elements in the list, you're done, otherwise to to step 2.
示例:
Input: L = [100,74,104,76,29,79,98,33,201], x = 10
Sorted: [29, 33, 74, 76, 79, 98, 100, 104, 201]
Output: [[29, 33], [74, 76, 79], [98, 100, 104], [201]]
因为我注意到你使用的是PHP,所以这是PHP中的一个实现:
function cluster($arr, $x)
{
$clusters = array();
if(count($arr) == 0)
return $clusters;
sort($arr);
$curCluster[0] = array_shift($arr);
while(count($arr) > 0) {
$cur = array_shift($arr);
if($cur - $curCluster[0] < $x)
array_push($curCluster, $cur);
else {
array_push($clusters, $curCluster);
$curCluster = array($cur);
}
}
if(count($curCluster) != 0)
array_push($clusters, $curCluster);
return $clusters;
}