O'Reilly logo

Genetic Algorithms and Machine Learning for Programmers by Frances Buontempo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Let’s Make a Swarm

Now that you know what you’re going to do, and you have an idea of how to do it, you’re ready to dive in and write the code. For both algorithms, KNN and PSO, you can reuse the HTML from the ​code​​​ to create a canvas and have a button calling an init function. Both algorithms need Particles and a move function. After each move, draw the current positions on your canvas to see what’s happening.

Follow Your Neighbor

To make your particles follow their neighbors, create an array of particles. Add one each time this button is clicked. Use setInterval to drive a particle’s movement, and save the interval’s id in the class so you can make it stop. You also need to store its index into the array and the current x and y position. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required