Basically I want to create a historical route in my app and I tried SplDoublyLinkedList
, but I failed.
Now I decided to just use an array.
Suppose there is an array $array = [0,1,2,3];
. I want to generate all sequences with the following conditions.
$result = [ [ 'sequence' => [0,1], 'start' => 0, 'finish' => 1, 'via' => 'direct' 'transit' => null ], [ 'sequence' => [0,1,2], 'start' => 0, 'finish' => 2, 'via' => 'transit', 'transit' => [1] ], [ 'sequence' => [0,1,2,3], 'start' => 0, 'finish' => 3, 'via' => 'transit', 'transit' => [1,2] ], [ 'sequence' => [1,2], 'start' => 1, 'finish' => 2, 'via' => 'direct' 'transit' => null ], [ 'sequence' => [1,2,3], 'start' => 1, 'finish' => 3, 'via' => 'transit' 'transit' => [2] ], [ 'sequence' => [2,3], 'start' => 2, 'finish' => 3, 'via' => 'direct' 'transit' => null ], ];
Advertisement
Answer
You can reach the desired result by using an outer and an inner loop:
$result = []; $array = [0, 1, 2, 3]; $arrayCount = count($array); for ($i = 0; $i < $arrayCount - 1; $i++) { for ($j = 0; $j < $arrayCount - $i - 1; $j++) { $arr = array_slice($array, $i, $j + 2); $count = count($arr); $direct = $count === 2; $result[] = [ 'sequence' => $arr, 'start' => $arr[0], 'finish' => $arr[$count - 1], 'via' => $direct ? 'direct' : 'transit', 'transit' => $direct ? null : array_slice($arr, 1, $count - 2) ]; } }
If you intend to generate many sequences and you must consider memory usage, then you can also use a generator:
function sequenceGenerator(array $array): iterator { $arrayCount = count($array); for ($i = 0; $i < $arrayCount - 1; $i++) { for ($j = 0; $j < $arrayCount - $i - 1; $j++) { $arr = array_slice($array, $i, $j + 2); $count = count($arr); $direct = $count === 2; yield [ 'sequence' => $arr, 'start' => $arr[0], 'finish' => $arr[$count - 1], 'via' => $direct ? 'direct' : 'transit', 'transit' => $direct ? null : array_slice($arr, 1, $count - 2) ]; } } } foreach (sequenceGenerator([0, 1, 2, 3]) as $sequence) { // Do something here, maybe store it to db? var_dump($sequence); }