Php value of a number in a set of numbers

I have a set of numbers, for example.

$input = array(1, 4, 7, 4, 9, 4, 8, 6, 2, 8, 7, 7, 4, 5, 3); 

I am trying to determine the importance of each number based on the following rule:

As the sequence gets longer, the numbers become less significant, and every time a number is mentioned, it improves relevance (how much it depends on its position in the sequence).

I expect something like:

 Array( '4' => 90% '1' => 75% '7' => 60% .... ) 

So 4 is the most important, followed by 1, then 7, etc. Please note that the output is completely fabricated, but gives an indication that 4 should be the most important. I think I want some kind of linear solution.

+7
algorithm php numbers
source share
3 answers

Is that more than what you were thinking? Answer based on sustained

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

result:

 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
source share
 $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); 

Result:

 Array ( [1] => 15 [4] => 5040 [7] => 260 [9] => 11 [8] => 54 [6] => 8 [2] => 7 [5] => 2 [3] => 1 ) 
+2
source share

This algorithm is pretty simplistic, but I think it does what you are looking for.

Given that you have the sequence described above and it is stored in an array named $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; 
+1
source share

All Articles