Algorithm in SCALA