Derek Williams

Menu

Tag Archives: Friday Fragment

I recently received a request to push some of my recent Friday Fragment code out to github to make it simple for folks to pull it. Not a bad idea, so I did that tonight. If you’re interested, see https://github.com/derekwlms and clone away. If/when Friday Fragments resume, I’ll probably use github as yet another means of sharing solutions.

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

This Week’s Fragment?

There’s no new fragment for this week. The Friday Fragment will take a break while a couple of interesting projects keep me busy. But somehow, some way, some Friday, it’ll be back to remind us all what just a fragment of code can accomplish.

Last Week’s Fragment – Solution

Last week’s challenge was to outsmart a call center math PhD who was just trying to get rid of me for awhile:

Write code to do ten threaded runs of the basic Leibniz formula to calculate pi to nine correct digits (one billion iterations) in significantly less time than ten successive runs.

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

This Week’s Fragment

It was my Friday lunch break, and since I wanted get a problem with a recent online order corrected before the weekend, I called the merchant’s 800 number. After a long hold time, I finally got a representative on the phone who, horror of horrors, was a mathematics PhD working a call center job. As I cranked up the phone volume, she told me she was swamped with calls and the correction I needed was going to take awhile. She’d prefer I just go away.

“Can you call back later?” she asked.“Sure. When?”“In a while.”“How long?”“A while.”“Can you give me an idea?” I asked.“Tell ya’ what. Calculate pi using the Leibniz formula to nine correct digits. Use the basic algorithm with no series accelerations or transforms. Do it 10 times. When you’re done, call me back.”“OK,” I mumbled and hung up.

What to do? The coding part was easy, and there are even Leibniz implementations all over the net. But nine correct digits would take good big number support and a billion iterations of basic Leibniz. Ten successive runs of that would go well past the end of my lunch break.

Fortunately, I have a quad core machine, had seen first-hand the benefits of threading things such as this, and even wrote about it just yesterday. So I wrapped some threads around a basic implementation, ran it, and called back. Problem solved.

You never know when you, too, might have a math PhD on the other end of a customer service call. So to help you prepare for that, I invite you to this exercise:

Write code to do ten threaded runs of the basic Leibniz formula to calculate pi to nine correct digits (one billion iterations) in significantly less time than ten successive runs.

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. Finish implementing our genetic algorithm solution by doing the natural selection and termination.

Natural selection can be done simply by sorting the current population by fitness and taking the top N individuals, like so:

/**
* Compare fitness levels for sorting.
*/publicfunction compareFitness($purchase1,$purchase2){if($purchase1->getFitness()==$purchase2->getFitness())return0;return($purchase1->getFitness()>$purchase2->getFitness()) ? -1:1;}/**
* Select a subset of the given population for breeding a new generation.
* Return this subset ordered by the most fit first.
*/public static function select($population,$size){usort($population,array('PetPurchase','compareFitness'));returnarray_slice($population,0,$size);}

And we terminate by breeding until we either find a perfect fit or hit a generation cap:

/**
* Find the most fit solution by breeding the given number of generations,
* each with the specified population size.
* Return an array with the most fit and the number of generations created.
*/public static function findMostFit($generations,$populationSize){$population=self::createPopulation($populationSize);$mostFit=new PetPurchase();for($i=0;$i<$generations;$i++){$population=self::select($population,$populationSize);if($population[0]->getFitness()>$mostFit->getFitness())$mostFit=$population[0];if($mostFit->getFitness()==100)break;$population=self::breed($population);}returnarray($mostFit,$i);}

My completed PetPurchase class is here. I also coded a Ruby version here. Here’s an example run:

As in this case, genetic algorithms often aren’t the fastest or most efficient way to get a result. They’re really a (slightly) directed random walk, and they’re not good for well-understood solutions that don’t justify the overhead of a genetic approach. But for cases where fitness is well-understood but the solution isn’t, genetic algorithms can be a valuable tool.

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. Finish implementing our genetic algorithm solution by doing the natural selection and termination.

To play along, post your code as a comment or send it via email. If you’d like, you can build atop my current PetPurchase class; I put in placeholders for the next steps.

