A Flash Developer Resource Site

Results 1 to 3 of 3

Thread: Need help with for loop math

  1. #1
    AS3 Mod
    Join Date
    Sep 2007
    Location
    O-H-I-O
    Posts
    2,385

    Need help with for loop math

    I am building a bracket system (double elimination) and need to figure out how to create a loop that will return the proper matches according to seed.

    For example, if a tournament has 8 teams the seeds would line up as follows:

    Array(1,8,5,4,3,6,7,2);

    Now I have temporarily built this into a static array:

    PHP Code:
    $this->seedData[8] = array(
                                    
    => array(1,8,5,4,3,6,7,2),
                                    
    => array(1,4,3,2),
                                    
    => array(1,2),
                                    
    => array(1)
                                ); 
    Does anyone have any ideas how I can put a formula into a for loop that will generate this rather than having to build static arrays? The reasoning is due to having either 8, 16, 32 or 64 teams.

    Thanks to anyone who is able to assist.

  2. #2
    Junior Member
    Join Date
    Jul 2008
    Posts
    23
    After a bit of trial and error, I came up with the following code:

    Code:
    $teams = 8;
    $data = array();
    $round = $teams;
    $i = 0;
    while(($round%2 == 0 && $round >= 2) || $round == 1){
    $data[$i+1] = array();
     for($j=0; $j<$round/2; $j++){
     array_push($data[$i+1],$j+1);
      if($round != 1){
      array_push($data[$i+1],$round-$j);
      }
     }
    $round /= 2;
    $i++;
    }
    print_r($data);
    I'm not sure if it lists them in the order you'd like, but it seeds the teams correctly. Here's a sample of running the above code with 8 teams:

    Code:
    Array
    (
        [1] => Array
            (
                [0] => 1
                [1] => 8
                [2] => 2
                [3] => 7
                [4] => 3
                [5] => 6
                [6] => 4
                [7] => 5
            )
    
        [2] => Array
            (
                [0] => 1
                [1] => 4
                [2] => 2
                [3] => 3
            )
    
        [3] => Array
            (
                [0] => 1
                [1] => 2
            )
    
        [4] => Array
            (
                [0] => 1
            )
    
    )
    I hope it is sufficient for your needs!

  3. #3

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  




Click Here to Expand Forum to Full Width

HTML5 Development Center