I tried shortening my question, but this is the best I could do. Since I guess it's pretty hard to understand what I need, I'll provide an example:
Say I have the following array:
$var = array(
array(1, 2, 3),
array(1, 3),
array(1, 2, 4, 3),
array(1, 3, 4)
);
What I want is to remove all arrays from $var
that have the first and last element the same as another array from $var
but have more elements than the latter.
So, the following arrays should be removed: (1, 2, 3)
and (1, 2, 4, 3)
because they both start with 1
and end with 3
and have more elements than (1, 3)
, which also starts and ends with 1
and 3
. (1, 3, 4)
should remain, because there is no other array which starts with 1
and ends with 4
and has fewer elements than it.
I am looking for the most efficient way of doing this, both in terms of memory and time. $var
may have up to 100 arrays, and each individual array may have up to 10 elements in it. I thought of using some kind of comparison between all two elements (for(i=0;...) for(j=i+1;...) complexCompareFunction();
), but I believe this isn't very efficient.
In general, yes, you are too worried about efficiency (as you wondered in another comment). Though PHP is not the most blisteringly-fast language, I would suggest building the most straightforward solution, and only worry about optimizing it or streamlining it if there is a noticeable issue with the end result.
Here is what I would do, off the top of my head. It is based off of ajreal's answer but hopefully will be easier to follow, and catch some edge cases which that answer missed:
// Assume $var is the array specified in your question
function removeRedundantRoutes( $var ){
// This line sorts $var by the length of each route
usort( $var, function( $x, $y ){ return count( $x ) - count( $y ); } );
// Create an empty array to store the result in
$results = array();
// Check each member of $var
foreach( $var as $route ){
$first = $route[0];
$last = $route[ count( $route ) - 1 ];
if( !array_key_exists( "$first-$last", $results ) ){
// If we have not seen a route with this pair of endpoints already,
// it must be the shortest such route, so place it in the results array
$results[ "$first-$last" ] = $route;
}
}
// Strictly speaking this call to array_values is unnecessary, but
// it would eliminate the unusual indexes from the result array
return array_values( $results );
}