/**
* Generate a random set of counts, within reasonable constraints.
*/publicfunction randomize(){$this->setDogCount(rand(1,6));$this->setCatCount(rand(1,85));$this->setMouseCount(rand(1,336));}/**
* Create a population of the given size with random individuals.
*/public static function createPopulation($size){$population=array();for($i=0;$i<$size;$i++){$purchase=new PetPurchase();$purchase->randomize();array_push($population,$purchase);}return$population;}

And combination and mutation is done with these new methods:

/**
* Set my attributes from those of my parents.
* This is also known as breeding, crossover, or recombination.
*/publicfunction combine($dad,$mom){$this->setDogCount(rand(0,1)==0 ?
$dad->getDogCount():$mom->getDogCount());$this->setCatCount(rand(0,1)==0 ?
$dad->getCatCount():$mom->getCatCount());$this->setMouseCount(rand(0,1)==0 ?
$dad->getMouseCount():$mom->getMouseCount());}/**
* Mutate my attributes so that I'm not an exact clone of my parents.
*/publicfunction mutate(){$this->setDogCount(rand(0,2)==0 ?
rand(1,6):$this->getDogCount());$this->setCatCount(rand(0,2)==0 ?
rand(1,85):$this->getCatCount());$this->setMouseCount(rand(0,2)==0 ?
rand(1,336):$this->getMouseCount());}

There are the many possible ways to go about this; breeding techniques can be quite different, but still result in a population that contains a correct (best fit) solution.

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. Start implementing a genetic algorithm solution – determine how to encode candidate solutions (individuals) and code the fitness function.

We could encode candidate solutions using a simple associative array with the number of dogs, cats, and mice, but I decided to create a class (PetPurchase) and use instance variables, like so:

