Natural Computing Blog

Using swarm A.I. to play cards

This week we’ll see how to use my c++ DFO algorithm to solve a logic card game


Setting up

First, we need to set up a new c++ project. I’ll use a Mac  and its XCode but you can use any other OS or IDE.

Then we need to download the “bare version of my DFO”. You can download it or clone it from here:


The Logic

The game we want to solve is as follows:

You’re in a pub in an island and a friend decides to give a million to anyone who could solve the following problem only by using DFO:

Each one of you is given 10 cards, numbered 1-10. You’re asked to divide the cards in two groups where the sum of the numbers on the cards in the first group is as close to 36 and the product of the numbers in the second group is as close as possible to 360.



Once you have the algorithm, you should link it to your project:

All the source code is in DFO/lib and the only header you need to include is DFO.hpp

You should then create an instance of the DFO class, which will set up the algorithm for you.

Once you do this, you can set up variables such as the dimensions of the search space (10), the range of the initial search space (0 to 1), the type of algorithm (best neighbour rather than swarm’s best usually works better for this type of problems), and the number of agent “flies” you want to use (I chose 80).

The most important feature thet you need to set is the fitness function. I have set it so that if a feature in the fly’s position/hypothesis vector is < than 0.5, then the card whose value would be “position_vector_index + 1” is “added” to the running sum of “group 1”. Otherwise, the same value is multiplied by the running product of “group 2”. The fitness is then a measure of the error in the two groups (how fare we are from 36 ad 360 respectively), which optimises at 0.



Finally, you run the program in a loop for a certain number of times and you check what is the fitness of the best fly at the end, as well as its solution vector.



Here is a live coded video tutorial for you to check:







Leave a Reply

Your e-mail address will not be published. Required fields are marked *