Had an intuition how this should have been solved, went against it, and then had to do that implementation anyway, so I basically wrote this one twice. Three times, if you count the visualization.. =)