combined double foreach into a single for loop in problem 50