Created
August 3, 2021 22:52
-
-
Save guillaumebdx/a672a5c02253bd574e10987dd78b4ba4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // expected [3, 7, 8, 19] | |
| $data = [10, 11, 15, 22, 26, 27]; | |
| $possibilities = createPossibilities($data); | |
| $result = getResult($possibilities, $data); | |
| var_dump($result); | |
| //output array(4) { [0]=> int(3) [1]=> int(7) [2]=> int(8) [3]=> int(19) } | |
| function createPossibilities(array $data): array | |
| { | |
| $possibilities = []; | |
| for ($k=0; $k<count($data); $k++) { | |
| for ($i=1; $i<=100; $i++) { | |
| for ($j=1; $j<=100; $j++) { | |
| if ($i !== $j && $i + $j === $data[$k]) { | |
| $possibilities[$data[$k]][] = [$i, $j]; | |
| } | |
| } | |
| } | |
| } | |
| return $possibilities; | |
| } | |
| function getResult(array $possibilities, array $data): ?array | |
| { | |
| foreach ($possibilities[$data[0]] as $key => $paires) { | |
| foreach ($possibilities as $secondPaires) { | |
| foreach ($secondPaires as $pairesToMerge) { | |
| $probables = array_merge($paires, $pairesToMerge); | |
| if (isCorrect($data, $probables)) { | |
| return $probables; | |
| } | |
| } | |
| } | |
| } | |
| return null; | |
| } | |
| function isCorrect(array $inputs, array $probables): bool | |
| { | |
| $find = 0; | |
| foreach ($inputs as $number) { | |
| if (isThereAPair($probables, $number)) { | |
| $find += 1; | |
| } | |
| } | |
| return $find === count($inputs); | |
| } | |
| function isThereAPair(array $probables, int $number): bool | |
| { | |
| for ($i=0; $i<count($probables); $i++) { | |
| for ($j=0; $j<count($probables); $j++) { | |
| if ($probables[$i] + $probables[$j] === $number) { | |
| return true; | |
| } | |
| } | |
| } | |
| return false; | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment