The Friday Fragment

Published on 22 January 2011
This post thumbnail

It's Friday, and time again for the Friday Fragment: our weekly programming-related puzzle.

This Week's Fragment

Equations are a perfect fit for programming. A small fragment of code can help you quickly compute a result, particularly when substitution or Monte Carlo methods are required: you can save time by letting the computer do the "plugging in."

A recent Car Talk Puzzler required simultaneous equations with some trial and error. Let's write code to let the computer do the time-consuming substitution work for us:

You're given $100 and told to spend it all purchasing exactly 100 animals at the pet store, buying at least one of each animal. Dogs cost $15. Cats cost $1, and mice are 25 cents each. Determine the equations and write code to solve them.

To play along, post your code as a comment or send it via email.

Last Week's Fragment - Solution

In celebration of the NFL postseason, last week's challenge was to complete our basic our team ranking system:

Write code to use a tournament matrix (built from win/loss records) to compute power rankings for a set of teams.

To do this, we load up the matrix from win/loss records (I used scores from, square it and add it to itself (M + M2), and then add across the rows. I offered my initial tournament matrix class to do the math and get started.

To complete this, we add methods to our TournamentMatrix class to parse the scores (parseScores) and compute the powers (computePowers). My updated class is here as TournamentMatrix2.php. Calling it from a web page is straightforward:

    require 'TournamentMatrix2.php';
    if (isset($_POST['submit'])) {

    function doTourney($scores) {
        $matrix = new TournamentMatrix2();

The calling code is in rankings.php. You can run my code from /files/fragments/tourney.html. Paste in your own scores, or use my NFL regular season scores at /files/fragments/nflscores.txt. For this NFL data, you'll see that the top 10 power rankings are:


Pretty much what you'd expect (the Packers are #13). If only the playoffs had cooperated.