Extract common code from value iteration functions