php[architect] logo

Want to check out an issue? Sign up to receive a special offer.

A Simplified World Cup Draw Generator

Posted by on December 3, 2013

If you’re a football fan, like I am, your anticipation for next year’s World Cup in Brazil is growing. This Friday, we will know the groupings for the 32 teams that will participate in the finals. I put together the (simplified) simulator shown in the gist below. Using PHP’s shuffle() function and SPL iterators, we can generate potential groups in less than 30 lines of code.

Want to learn how to leverage Iterators and Interfaces from the SPL? Check out our book, Mastering the SPL Library by Joshua Thijssen.


Some sample output:

A: Argentina, France, Korea Republic, Russia
B: Uruguay, Ecuador, Honduras, England
C: Belgium, Chile, Japan, Croatia
D: Colombia, Cote d'Ivoire, Mexico, Netherlands
E: Spain, Algeria, Australia, Greece
F: Switzerland, Nigeria, Iran, Italy
G: Germany, Ghana, USA, Portugal
H: Brazil, Cameroon, Cost Rica, Bosnia-Herzegovina

OR

A: Colombia, Nigeria, Korea Republic, Bosnia-Herzegovina
B: Brazil, Chile, Japan, England
C: Spain, France, Iran, Netherlands
D: Switzerland, Cameroon, Mexico, Croatia
E: Germany, Ecuador, USA, Italy
F: Uruguay, Cote d'Ivoire, Cost Rica, Russia
G: Argentina, Algeria, Australia, Portugal
H: Belgium, Ghana, Honduras, Greece

I said this was a simplified example. For the actual draw, the pots are not balanced. Pot 2 which contains the teams from South America and Africa only has 7 teams. Pot 4 which is made up of non-seeded European teams has 9 items. You’ll notice that I moved France to Pot 2 so that each has an equal number. The actual draw also has these additional rules:

  • Brazil enters the group A.
  • Countries outside Europe will not be the same group with countries of the same region.
  • European countries will enter up to two teams up to the group.

To account for these rules, we could create a Group class that extends the SplQueue class and validates if a team can be added to the group. We’d also need a simple Team class with a property to hold a team’s region. There are additional tools from the SPL you could use when simulating the real problem, but this example shows you the power of the SPL. To learn more, read Joshua’s book.


Oscar still remembers downloading an early version of the Apache HTTP server at the end of 1995, and promptly asking "Ok, what's this good for?" He started learning PHP in 2000 and hasn't stopped since. He's worked with Drupal, WordPress, Zend Framework, and bespoke PHP, to name a few. Follow him on Google+.
Tags: ,
 

Leave a comment

Use the form below to leave a comment: