I am trying to convert a function written in Javascript to PHP, but even though it is written the same and receiving the same input data it returns different results.
A little context. I am working on creating play days for a tournament in a dynamic way. The input data represents the clashes that will take place between the teams throughout the tournament
Thus
Given the following data
combinations = [
[ 'A', 'B' ], [ 'A', 'C' ],
[ 'A', 'D' ], [ 'B', 'C' ],
[ 'B', 'D' ], [ 'C', 'D' ],
[ 'C', 'D' ], [ 'B', 'D' ],
[ 'B', 'C' ], [ 'A', 'D' ],
[ 'A', 'C' ], [ 'A', 'B' ],
[ 'A', 'B' ], [ 'A', 'C' ],
[ 'A', 'D' ], [ 'B', 'C' ],
[ 'B', 'D' ], [ 'C', 'D' ]
]
Javascript
const getMatches = (combinations) => {
let matches = [];
let i = 0;
while (combinations.length) {
for (const [index, combination] of combinations.entries()) {
if (combinations.length === 1) {
matches[i - 1].push(combination);
combinations.splice(index, 1);
break;
}
if (index === 0) {
matches.push([combination]);
combinations.splice(index, 1);
continue;
}
const [team1, team2] = combination;
const idx = matches[i].findIndex((match) => {
return match.includes(team1) || match.includes(team2);
});
if (idx !== -1) {
continue;
}
matches[i].push(combination);
combinations.splice(index, 1);
}
i++;
}
return matches;
};
PHP
function get_matches ($combinations) {
$matches = [];
$i = 0;
while (count($combinations)) {
foreach ($combinations as $index => $combination) {
if (count($combinations) === 1) {
array_push($matches[$i - 1], $combination);
array_splice($combinations, $index, 1);
break;
}
if ($index === 0) {
array_push($matches, [$combination]);
array_splice($combinations, $index, 1);
continue;
}
$idx = find_index($matches[$i], $combination);
if ($idx !== -1) {
continue;
}
array_push($matches[$i], $combination);
array_splice($combinations, $index, 1);
}
$i++;
}
return $matches;
}
Helper function in PHP
function find_index ( $matches, $teams ) {
[$team1, $team2] = $teams;
foreach ( $matches as $index => $match ) {
if (in_array($team1, $match) || in_array($team2, $match)) {
return $index;
}
}
return -1;
}
Expected output, I am getting this in Javascript
[
[ [ 'A', 'B' ], [ 'C', 'D' ] ],
[ [ 'A', 'C' ], [ 'B', 'D' ] ],
[ [ 'A', 'D' ], [ 'B', 'C' ] ],
[ [ 'B', 'C' ], [ 'A', 'D' ] ],
[ [ 'C', 'D' ], [ 'A', 'B' ] ],
[ [ 'B', 'D' ], [ 'A', 'C' ] ],
[ [ 'A', 'C' ], [ 'B', 'D' ] ],
[ [ 'A', 'B' ], [ 'C', 'D' ] ],
[ [ 'A', 'D' ], [ 'B', 'C' ] ]
]
PHP output
[
[["A","B"],["C","D"]],
[["A","C"],["B","D"]],
[["A","D"],["B","C"]],
[["B","C"],["A","D"]],
[["B","D"],["A","C"]],
[["B","C"],["A","D"]],
[["A","D"],["B","C"]],
[["A","B"],["C","D"]],
[["A","C"],["C","D"]],
[["B","C"],["C","D"]]
]
The result of PHP has the following errors, first instead of returning an array of 9 items it returns 10, second in item 10 and 9 the team C
would play twice at the same time
update 0
The logic of the function is implemented following the advice in this answer, specifically paragraphs 1 to 4
Thanks in advance for the time