Ordered Cartesian Product Arrays

In an efficient sorted Cartesian product of 2 sorted arrays of integers, a lazy algorithm is proposed for creating ordered Cartesian products for two sorted integer arrays.

I am interested to know if there is a generalization of this algorithm for more arrays.

For example, we have 5 sorted arrays of doubles

(0.7, 0.2, 0.1)

(0.6, 0.3, 0.1)

(0.5, 0.25, 0.25)

(0.4, 0.35, 0.25)

(0.35, 0.35, 0.3)

I'm interested in generating an ordered Cartesian product without having to calculate all possible combinations.

Evaluate any ideas on how a possible lazy Cartesian product algorithm could possibly extend to sizes beyond 2.

+4
2

(., , https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm). , . - - . 5 (0, 0, 0, 0, 0).

, . , .

, m n , O ((n ^ m).log(n (m-1)).

python:

from heapq import heappush, heappop

def cost(s, lists):
    prod = 1
    for ith, x in zip(s, lists):
        prod *= x[ith]
    return prod

def successor(s, lists):
    successors = []
    for k, (i, x) in enumerate(zip(s, lists)):
        if i < len(x) - 1: 
            t = list(s)
            t[k] += 1
            successors.append(tuple(t))
    return successors

def sorted_product(initial_state, lists):    
    fringe = []
    explored = set()
    heappush(fringe, (-cost(initial_state, lists), initial_state))
    while fringe:
        best = heappop(fringe)[1]
        yield best
        for s in successor(best, lists):
            if s not in explored:
                heappush(fringe, (-cost(s, lists), s))
                explored.add(s)

if __name__ == '__main__':
    lists = ((0.7, 0.2, 0.1),
             (0.6, 0.3, 0.1),
             (0.5, 0.25, 0.25),
             (0.4, 0.35, 0.25),
             (0.35, 0.35, 0.3))
    init_state = tuple([0]*len(lists))
    for s in sorted_product(init_state, lists):
        s_output = [x[i] for i, x in zip(s, lists)]
        v = cost(s, lists)
        print '%s %s \t%s' % (s, s_output, cost(s, lists))
+2

, A (A1,..., An) B (B1,..., Bn).

A < B ,

A1 *... * An < B1 *... * Bn

, , , , :

(- 50, -100, 1) > (1, 2, 3)

-50 * (-100) * 1 = 5000 > 6 = 1 * 2 * 3

. , , k. (A1,..., Ak) (B1,..., Bk), , (A1,..., Ak,... An), , (B1,..., Bk,..., Bn). , , , . :

  • k A B

(C1,..., Ck), , (B1,..., Bk), (C1,..., Ck) - , (A1,..., Ak) (C1,..., Ck) .

, , (A1,..., Ak) < (B1,..., Bk), , , l , , A B. l , , ( , ). . , , (A1,..., Ak,..., Al) > (B1,..., Bk,..., Bl), , A B, , B A.

, :

class Rule {
    int k;
    int[] smallerCombinationIndexes;
    int[] biggerCombinationIndexes;
    List<Rule> exceptions;
}

, , . , , , , .. , , A B, A B, , (A1,..., Ak) (B1,..., Bk), , (A1,..., Ak) (B1,..., Bk) . . , : , , .

0

All Articles