Map integer to binary
AnsweredI am want to model a situation that:
N is an integer variable, and n0,n1,n2 are binary variables.
I wish that when N % 3 == 0, n0 = 1 and others =0; when N % 3 == 1, n1 = 1 and others =0; when N % 3 == 2, n2 = 1 and others =0;
Want to ask how to achieve such constraints in Gurobi. Thank you
-
Official comment
This post is more than three years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum. Or why not try our AI Gurobot?. -
Hi,
It is possible with two auxiliary variables and a couple of equality constraints. First, we have to model the modulo operation
\[\begin{align}
N &= n + 3 k\\
N &\in \mathbb{Z}_{\geq 0}, n \in \{0,1,2\}, k \in \mathbb{Z}_{\geq 0}
\end{align}\]Integer variable \(n\) gives us the result of the modulo operation. Next we need to model the \(\texttt{if}\)-relationships.
\[\begin{align}
2 n_0 &+ 3 n_1 + 4 n_2 = n+2 \\
&n_0, n_1, n_2 \in \{0,1\}
\end{align}\]The above equality constraint states that, when \(n=0\), then only \(n_0=1\), if \(n=1\), then only \(n_1=1\), and if \(n=2\), then only \(n_2=1\).
Please note that the above is just one of many possible formulations and is not guaranteed to be the best one.
Best regards,
Jaromił0 -
Thank you Jaromił! This solution really inspires me!
0
Post is closed for comments.
Comments
3 comments