Say that i have an array like this :
$arr_sequences =
array('00-02', '02-03', '03-07', '23-03', '03-23', '07-11', '11-10', '11-11');
How to sort the array so the values would look like this :
$arr_sequences =
array('00-02', '02-03', '03-23', '23-03', '03-07', '07-11', '11-11', '11-10');
If we look closely each value has an id (code) that's divided by -
For example :
$arr_sequences[2] = '03-07'; // '07' as last code, then search another value with '07' in front of the value
Then next index value shoud be
$arr_sequences[5] = '07-11'; // '07' front, then search '11' as next value
the goal is to sort the array without losing any length.
I have tried with tree algorithm, but I can't get it to work.
The crazy approach:
The PHP code
$arr_sequences = array('00-02', '02-03', '03-07', '23-03', '03-23', '07-11', '11-10', '11-11'); // Input
$permutations = permutations($arr_sequences); // Generating permutations
// Generating a regex
$n = count($arr_sequences);
$regex = '\d+';
for($i=1;$i<$n;$i++){
$regex .= '-(\d+)-\\'.$i;
}
$regex .= '-\d+';
$sorted = preg_grep('#'.$regex.'#', $permutations); // Filtering the permutations
sort($sorted); // re-index the keys
//generating the desired output
$output = array();
foreach($sorted as $key => $sample){
$temp = explode('-', $sample);
$c = count($temp); // Micro-optimization, yeaaaah!
for($i=0;$i<$c;$i+=2){
$output[$key][] = $temp[$i] . '-' . $temp[$i+1];
}
}
print_r($output); // printing
// Function from http://stackoverflow.com/a/14998162
function permutations($elements) {
if(count($elements)<2) return $elements;
$newperms= array();
foreach($elements as $key=>$element) {
$newelements= $elements;
unset($newelements[$key]);
$perms= permutations($newelements);
foreach($perms as $perm) {
$newperms[]= $element."-".$perm;
}
}
return $newperms;
}
The output
Array
(
[0] => Array
(
[0] => 00-02
[1] => 02-03
[2] => 03-23
[3] => 23-03
[4] => 03-07
[5] => 07-11
[6] => 11-11
[7] => 11-10
)
)
It seems that there was only one solution :p
A Brute Force way, in php. (Not tested):
<?php
$arr = array('00-02', '02-03', '03-07', '23-03', '03-23', '07-11', '11-10', '11-11');
function findMatches($i, $val_ignore, $arr) {
$arr_matches = array();
foreach($arr as $key => $val) {
$j = substr_replace($val, '', 2);
if (($i == $j) && ($val != $val_ignore))
$arr_matches[] = $val;
}
return $arr_matches;
}
$arr_sorted = array();
foreach($arr as $key => $val) {
$i = substr_replace($val, '', 0, 3);
if (!in_array($val, $arr_sorted)) $arr_sorted[] = $val;
$arr_sorted = array_merge($arr_sorted, findMatches($i, $val, $arr));
}
?>