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

Get Genetic Algorithms and Machine Learning for Programmers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.