solved problem 18 in ruby