在MiniZinc中实现可变长度数组交错合并函数
Interleaved Array Merging in MiniZinc (Preserving Element Order)
Got it, let's tackle this problem of writing a MiniZinc function that merges two variable-length arrays while preserving the relative order of elements from each original array. Here's a practical implementation that fits the function array[int] of var... format you need:
The Function Implementation
function array[int] of var $T$ interleave(array[int] of var $T$ a, array[int] of var $T$ b) where $T$ is any type: let { int: len_a = length(a); int: len_b = length(b); int: len_c = len_a + len_b; % The merged array we'll return array[1..len_c] of var $T$ c; % Arrays to track positions of elements from a and b in c array[1..len_a] of var 1..len_c: pos_a; array[1..len_b] of var 1..len_c: pos_b; } in c % Ensure all positions are unique (no overlapping elements in c) /\ all_different(pos_a ++ pos_b) % Maintain the original order of elements from array a /\ forall(i in 1..len_a-1)(pos_a[i] < pos_a[i+1]) % Maintain the original order of elements from array b /\ forall(i in 1..len_b-1)(pos_b[i] < pos_b[i+1]) % Map elements from a to their positions in c /\ forall(i in 1..len_a)(c[pos_a[i]] = a[i]) % Map elements from b to their positions in c /\ forall(i in 1..len_b)(c[pos_b[i]] = b[i]) ;
How It Works
Let's break down what this code does:
- Length Calculation: First, we compute the lengths of the input arrays and the resulting merged array.
- Position Tracking: The
pos_aandpos_barrays store where each element fromaandbends up in the merged arrayc. - Uniqueness Constraint:
all_different(pos_a ++ pos_b)ensures every element gets a unique spot inc—no duplicates or overlaps. - Order Preservation: The two
forallconstraints guarantee that elements fromastay in their original relative order (e.g., ifa[1]comes beforea[2]ina, it will also come beforea[2]inc), and the same rule applies to elements fromb. - Element Mapping: Finally, we link each element from
aandbto its assigned position inc.
Example Usage
If you pass a = [x, y, z, a, b] and b = [p, q, r], the solver will generate valid merged arrays like:
[x, p, q, y, z, r, a, b][p, x, q, r, y, z, a, b]- Any other combination where the order of elements from
aandbindividually stays intact.
Notes
- This function is generic—it works with any variable type (
int,float,bool, custom enums, etc.) as long as both input arrays use the same type. - Since MiniZinc is a constraint programming language, this function doesn't produce a single hardcoded merged array—it defines the constraints that any valid merged array must satisfy. The solver will generate all possible valid combinations when you run your model.
内容的提问来源于stack exchange,提问作者Rajat Gupta
相关产品推荐
相关产品推荐

