Reputation: 13
I have a little logical problem that I would like to have solved someday!! Let's say you have 4 variables, I will call them a, b, c and d. Now based on some logic the following conditions are given.
The program passes:
if both a and d are filled
if both b and c are filled
if both b and d are filled
if both c and d are filled
the program fails:
So if you fill in one variable you are forced to fill in more. If you don't fill in any variable no action is needed.
To keep it simple I said that 1 equals filled and 0 equals not filled. My piece of code is not working correctly because if I say that only d is filled it gives back that this is okay. But it shouldn't work since only d is a fail.
Any idea's what I could do? Maybe my way of thinking about this is not correct? Keep in mind that the 0 and 1 are just to keep this simple, so adding a sum would not help!
Here is my code:
a = 0;
b = 0;
c = 0;
d = 1;
if a ~=0 || b ~=0 || c ~=0 || d ~=0
if ~(a~=0 || b~=0 && c~=0 || d~=0 )
works = 1;
else
no = 1;
end
end
Thank you for reading!
Upvotes: 0
Views: 147
Reputation: 3052
As the question is tagged MATLAB I will also give you a MATLAB solution. Basically your idea of adding a sum is just the way to go, just convert your variables to binary first, which is done with logical
. Thus the check for fail can be done with
arr = logical([a,b,c,d]);
fail = sum(logical(arr))==1 || all(arr(1:2))
Where the first condition checks how many have been filled and the second checks whether a
and b
are both set.
One should note, that there are cases that satisfy both pass and fail conditions (e.g. all variables set). The solution above is fail greedy. A pass greedy solution would be (as proposed by Cris Luengo in the comments)
arr = logical([a,b,c,d]);
fail = sum(logical(arr))==1 || all(arr==[1,1,0,0])
Upvotes: 1
Reputation: 868
If you want your code is more readable, you can use a method to do the logic, and the easiest way to do it just translate your logic.
public static boolean isParamFilled(boolean a, boolean b, boolean c, boolean d) {
if ((a || b) && (c || d)) return true;
if (c && d) return true;
int ia = a ? 1 : 0;
int ib = b ? 1 : 0;
int ic = c ? 1 : 0;
int id = d ? 1 : 0;
// Only one of the 4 parameters is filled.
if (ia + ib + ic + id == 1) return true;
if (a && b) return false;
// default value
return false;
}
public static void main(String...args) {
boolean a = false;
boolean b = false;
boolean c = false;
boolean d = true;
booledan worked = isParamFilled(a, b, c, d);
}
Upvotes: 1