class PetPurchase {
private $dogCount, $catCount, $mouseCount;

Here’s a very simple fitness function I wrote – a method on PetPurchase. There are many possible answers.

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

This Week’s Fragment

Genetic algorithms have received new attention lately with interesting things like BoxCar 2D. And while some of the research around them may seem mysterious, the basic approach is quite simple. Let’s revisit a recent Friday Fragment and apply evolutionary techniques to solve it:

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. Start implementing a genetic algorithm solution – determine how to encode candidate solutions (individuals) and code the fitness function.

To play along, post your code as a comment or send it via email. You can refer back to Joe’s conventional programming solution if you’d like; the point here is to re-structure it into a genetic algorithm in order to learn this approach first-hand.

Last Week’s Fragment – Solution

Last week’s puzzle continued our team ranking system based on win/loss records and strength of schedule (SOS):

Write code to calculate the RPI (Ratings Percentage Index) for a set of teams using the basic Wikipedia calculation. Present the teams ordered by RPI.

I updated my PHP Team class (now TeamRPI) to calculate RPI and sort the results. Here are the changes:

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

This Week’s Fragment

Let’s continue our team ranking system based on win/loss records and strength of schedule (SOS):

Write code to calculate the RPI (Ratings Percentage Index) for a set of teams using the basic Wikipedia calculation. Present the teams ordered by RPI.

To play along, post your code or URL as a comment, or send it via email. If you’d like, you can build atop last week’s code and data.

Last Week’s Fragment – Solution

Last week’s puzzle introduced us to strength of schedule calculations for NCAA teams, or any team for that matter:

Write code to find the strength of schedule (SOS) for your favorite team using the basic Wikipedia calculation. Start with a simple list of wins and losses, parse the results, and calculate the ratio. For extra insight, compare it to other teams played.

I wrote a basic PHP Team class to parse the results, house the records and opponents, and calculate strength of schedule. Here’s the gist of it:

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

This Week’s Fragment

The NFL has honed parity to the point where “any given Sunday” should be the new slogan. But that’s far from the case for the NCAA. In this era of “buy games” and weak conferences, strength of schedule (SOS) is as important as win-loss record for NCAA play. Want to know where your team really stands? Then, yes, look at their win/loss record, but also look at their SOS ranking.

We calculated tournament graph power rankings in a recent Friday Fragment. For the next couple of weeks, we’ll look at ranking by record and schedule strength. So let’s get started:

Write code to find the strength of schedule (SOS) for your favorite team using the basic Wikipedia calculation. Start with a simple list of wins and losses, parse the results, and calculate the ratio. For extra insight, compare it to other teams played.

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

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.

Joel Odom pointed out that this is a form of the classic Knapsack problem. Indeed it is, as we’re optimizing money spent and number of animals purchased. Fortunately, the $100 and 100 item bounds keep it in (fast) polynomial time. Joe Richardson gave us a solution in C#:

This gives us 3 dogs, 41 cats, and 56 mice, lickety-split. On the follow-up Car Talk episode, Ray and Tom talked about how they spent hours on this puzzle: Tom stayed up until 3 am without an answer, and Ray spent a lot of time just plugging in numbers. That’s the beauty of this code fragment: let the computer do the time-consuming work!

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 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:

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

This Week’s Fragment

In celebration of the NFL playoffs, we continue our team ranking system. It’s time to implement our tournament matrix:

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

As described below, you load up the matrix, square it and add it to itself (M + M2), and then add across the rows. To play along, provide either the URL or the code for the solution. You can post it as a comment or send it via email. If you’d like, you can build atop the simple tournament matrix class I started.

Propose an algorithm to use a tournament graph to compute power rankings. Start with simple list of wins and losses (Team A beat Team B, Team B beat Team C, etc.) and propose a way to rank the teams.

You start by creating a matrix (two-dimensional array) from the win-loss results and assign a zero or one to each cell: one if the row-wise team beat the team in that column; otherwise, zero. You then compute the powers of each vertex (in the matrix-represented graph) using the formula M + M2 (add the matrix to the result of squaring itself). From the resulting matrix, sum each row to get the power of each team. There’s a nice, brief description at the bottom of this page: http://aix1.uottawa.ca/~jkhoury/graph.htm.

The benefit of this approach is it considers “transitive wins:” if Team A beats Team B and Team B beats Team C, Team A gets some credit over Team C, even if they never played. The downside is that football isn’t always transitive.

So finish the code and plug in some records. Let’s see how our power matrix compares to reality.

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

This Week’s Fragment

It’s NFL wildcard weekend, and analysts are all over the place in their predictions. It’s clear who the top NFL teams are (Falcons, Pats), but less clear for teams with fewer wins, and when comparing teams that haven’t played each other in awhile. There’s no RPI for football, but a dominance-directed graph (a.k.a., tournament graph) can provide some basic rankings. Over the next two weeks, we’ll see if we can build such a ranking system. Let’s start with the approach:

Propose an algorithm to use a tournament graph to compute power rankings. Start with simple list of wins and losses (Team A beat Team B, Team B beat Team C, etc.) and propose a way to rank the teams.

To play along, write a description of the solution or pseudo code and post it as a comment or send it via email. To avoid “spoilers”, simply don’t expand comments for this post.

There are many implementations already available (including C code for the unix cal utility), but this was an opportunity to work it out for yourself. I coded a Q&D web implementation in PHP; here’s the gist:

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

This Week’s Fragment

If you coded last week’s fragment under Linux, you could check your results by running cal month year. The unix cal utility formats calendars based on the current date or a given date. So let’s continue our new year’s programming along those lines:

Write code to print out a month’s calendar given a month and year.

To play along, post the code for the solution as a comment or send it via email. You can built atop last week’s solution to determine the starting day of week. There are likely many implementations already available (including C code for the unix utility), but this is a good opportunity to try new languages or techniques.

Last Week’s Fragment – Solution

With our round of game programming, our code solutions had grown a bit larger than mere fragments. So last week’s puzzle returned to something short and sweet, as Friday Fragments marked Christmas Eve and New Year’s Eve:

Write code to calculate the day of week (Sunday through Saturday) for a given date. Remember to account for leap years.

Upgrade your game (rock-paper-scissors, tic-tac-toe, or Reversi, your choice) to use async (AJAX-style) calls and updates, rather than postbacks. Use any frameworks you’d like, or just plain old Javascript.

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

This Week’s Fragment

Let’s bring our games into the modern era. You’ll notice in my solutions that every play causes a full redraw of the page. That’s so very 1990s, so let’s fix it:

Upgrade your game (rock-paper-scissors, tic-tac-toe, or Reversi, your choice) to use async (AJAX-style) calls and updates, rather than postbacks. Use any frameworks you’d like, or just plain old Javascript.

To play along, provide either the URL or the code for the solution. You can post it as a comment or send it via email. If you’d like, you can build atop the games, bots, and/or source code at http://derekwilliams.us/bots.

Write code to let man compete against machine (a game bot) in Reversi. Present the game board on a web page, let the human player make the next move, and then call the game bot for its move. Continue this until one side wins.

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

This Week’s Fragment

With this week’s solution, we now have code to match man against machine in tic-tac-toe. Let’s do that for our Reversi game:

Write code to let man compete against machine (a game bot) in Reversi. Present the game board on a web page, let the human player make the next move, and then call the game bot for its move. Continue this until one side wins.

To play along, provide either the URL or the code for the solution. You can post it as a comment or send it via email. If you’d like, you can build atop the games, bots, and/or source code at http://derekwilliams.us/bots.

Write code to let man compete against machine (a game bot) in rock-paper-scissors, tic-tac-toe, or Reversi (your choice). Present the game board on a web page, let the human player make the next move, and then call the game bot for its move. Continue this until one side wins.

To keep it simple, there’s not a lot of error handling. Also, you’ll notice that our prior tic-tac-toe bot (the O player) isn’t very good at it. If you haven’t already done so, try coding your own bot, plug it in at the “Your bot here” line, and compete against it. Perhaps you could upgrade the wins map. Then maybe your record will be as good as the NFC-leading Falcons. 10-2 – Rise Up!

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

This Week’s Fragment

After last week’s commemorative fragment, we’ll resume our game bots. Let’s make our bots more interesting by letting us play instead of just watching:

Write code to let man compete against machine (a game bot) in rock-paper-scissors, tic-tac-toe, or Reversi (your choice). Present the game board on a web page, let the human player make the next move, and then call the game bot for its move. Continue this until one side wins.

To play along, provide either the URL or the code for the solution. You can post it as a comment or send it via email. If you’d like, you can build atop the bots and/or source code at http://derekwilliams.us/bots.

I offered a hint (“try some googling”) and a short-cut (“just offer suggestions on how to go about solving it”). And for good reason: this is a somewhat famous unsolved cryptogram. It’s Part 4 of Kryptos, Jim Sanborn’s sculpture at the CIA headquarters. I posted it last week in celebration of its 20th anniversary, and the recent release of a new clue.

Many experts and othersorts have worked on solving Part 4, in search of fame or just a good challenge. I think it utilizes a one-time pad or a long key, perhaps along with the Vigenere Table found on the sculpture. The key or pad may be located on-site; for example in the underground utility tunnel. Time will tell.

If you think you can crack it, don’t just tell me: send your solution to Sanborn for verification.

You can provide the solution or just offer suggestions on how to go about solving it. For example, I can’t solve it, but based on its background (try some googling), I have ideas about how it might be solved. To “play along,” post your response as a comment or send it via email.

Code a simple REST web service to start playing Reversi. It should accept a 64-character string representing the current 8×8 “game board” with dot (empty space), X (black), or O (white) in each position (starting from the top left, going left-to-right and down). It should return a 64-character string with your next move added. Don’t worry about turning pieces yet, just find the next best move.

Here’s a simple solution in PHP, with room for improvement. To start playing, pass it ?board=………………………OX……XO………………………&piece=X.

Of course, there are much smarter ways to code Reversi, such as applying common strategies and running look-ahead scenarios, but that’d be more than a fragment. Years ago, a coworker wrote one for VisualWorks (still in the Cincom Public Repository), and there’s a well-documented implementation at lurgee.net. If you’re up for coding a smarter version behind the service interface, give it a shot.

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

This Week’s Fragment

Let’s do another “game bot” – this time, Othello (a.k.a., Reversi):

Code a simple REST web service to start playing Reversi. It should accept a 64-character string representing the current 8×8 “game board” with dot (empty space), X (black), or O (white) in each position (starting from the top left, going left-to-right and down). It should return a 64-character string with your next move added. Don’t worry about turning pieces yet, just find the next best move. We’ll work on flipping pieces in next week’s fragment.

To “play along,” provide either the URL or the code for the solution. You can post it as a comment or send it via email.

Code a simple REST web service to play tic-tac-toe. It should accept a nine-character string representing the current “game board” with space, X, or O in each position (starting from the top left, going left-to-right and down). It should return a nine-character string with your next move added.

Here’s my Q&D, brute-force solution in PHP, with room for improvement. I added vertical bar wrappers to preserve spaces on the GET request, so pass it ?board=| | to start.