Originally posted by: 5HNY_Imad_Abdeljaouad
I see. Given that those numbers (range from 1..Nb which is 6 in the eg., and the number of consecutive 1s which is 2 in the eg.) can change based on what I have in the data file, it would be inefficient and would definitely make the model long/hard to write. Anyway, I just found a way (after days of thinking and trying):
I use two expressions, one to store the index of the first '1' and another for the index of the last '1'.
int Nb = 6;
int j = 2;
range i = 1..Nb;
dvar boolean x[i];
dexpr int ending = max(t in i) (x[t] * t);
dexpr int starting = min(t in i) ( ( (-(x[t]*t)+t)*(2*Nb) )+t );
//obj function here
//constraints:
subject to{
sum(t in i) x[t] == j; //where j is how many 1s you would like to be consecutive , in the example above it's 2
ending - starting == j -1;
}
//thanks to Joris Kinable (JorisK) for the ending constraint
Of course I assume that j >= 2, otherwise there is no need to bother with the constraint (and it will not work :P )
#CPOptimizer#DecisionOptimization