Rewritten al the algorithm in Ruby