0

I have an array of route elements (point1, point2, ...) to provide to a map engine. I don't know how many points I have. Each point is an array of possible addresses. I need to perform a check for every combination possible of these points, but only one successful check is required.

My array looks like something akin to:

$point[0] = array($address1, $address2, $adress3);
$point[1] = array($address1, $address2);
$point[2] = array($address1, $address2, $adress3, $adress4);
$point[n] = ...

I want to perform a test for combination: $point[0][0] - $point[1][0] - $point[2][0], $point[0][1] - $point[1][0] - $point[2][0], and so on ! :) The first successful test (route found) should end the function.

I'm trying to do something with recursion but have spent many hours on this without success.

4
  • So you have list of routes, each node is an address. What are you checking? Do you want to know if a set of address nodes is a route? Commented Mar 4, 2014 at 16:38
  • Longest match or shortest match or first match wins? Commented Mar 4, 2014 at 16:44
  • I have a first operation converting adresses string to adresses objects with latidute - longitude attributes. This first passage returns several possible addresses objects for each addresses strings. I need to check every addresses objects combinaisons until the map engine finds a valid route. Commented Mar 4, 2014 at 16:47
  • First match wins ! :) Commented Mar 4, 2014 at 16:47

1 Answer 1

4

If I got you right, you want to have a "cartesian product".

This is an example function for it:
It first checks, if there are any subvalues in one of the subarrays and then it creates an array with all possible arraycombinations and returns it.

<?php
function array_cartesian_product($arrays)
{
    $result = array();
    $arrays = array_values($arrays);
    $sizeIn = sizeof($arrays);
    $size = $sizeIn > 0 ? 1 : 0;
    foreach ($arrays as $array)
        $size = $size * sizeof($array);
    for ($i = 0; $i < $size; $i ++)
    {
        $result[$i] = array();
        for ($j = 0; $j < $sizeIn; $j ++)
            array_push($result[$i], current($arrays[$j]));
        for ($j = ($sizeIn -1); $j >= 0; $j --)
        {
            if (next($arrays[$j]))
                break;
            elseif (isset ($arrays[$j]))
                reset($arrays[$j]);
        }
    }
    return $result;
}
?>
Sign up to request clarification or add additional context in comments.

1 Comment

Wow thank you ! I was looking for something like that !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.