Coins on a Star Puzzle with p5.js

Here’s a fun puzzle for you, which I have implemented online using the fantastic p5.js library for creative coding.

The goal is to place as many coins on the board as possible according the the following rules:

  • Place a coin on one of the numbered circles and immediately slide it alone one of the lines to a connected circle, after which you may not move it again.
  • Only one coin is allowed on each final position.

For example the position shown in the featured image above is the result of performing the following sequence of moves:

1 -> 4, 2 -> 5, 3 -> 6, 2 -> 7, 3 -> 8

giving a total of 5 coins on the star with no way to add more. This is not the maximum possible number of coins which can be placed? What is the maximum? Try the puzzle now to see if you can work it out.

Try the Coins on a Star Puzzle Here

Click on the nodes to select. Once selected, click a second connected node to slide the coin to its final position.

What is the maximum number of coins which can be placed?

Graph Unfolding to Solve the Coins on a Star Puzzle

One very useful trick to help solve this puzzle, which is made easy by my implementation and the power of p5.js, is “untangling” or “unfolding” the graph (the puzzle can be thought of as a graph, in the sense of “graph theory” or the study of nodes and edges…).

Graph unfolding for Coins on a Star Puzzle with p5.js

You can drag the nodes of the puzzle around the canvas to unfold the graph. Have a go now, unfolding the graph first, and see if it becomes clearer how to solve the puzzle.

Here’s a solution using the graph unfolding method:

Code listing of p5.js Coins on a Star Puzzle

My implementation is provided below for your interest.

The node objects are not directly clickable using p5.js – this is because the mousePressed() handler applies to the whole canvas, so to work out which node was clicked on I have iterated through all the nodes to see if the mouse (X, Y) coordinates are inside each node.

The code could well be useful for more puzzles and illustrating Computer Science concepts such as Dijkstra’s algorithm etc..

Happy computing.

 Take your Python skills to the next level!

with our free email course on object oriented programming with Python