change algorithm for cartesian product