April 2011’s issue of MSDN Magazine had an interesting piece on **Bee Colony Algorithms** by **Dr. James McCaffrey, **explaining the concepts and providing an example, applying the algorithm to the Traveling Salesman Problem. In a nutshell, the algorithm is a meta-heuristic, that is, a method that is not guaranteed to produce an optimal solution, but will search for “decent” solutions in a large space. In a real-life bee hive, bees scout for areas rich with food, keep visiting them until they are exhausted, and tell other bees about good spots so that more bees come search that area. By analogy, the algorithm uses scout bees, which search for new random solutions, and recruit inactive bees which become active and start searching for improved solutions around their current solution.

I found the algorithm intriguing, and thought it would be a good learning exercise to try and adapt it to F#.

*Disclaimer: I am still learning the ropes in F#, so take the code that follows with a grain of salt. I’ll gladly take advice and criticism to make this better – my intent is to share my learning experience with the language, not to teach you best practices.*

In the case of the Traveling Salesman Problem, the goal is to find the shortest (or some other cost measure) closed route connecting a list of cities. In order to do this, we need to be able to create random solutions, as well as solutions in the neighborhood of an existing solution.

Assuming we begin with an initial list of Cities (the cities our salesman needs to visit), we can generate random solutions by shuffling that list, using the Fisher-Yates shuffle algorithm. We can generate the sequence of index pairs that need to be swapped with the following

let SwapIndexPairs list =
let random = new Random()
seq {
for i in (List.length list - 1) .. -1 .. 1 do
yield (i, random.Next(i + 1)) }

Running this in the interactive window produces the following:

> open System;;
> let SwapIndexPairs list =
let random = new Random()
seq {
for i in (List.length list - 1) .. -1 .. 1 do
yield (i, random.Next(i + 1)) };;
val SwapIndexPairs : 'a list -> seq<int * int>
> let i = SwapIndexPairs [0;1;2;3;4;5] |> Seq.toList;;
val i : (int * int) list = [(5, 0); (4, 0); (3, 2); (2, 1); (1, 1)]

More...

## Comments

- Read the contents of a worksheet with C# (28)
- Create an Excel 2007 VSTO add-in: adding a WPF control (14)
- Management, the Gordon Ramsay way (4)
- How dense is the product of Sparse Matrices? (5)

Comment RSSDewayne wrote: Wonderful beat ! I would like to apprentice while ... [More]

Healthy Weight Loss Tips After Pregnancy wrote: This could possibly be enough to help you fit comf... [More]

maximum shred reviews wrote: You really make it seem so easy with your presenta... [More]

How To Reverse Aging wrote: Hello, I enjoy reading all of your article. I want... [More]