Search code examples
phpnested-loops

Faster/Better method to compare related lists of data


There are two arrays with a ton of data in them. They both have the same keys though, just different values. Example:

Say you have two people and you want to do some calculations based on how they like fruit, but you don't want to compare the same fruits.

$person1 = array("Apple" => 10, "Pear" => 4, "Banana" => 8, "Pineapple" => 7, "Watermelon" => 7)

$person2 = array("Apple" => 6, "Pear" => 10, "Banana" => 6, "Pineapple" => 9, "Watermelon" => 3)

Now I want to compare all values, except when the fruits are the same. So,

Person 1    Person 2
Apple = 10  Pear = 10
Apple = 10  Banana = 6
Apple = 10  Pineapple = 9
...
Banana = 8  Apple = 6
Banana = 8  Pear = 10
Banana = 8  Pineapple = 9

Notice that I did Apple Banana and then Banana Apple for person 1 to person 2 because the calculated value could be different. So, if I did something like:

(Person 1 Key) * 2 + (Person 2 Key)

Then you could get:

10 * 2 + 6 = 26 for Person1["Apple"] and Person2["Banana"] and then

8 * 2 + 6 = 22 for Person1["Banana"] and Person2["Apple"]

Is there anyway to do this without using a nested array or something that's faster.


Edit

$calculatedValues = array();
$len = sizeof($person1);


$inc = 0;
for($i = 0; $i < $len; ++$i){
   for($j = 0; $j < $len; ++$j){
     if($i != $j){
       $calculatedValues[$inc] = $person1[i] * 2 + $person2[j];
       inc++;
     }
   }
}

Solution

  • No, nothing's going to be faster than a nested loop. Think about it some. You have to compare all of item A's things to all of item B's things to produce your list. If you nest a loop over person B's things in a loop over person A's things, how many total iterations will you make? Exactly as many as the pairs you have to compare. That's the minimum number of operations, so you can't do better.

    foreach ($person1 as $fruitA => $quantityA) {
      foreach ($person2 as $fruitB => $quantityB) {
        $calculatedValues[] = $quantityA * 2 + $quantityB;
      }
    }