rewrite of perl solution #24 (improved code)