I started learning and I am making a project for a home fifa18 cup. I have one problem, I don't know how I can pair all players I mean: Player1, Player2, Player3, Player4
=> P1 vs P2, P1 vs P3, P1 vs P4
=> P2 vs P3, P2 vs P4
=> P3 vs P4
I use Newton formula n!/k!(n-k)!
to count how many match without revenge will be and have all players in $tab
.
So now, my question, how can I pair this?
Like that and it will be not repetition & P1 vs P1 example.
<?php
require("server/baza.php");
$przelacznik = 1;//$_POST['losuj'];
$zapytanie = "select nick from mecze";
if($przelacznik == 1){
$wynik = mysqli_query($polaczenie,$zapytanie);
$tab = array();
$n=0;
while($wiersz = mysqli_fetch_assoc($wynik)){
array_push($tab,$wiersz['nick']);
//$tab[] = $wiersz;
$n++;
}
$Nsilnia = 1;
$NKsilnia =1;
for ($i=1; $i<=$n; $i++) {
$Nsilnia *= $i;
}
for($j=1;$j<=($n-2);$j++){
$NKsilnia *= $j;
}
$ilosc_rozgrywek = ($Nsilnia)/(2*$NKsilnia);
}
?>
If P1 vs P2 and P2 vs P1 are not same. Then use this one.
$player_list = ['p1', 'p2', 'p3', 'p4'];
$player_pair = array();
foreach($player_list as $key => $player){
for($i = 0; $i < count($player_list); $i++ ){
if($i != $key){
$player_pair[] = $player_list[$i] . ' VS ' . $player;
}
}
}
print_r($player_pair);
ELSE USE THIS ONE:
$player_list = ['p1', 'p2', 'p3', 'p4'];
$player_pair = array();
foreach($player_list as $key => $player){
for($i = 0; $i < count($player_list); $i++ ){
$str = $player_list[$i] . ' VS ' . $player;
$str2 = $player . ' VS ' . $player_list[$i];
if($i != $key && !in_array($str, $player_pair) && !in_array($str2, $player_pair)){
$player_pair[] = $player_list[$i] . ' VS ' . $player;
}
}
}
print_r($player_pair);
If you store your player in an array like:
$player = ['P1', 'P2', 'P3', 'P4'];
you can use two loops to pair all possible matches without revenge.
for ($i = 0; $i < count ($player); $i++) {
//set the start of the second loop to $i + 1
for ($j = $i + 1; $j < count ($player); $j++) {
echo $player[$i].' vs '.$player[$j];
}
}
that will output:
// P1 vs P2
// P1 vs P3
// P1 vs P4
// P2 vs P3
// P2 vs P4
// P3 vs P4
$players = [ 'p1', 'p2','p3','p4', 'p5'];
$result =[];
for($i = 0; $i < count($players); $i++ ) {
for($j=$i+1; $j<count($players); $j++) {
$result[] = $players[$i] . ' vs ' . $players[$j];
}
}
print_r($result);
<?php
$no_players = 4;
$pairings = [];
for($i = 1; $i <= $no_players; $i++)
for($j = 1; $j <= $no_players; $j++)
if($i !== $j && !in_array([$j, $i], $pairings))
$pairings[] = [$i, $j];
var_export($pairings);
Output:
array (
0 =>
array (
0 => 1,
1 => 2,
),
1 =>
array (
0 => 1,
1 => 3,
),
2 =>
array (
0 => 1,
1 => 4,
),
3 =>
array (
0 => 2,
1 => 3,
),
4 =>
array (
0 => 2,
1 => 4,
),
5 =>
array (
0 => 3,
1 => 4,
),
)