The Friday Fragment
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 ProFootball-Fans.com), 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:
<?php
require 'TournamentMatrix2.php';
if (isset($_POST['submit'])) {
doTourney($_POST['scores']);
}
function doTourney($scores) {
$matrix = new TournamentMatrix2();
$matrix->parseScores($scores);
$matrix->computePowers();
show_powers($matrix->getPowers());
}
?>
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:
Rank | Team | Power |
---|---|---|
1 | Patriots | 91 |
2 | Falcons | 85 |
3 | Jets | 84 |
4 | Ravens | 79 |
5 | Chiefs | 77 |
6 | Bears | 76 |
7 | Saints | 74 |
8 | Giants | 71 |
9 | Steelers | 69 |
10 | Eagles | 69 |
Pretty much what you'd expect (the Packers are #13). If only the playoffs had cooperated.