Please see my comment to the question.
Here is the idea: showing the picture does not mean definition of the problem. Moreover, showing one particular example is also not a definition of the problem. By an example, it's usually possible to find some different algorithms doing different things is some general case which is not formally described.
The code is pretty much like a statement in mathematics: it does not just express some idea, more or less vague. It always defines something in an absolutely certain way, even when this absolute level of certainty is not required by some practical purpose. Every such definition or algorithm hold the notion of infinity in its depth: it defines some invariant behavior, which does not depend on how and when the code was compiled, how many times executed (it it is stateless, of course), on what what CPU, at what time, etc. It always define some invariant behavior, without any ambiguity. So, the requirements to the algorithm should meet this level or certainty.
That said, this is one of the typical cases, when the
solution of the problem is nearly equivalent to its strict formulation. Here is what you have to do: formulate the problem in the form of text fully understandable to all qualified readers, in a
fully unambiguous way. You will see that it would require strict mathematical language. As soon as you do it, you will see that the algorithm is already there — you only need to translate it from you
declarative language to some
imperative language. Such as Java.
There are very many cases, when such translation itself is extremely difficult; and there is a good number of unsolved problems, well known in the world. But not in your case. I'm pretty sure in your simple case this is all what involved, there is nothing else.
Consider I gave you a
universal algorithm 
for solving of unlimited number of similar problems:
formulate it strictly, and immediately see the solution.
—SA