Skip to main content

Generating And / Or Conditions Automatically from a List


I have the following list:




l1 = {x y, s t, a b}



From this list, I am trying to essentially generate a new list that looks like this:


    l1 = {x==1 && y==1 && s == 0 && t == 0 && a == 0 && b == 0
|| x == 0 && y == 0 && s == 1 && t == 1 && a == 0 && b == 0
|| x == 0 && y == 0 && s == 0 && t == 0 && a == 1 && b == 1}

I.e., only one pair at a time can take on the value of 1 in each OR statement.



Answer



l1 = {x y, s t, a b}; 


res1 = {Or @@
Inner[Sequence @@ Thread[Equal[List @@ #2, #]] &, IdentityMatrix[Length @ l1], l1, And]}


{(x == 1 && y == 1 && s == 0 && t == 0 && a == 0 && b == 0) ||
(x == 0 && y == 0 && s == 1 && t == 1 && a == 0 && b == 0) ||
(x == 0 && y == 0 && s == 0 && t == 0 && a == 1 && b == 1)}



Alternatively,



l2 = Flatten[l1 /. Times -> List]


{x, y, s, t, a, b}



res2 = {Or @@ 
Inner[Equal[#2, #] &, Riffle[#, #] & /@ IdentityMatrix[Length[l2]/2], l2, And]}


{(x == 1 && y == 1 && s == 0 && t == 0 && a == 0 && b == 0) ||

(x == 0 && y == 0 && s == 1 && t == 1 && a == 0 && b == 0) ||
(x == 0 && y == 0 && s == 0 && t == 0 && a == 1 && b == 1)}



Comments