The first thing to do is figure out the rules for the algorithm using a pencil and paper. Figure out the logic then worry about the code.