我有一组数字,例如
$input = array(1, 4, 7, 4, 9, 4, 8, 6, 2, 8, 7, 7, 4, 5, 3);
我正在尝试根据以下规则计算每个数字的重要性:
随着序列越来越长,数字变得越来越不重要,每次提到一个数字,那么它将提高相关性(多少取决于它在 序列)。
我期待的是:
Array(
'4' => 90%
'1' => 75%
'7' => 60%
....
)
因此4是最重要的,然后是1然后是7等。请注意,输出是完全捏造的,但是表明4应该是最重要的。我相信我想要某种线性解决方案。
答案 0 :(得分:2)
$numbers=array(1, 4, 7, 4, 9, 4, 8, 6, 2, 8, 7, 7, 4, 5, 3);
$weight=array();
$count=count($numbers);
for ($i=0; $i<$count; $i++) {
if (!isset($weight[$numbers[$i]]))
$weight[$numbers[$i]]=1;
$weight[$numbers[$i]]*=$count-$i;
}
var_dump($weight);
结果:
Array
(
[1] => 15
[4] => 5040
[7] => 260
[9] => 11
[8] => 54
[6] => 8
[2] => 7
[5] => 2
[3] => 1
)
答案 1 :(得分:2)
这更像你在想什么?基于仍然存在的答案
$numbers = array(1, 4, 7, 4, 9, 4, 8, 6, 2, 8, 7, 7, 4, 5, 3);
$weight = array();
$count = count($numbers);
for ($i=0; $i<$count; $i++) {
if (!isset($weight[$numbers[$i]])) $weight[$numbers[$i]] = 1;
$weight[$numbers[$i]] += $count + pow($count - $i, 2);
}
$max = array_sum($weight);
foreach ($weight as &$w) {
$w = ($w / $max) * 100;
}
arsort($weight);
结果:
Array
(
[4] => 34.5997286296
[7] => 17.3677069199
[1] => 16.3500678426
[8] => 10.0407055631
[9] => 9.29443690638
[6] => 5.42740841248
[2] => 4.40976933514
[5] => 1.35685210312
[3] => 1.15332428765
)
答案 2 :(得分:1)
这个算法相当简单,但我认为它可以完成你想要的。
鉴于您拥有上述序列,并将其存储在名为$sequence
$a = array();
for($i=0;$i<count($sequence);$i++)
{
//calculate the relevance = 1/position in array
$relevance = 1/($i+1);
//add $relevance to the value of $a[$sequence[$i]]
if(array_key_exists((string)$sequence[$i],$a))
$a[(string)$sequence[$i]] += $relevance;
else
$a[(string)$sequence[$i]] = $relevance;
}
return $a;