How to count gaps in a timetable?

47 Views Asked by At

I have a timetable with $n$ time slots. There can be an arbitrary amount of appointments in this timetable.
Some example schedules for $n=4$: $(x_1, x_2, x_3, x_4)$: $(1,1,0,0), (1,0,0,1), (1,1,1,0) $, ...
Since I am using mixed integer programming, my data format is $x_i = 1$ if there is an appointment at time slot $i$ and $0$ otherwise. I am now searching for a function $f$ to count the number of free time slots between appointments. Example: $f((1,1,0,0)) = 0$ because the two appointments are directly after each other. But, $f((1,0,0,1)) = 2$ because there are two free time slots between the appointments. $f((0,1,0,1,0,1,0)) = 2$

It's easy to get the number of appointments: $\sum_i x_i$.
It's also easy to get the number of free slots: $ n - \sum_i x_i$. But I can't find a function $f$, which finds how many free time slots are in between the appointments.
Can someone help here?

1

There are 1 best solutions below

0
On BEST ANSWER

Introduce binary variables $y_i$ and $z_i$ to track the first and last appointments, respectively. The constraints are: \begin{align} y_i &\le x_i &&\text{for all $i$} \tag1\label1 \\ y_i &\le 1 - x_j &&\text{for all $i$ and $j<i$} \tag2\label2 \\ z_i &\le x_i &&\text{for all $i$} \tag3\label3 \\ z_i &\le 1 - x_j &&\text{for all $i$ and $j>i$} \tag4\label4 \\ \sum_i y_i &= 1 \tag5\label5 \\ \sum_i z_i &= 1 \tag6\label6 \end{align} Constraints \eqref{1} and \eqref{2} enforce the logical implication $$y_i \implies \left(x_i \land \bigwedge_{j<i} \lnot x_j\right).$$ Constraints \eqref{3} and \eqref{4} enforce the logical implication $$z_i \implies \left(x_i \land \bigwedge_{j>i} \lnot x_j\right).$$ Then $$f = 1+\sum_i \left(i(z_i-y_i)-x_i\right).$$
Constraints \eqref{5} and \eqref{6} choose exactly one first and one last appointment, respectively.