2010-11-22 43 views
7

我有一組數字,例如php在一組數字中的重要性

$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是最inportant,其次是1,然後7等。注意,輸出,完全是無中生有,但跡象表明,4應該是給最重要的。我相信我想要某種線性解決方案。

+1

你可以添加一些實際的數字?根據什麼規則,相關性如何得到改善? – 2010-11-22 16:37:41

+0

我不確定我缺少什麼,我列出了一組數字,在我的問題中,左邊的數字是最重要的,隨着序列變長,重要性降低。 – Lizard 2010-11-22 16:41:10

回答

2

這是更多的你在想什麼?答案基於stillstanding

$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
$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

這種算法是相當簡單的,但我認爲它實現你在找什麼。

既然你有上述的序列,它存儲在陣列稱爲$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;