Search code examples
optimizationminizinc

Max number of consecutive values (Minizinc)


I'm trying to model the next constraint in Minizinc:

Suppose S is an array of decision variables of size n. I want my decision variables to take a value between 1-k, but there is a maximum 'Cons_Max' on the number of consecutive values used.

For example, suppose Cons_Max = 2, n = 8 and k = 15, then the sequence [1,2,4,5,7,8,10,11] is a valid sequence , while e.g. [1,2,3,5,6,8,9,11] is not a valid sequence because the max number of consecutive values is equal to 3 here (1,2,3). Important to mention is that sequence [1,3,5,7,9,10,12,14] is also valid, because the values don't need to be consecutive but the max number of consectuive values is fixed to 'Cons_Max'.

Any recommendations on how to model this in Minizinc?


Solution

  • Here's a model with a approach that seems to work. I also added the two constraints all_different and increasing since they are probably assumed in the problem.

    include "globals.mzn";
    int: n = 8;
    int: k = 15;
    int: Cons_Max = 2;
    % decision variables
    array[1..n] of var 1..k: x;
    
    constraint 
       forall(i in 1..n-Cons_Max) (
          x[i+Cons_Max]-x[i] > Cons_Max
       )
    ;
    
    constraint 
      increasing(x) /\
      all_different(x)
    ;
    
    %% test cases
    % constraint 
    %    % x = [1,2,4,5,7,8,10,11] % valid solution
    %    % x = [1,3,5,7,9,10,12,14] % valid valid solution
    
    %    % x = [1,2,3,5,6,8,9,11] % -> not valid solution (-> UNSAT)
    %  ;
    
    
    solve satisfy;
    output ["x: \(x)\n" ];