My script is centred around the array $givenNumbers with a random amount of random numbers from 1-1000:
$givenNumbers = [383, 886, 777, 84, 327, 336, 505, 846, 729, 313, 857, 124, 895, 582, 545, 814, 367, 434, 364, 43, 750, 87, 808, 276, 178, 788, 584, 403, 651, 754, 399, 932, 60, 676, 368, 739, 12, 226, 586, 94, 539, 654, 999, 5, 24];
The array is sorted and all repetitions of elements are removed:
$givenNumbers = array_unique($givenNumbers);
sort($givenNumbers);
I then declare the variable $amount which is the amount of elements in $givenNumbers;
$amount = count($givenNumbers);
I now store all possible slices of the array in the array $slices by using loops:
$slices = [];
for ($i = 0; $i < $amount; $i++) {
for($j = 0; $j < $amount; $j++) {
array_push($slices, array_slice($givenNumbers, $i, $j));
}
}
Having stored all slices in $slices I want to find all possible combinations of ten slices which, if merged together, will contain all elements of $givenNumbers without any element appearing twice or more.
I tried to do this by looping through the keys of slices:
$combinations[]
for($i = 0; $i < $amount; $i++) {
for($j = $i+1; $j < $amount; $j++) {
for($k = $j+1; $k < $amount; $k++) {
for($l = $k+1; $l < $amount; $l++) {
for($m = $l+1; $m < $amount; $m++) {
for($n = $m+1; $n < $amount; $n++) {
for($o = $n+1; $o < $amount; $o++) {
for($p = $o+1; $p < $amount; $p++) {
for($q = $p+1; $q < $amount; $q++) {
for($r = $q+1; $r < $amount; $r++) {
$combStorer = [];
$placeholder = array_merge($slices[$i], $slices[$j], $slices[$k], $slices[$l], $slices[$m], $slices[$n], $slices[$o], $slices[$p], $slices[$q], $slices[$r]);
$placeholder = array_unique($placeholder);
if (count($placeholder) == $amount) {
array_push($placeholder, $slices[$i], $slices[$j], $slices[$k], $slices[$l], $slices[$m], $slices[$n], $slices[$o], $slices[$p], $slices[$q], $slices[$r]);
foreach ($placeholder as $comb) {
$combStorer[] = $comb;
}
$combinations[] = $combStorer;
}
}
}
}
}
}
}
}
}
}
}
This should basically find all combinations of ten arrays in slices which meet my requirement and store them in the form of a multidimensional array in $combinations.
However, when I open my live preview, I get a fatal error, since the maximum execution of 30 seconds has been exceeded.
Several users have brought to my attention that this method is too convoluted and that there is definitely a better solution.
Could anyone suggest a more efficient solution?
$amountto the power of 10. Even if$amountis just 2, that is 1024 times. If$amountis 3, it will run 59,049 times. For bigger values this will increase vastly. So it is hardly surprising that your script is timing out, and not surprising at all that removing a couple of the loops (so it only runts n^8 times instead of n^10) makes a huge difference. You need to find a more efficient way of doing whatever it is that you are trying.$amountand check.$amountvalue. Also, try to increase the execution time.