Tournament bracket placement algorithm

前端 未结 10 648
生来不讨喜
生来不讨喜 2020-12-02 09:37

Given a list of opponent seeds (for example seeds 1 to 16), I\'m trying to write an algorithm that will result in the top seed playing the lowest seed in that round, the 2nd

10条回答
  •  忘掉有多难
    2020-12-02 10:07

    Since this comes up when searching on the subject, and it's hopeless to find another answer that solves the problem AND puts the seeds in a "prettier" order, I will add my version of the PHP code from darkangel. I also added the possibility to give byes to the higher seed players.

    This was coded in an OO environment, so the number of participants are in $this->finalists and the number of byes are in $this->byes. I have only tested the code without byes and with two byes.

      public function getBracket() {
          $players = range(1, $this->finalists);
          for ($i = 0; $i < log($this->finalists / 2, 2); $i++) {
            $out = array();
            $reverse = false;
            foreach ($players as $player) {
              $splice = pow(2, $i);
              if ($reverse) {
                $out = array_merge($out, array_splice($players, -$splice));
                $out = array_merge($out, array_splice($players, 0, $splice));
                $reverse = false;
              } else {
                $out = array_merge($out, array_splice($players, 0, $splice));
                $out = array_merge($out, array_splice($players, -$splice));
                $reverse = true;
              }
            }
            $players = $out;
          }
          if ($this->byes) {
            for ($i = 0; $i < $this->byes; $i++ ) {
              for ($j = (($this->finalists / pow(2, $i)) - 1); $j > 0; $j--) {
                $newPlace = ($this->finalists / pow(2, $i)) - 1;
                if ($players[$j] > ($this->finalists / (pow(2 ,($i + 1))))) {
                  $player = $players[$j];
                  unset($players[$j]);
                  array_splice($players, $newPlace, 0, $player);
                }
              }
            }
            for ($i = 0; $i < $this->finalists / (pow(2, $this->byes)); $i++ ) {
              $swap[] = $players[$i];
            }
            for ($i = 0; $i < $this->finalists /(pow(2, $this->byes)); $i++ ) {
              $players[$i] = $swap[count($swap) - 1 - $i];
            }
            return array_reverse($players);
          }
          return $players;
        }
    

提交回复
热议问题