rinserepeat
rinserepeat

Reputation: 165

Sum absolute differences between indexes of matching values in two arrays

I have been reading through the manual to find a function that does what I want but I ended up doing it myself. I want to compare two arrays and calculate the difference between the keys. Or more practically analyse the difference in order of the values.

I have done this as follows, but I have a feeling this can be done better.

if anyone has an idea how to improve this please let me know becasue im eager to improve.

<?php
$goodarray = array(300,250,200,150,100);

$usersupliedarray = array(250,300,200,150,100); // first two spots are wrong

$score = count($goodarray);

foreach($usersupliedarray as $key => $value){

    $arraykey = array_search($value, $goodarray);

    $difference = abs($key-$arraykey);

    $score = $score + $difference;


    echo "$value $goodarray[$key] ($difference = $score) <hr />";

}

Upvotes: 1

Views: 138

Answers (1)

georg
georg

Reputation: 214949

array_map with a void callback can come in handy here, for example,

$a = array(300,250,200,150,100);
$b = array(250,300,200,150,100);

$faults = 0;
foreach(array_map(null, $a, $b) as $x)
    $faults += $x[0] != $x[1]; // x[0] is $a element, x[1] is $b

print $faults; // 2

UPD: if you want to compute distances between equal elements, and not just count differences, your original code looks just fine to me. One improvement which can be made is to get rid of inefficient array_search and to use an "inverted index" of the first array instead:

foreach($a as $pos => $val)
    $inv[$val] = $pos;

or just

$inv = array_flip($a);

and then

foreach($b as $pos => $val)
    $score += abs($pos - $inv[$val]);

Upvotes: 1

Related Questions