我有一个数组
my @stuff = (6.5,6.54,6.465,6.3,6.42,8.07370,8.1165,8.07612,7.61855,6.94927,6.94072,8.09707,6.94468,7.55948,6.93,7.51448,8.02872,6.89643,7.44893,6.92997,7.46780,7.96705,6.93785,6.928,7.51177,7.93443,6.92620,7.40470,7.90602,8.39247,6.95032,7.42932,7.917,6.95272,7.93688,8.42192,6.95255,7.45207,8.43418,7.42768,8.42152,6.9645);
我想把它分成一个较小的数组,其中类似的数字可以组合在一起而不指定数组的数量。我希望每个较小数组中的值不应超过0.5。
答案 0 :(得分:4)
这很简单。听起来像perl类中的赋值。 我不会详细介绍,但一个简单的解决方案就是对数组进行排序。然后迭代并检查当前元素和第一个元素之间的差异。只要当前元素与第一个元素的差值(delta)大于delta(0.5),就会将数组拆分到此位置。然后你再次使用缩短的数组。
如何做到这一点有很多变化。我相信你会想出一个聪明的人。
答案 1 :(得分:1)
my @stuff = (6.5,6.54,6.465,6.3,6.42,8.07370,8.1165,8.07612,7.61855,6.94927,6.94072,8.09707,6.94468,7.55948,6.93,7.51448,8.02872,6.89643,7.44893,6.92997,7.46780,7.96705,6.93785,6.928,7.51177,7.93443,6.92620,7.40470,7.90602,8.39247,6.95032,7.42932,7.917,6.95272,7.93688,8.42192,6.95255,7.45207,8.43418,7.42768,8.42152,6.9645);
my (%h, @g);
my @r = map {
my $el = $_;
my ($ref) = map { abs($_-$el) <=0.5 ? $h{$_} : () } @g;
if ($ref) { push @$ref, $_; }
else {
$h{$_} = [$_];
push @g, $_;
}
$ref ? () : $h{$_};
}
sort { $a <=> $b }
@stuff;
use Data::Dumper; print Dumper \@r;
输出
$VAR1 = [
[
'6.3',
'6.42',
'6.465',
'6.5',
'6.54'
],
[
'6.89643',
'6.9262',
'6.928',
'6.92997',
'6.93',
'6.93785',
'6.94072',
'6.94468',
'6.94927',
'6.95032',
'6.95255',
'6.95272',
'6.9645'
],
[
'7.4047',
'7.42768',
'7.42932',
'7.44893',
'7.45207',
'7.4678',
'7.51177',
'7.51448',
'7.55948',
'7.61855'
],
[
'7.90602',
'7.917',
'7.93443',
'7.93688',
'7.96705',
'8.02872',
'8.0737',
'8.07612',
'8.09707',
'8.1165',
'8.39247'
],
[
'8.42152',
'8.42192',
'8.43418'
]
];
答案 2 :(得分:0)