My solution from the CodingGame contest.