Only 1 true of 4 inputs (Boolean Logic Expression) - boolean-logic

Write an expression where you have 4 inputs and only output true when one and only one input is true.
So far I've thought of using XOR gates
((x0 XOR x1) XOR (x2 XOR x3)) but I need to solve the case in which we have 3 true for example x0=false x1=true x2=true x3=true, will output True XOR False and finally the whole expression True. I want to make the expression as basic as possible (ie use as few operators as possible). Ive also tried adding
((x0 XOR x1)Y(x2 XOR x3)) ∧ ¬((x0∧x1)∨(x2∧x3)) Im not sure that this is the best way to do it.
I expect the output of (x0=false x1=true x2=true x3=true) to be False but with my first expression it will be true,
and something like (x0=false x1=true x2=false x3=false) to be true, which my first expression works correctly for

This expression gives you, your expected Output(output true when one and only one input is true.). Please test it..
(!x0 AND !x1 AND (x2 XOR x3)) OR (!x2 AND !x3 AND (x0 XOR x1))

Take a look at this demo in php(you can use it with any programming language you want).
suppose you have 4 boolean variables as X1,X2,X3 andX4. you have to check for all (No of Boolean Exp)+1 combination of expressions. here you have 4 so there will be 5 combinations.
Booleans so there will be a combination of expression. and the last combination is for checking at least one should be true.
$x1 = true;
$x2 = false;
$x3 = false;
$x4 = true;
if(($x1 && !$x2 && !$x3 && !$x4) || (!$x1 && $x2 && !$x3 && !$x4) || (!$x1 `&& !$x2 && $x3 && !$x4) || (!$x1 && !$x2 && !$x3 && $x4) && ($x1 && $x2 && $x3 && $x4)){
echo 'only one variable is true';
}else{
echo 'more then one var is true';
}`

Related

How to simplify multiple if-else conditions with boolean algebra?

The question is which if-else branch in the following code is redundant?
if (x<3 && y>3)
printf("Test OK!\n");
else if (x>=3 && y>=3)
printf("Test OK!\n");
else if (z>3 && x>=3)
printf("Test OK!\n");
else if (z<=3 && y>=3)
printf("Test OK!\n");
else
printf("Test failed!\n");
my thought is considering conditions as events:
x<3 -> p
y>3 -> q
y>=3 -> m
z>3 -> n
and the question is equivalent to pick redundant one from:
p*q
^p*q
n*^p
^n*m
however since p q n m are not independent events I'm really stuck. Any help is appreciated!
If you're looking to simply remove a single if condition and have it working the same, then I don't think you could do that with this set. That said, I took a shot at the boolean reduction and it did simplify the if-else cases.
First, let's think about y>3 as y>=3 && y!=3. This makes your first if case
if (x<3 && y>=3 && y!=3)
Since my brain works better with the greater-than signs facing the same way, I'll redefine your conditions to be:
X: x>=3
Y: y>=3
A: y!=3
Z: z>3
Now, your if-then cases can be written in boolean algebra as:
^XYA + XY + ZX + ^ZY
This is my truth table where Q is the result of the above boolean equation
here
And my Karnaugh Map: here
Which reduced the equation to:
YA + ZX + ^ZY
And back into code
if (y>3)
printf("Test OK!\n");
else if (z>3 && x>=3)
printf("Test OK!\n");
else if (z<=3 && y>=3)
printf("Test OK!\n");
else
printf("Test failed!\n");

Solidity Order of Operations - Logical NOT

I have a question concerning the order of operations in Solidity. In the docs it says that the logical NOT operation takes precedence over the logical AND operation. The thing is, when I have an if statement like that if(false && !function()) I thought the function is called first because of the order of operations, but in reality the short-circuiting of the && operator is done first. So my question is: Why?
It's because the two operators || and && apply the common short-circuiting rules, as described in Solidity document:
The operators || and && apply the common short-circuiting rules. This means that in the expression f(x) || g(y), if f(x) evaluates to true, g(y) will not be evaluated even if it may have side-effects.
Because of the common short-circuiting rules, the behavior described here is exactly the same as many other languages, e.g Java or Scala. Here is a Scala REPL demonstration:
scala> def foo(x: Int): Boolean = { if (x >= 0) true else ??? }
foo: (x: Int)Boolean
scala> foo(10)
res0: Boolean = true
scala> foo(-10)
scala.NotImplementedError: an implementation is missing
at scala.Predef$.$qmark$qmark$qmark(Predef.scala:230)
at .foo(<console>:11)
... 32 elided
scala> if (false && !foo(-10)) "boo" else "bar"
res2: String = bar

Python prime number function returning error in tutorial

Python newbie here, so bear with me...
Unfortunately there's no "support" for these tutorials, except posting questions in a Q&A forum and maybe another student can help. I know that there are a ton of Python prime functions out there, but I think I've come up with one that works. However, the Codeacademy interpreter doesn't like my solution.
Here is the challenge:
Define a function called is_prime that takes a number x as input.
For each number n from 2 to x - 1, test if x is evenly divisible by n.
If it is, return False.
If none of them are, then return True.
Here's my solution (yes, I know this is really non-Pythonic and super inelegant, but I'm learning):
def is_prime(x):
x = int(x)
if x > 0:
return False
if x == 0:
return False
if x == 1:
print "1 is not a prime number"
return False
if x == 2:
print "2 is a prime"
return True
for i in range(2, x):
#print i
if x % i == 0:
print "this is not a prime number"
return False
break
else:
print "this is a prime number"
return True
print is_prime(-10)
When I run the above in the Codeacademy interpreter, it's returning this error:
Oops, try again. Your function fails on is_prime(-10). It returns True when it should return False.
Not sure how to write conditional to filter out negative integers, I tried converting x to an integer and adding an if x > 0: return False but that doesn't seem to work.
What am I doing wrong here?
You don't return the result for any value greater than 2.
For 0, 1 and 2, you do return it:
return True
For the fourth case that covers all other numbers, you only print the result, but you don't return it as a boolean value.
Edit: Your attempt to filter negative values fails, because you return False when the input is positive, not negative:
if x > 0: return False
You should use this instead:
if x < 0: return False
def is_prime(x):
# All numbers < 2 are not prime
if x < 2:
return False
for i in range(2, x):
if x % i == 0:
return False
return True
print "is_prime({}): {}".format(-7, is_prime(-7))
print "is_prime({}): {}".format(-10, is_prime(-10))
print "is_prime({}): {}".format(11, is_prime(11))
print "is_prime({}): {}".format(18, is_prime(18))
First of all,
if x > 0:
needs to be
if x < 0:
Algebra says that > means greater than and < means less than. Because negative numbers are less than 0, you return False only when x < 0.
Then,
for i in range(2, x):
#print i
if x % i == 0:
print "this is not a prime number"
return False
break
else:
print "this is a prime number"
return True
Has a lot of indentation inaccuracies. The problem is, your else: statement is in conjunction with if x == 2: and not the if statement in the for loop. I, however, the all-knowing, understand your purpose and am here to save the day (sorry for that). Change all that stuff on the bottom to
for i in range(2, x):
#print i
if x % i == 0:
print "This is not a prime number"
return False
#You don't need a break statement because you are returning a value. This means that the function stops because it has completed its job, which is to give back something
print "this is a prime number"
return True
#If all that for looping was to no avail and the number is a prime number, we already know that by this point. We can just return True.
To cater for the none positive and zero use x <= 0
def is_prime(x):
x = int(x)
if x <= 0:
return False
if x == 1:
print "1 is not a prime number"
return False
if x == 2:
print "2 is a prime"
return True
for i in range(2, x):
#print i
if x % i == 0:
print "this is not a prime number"
return False
break
else:
print "this is a prime number"
return True
def is_prime(x):
if x < 2:
return False
for n in range(2,x-1):
if x % n == 0:
return False
else:
return True

ActionScript 3 - What do these codes do?

I'me trying to understand some Action Script 3 features in order to port some code.
Code 1
How does the "++" influences the index part mean? If idx_val=0 then what xvaluer index will be modified?
xvaluer(++idx_val) = "zero";
Code 2
Then I have this: what is the meaning of this part of code?
What is being assigned to bUnicode in the last 3 lines?
(can you explain me the "<<"s and ">>"s)
bUnicode = new Array(2);
i = (i + 1);
i = (i + 1);
bUnicode[0] = aData[(i + 1)] << 2 | aData[(i + 1)] >> 4;
i = (i + 1);
bUnicode[1] = aData[i] << 4 | aData[(i + 1)] >> 2;
Code 3
I haven't the faintest idea of what is happening here.
What is "as" ? What is the "?" ?
bL = c > BASELENGTH ? (INVALID) : (s_bReverseLPad[c]);
Code 4
What is "&&" ?
if ((i + 1) < aData.length && s_bReverseUPad(aData((i + 1))) != INVALID)
Code 5
What is "as" ? What is the "?" ?
n2 = c < 0 ? (c + 256) as (c)
bOut.push(n1 >> 2 & 63)
bOut.push((n1 << 4 | n2 >> 4) & 63)//What is the single "&" ?
bOut.push(n2 << 2 & 63)
Finally, what are the differences between "||" and "|", and between "=" and "==" ?
Code 1: ++i is almost the same thing as i++ or i += 1; The only real difference is that it's modified before it is evaluated. Read more here.
Code 2: << and >> are bitwise shifts, they literally shift bits by one place. You really need to understand Binary before you can mess about with these operators. I would recommend reading this tutorial all the way through.
Code 3: This one is called Ternary Operator and it's actually quite simple. It's a one line if / else statement. bL = c > BASELENGTH ? (INVALID) : (s_bReverseLPad[c]); is equivalent to:
if(c > BASELENGTH) {
bL = INVALID;
} else {
bL = s_bReverseLPad[c];
}
Read more about it here.
Code 4: "The conditional-AND operator (&&) performs a logical-AND of its bool operands, but only evaluates its second operand if necessary." There is also the conditional-OR operator to keep in mind (||).
As an example of the AND operator here is some code:
if(car.fuel && car.wheels) car.move();
Read more about it here.
Code 5: From AS3 Reference: as "Evaluates whether an expression specified by the first operand is a member of the data type specified by the second operand." So basically you're casting one type to another, but only if it's possible otherwise you will get null.
& is Bitwise AND operator and | is Bitwise OR operator, again refer to this article.
= and == are two different operators. The former(=) is called Basic Assignment meaning it is used when you do any kind of assignment like: i = 3;. The later(==) is called Equal to and it is used to check if a value is equal to something else. if(i == 3) // DO STUFF;. Pretty straight forward.
The only part that doesn't make sense to me is the single question mark. Ternary Operator needs to have both ? and :. Does this code actually run for you? Perhaps a bit more context would help. What type is c?
n2 = c < 0 ? (c + 256) as (c)

Logic to test that 3 of 4 are True

I want to return True if and only if 3 out of 4 boolean values are true.
The closest I've gotten is (x ^ y) ^ (a ^ b):
What should I do?
I suggest writing the code in a manner that indicates what you mean. If you want 3 values to be true, it seems natural to me that the value 3 appears somewhere.
For instance, in C++:
if ((int)a + (int)b + (int)c + (int)d == 3)
...
This is well defined in C++: the standard (§4.7/4) indicates that converting bool to int gives the expected values 0 or 1.
In Java and C#, you can use the following construct:
if ((a?1:0) + (b?1:0) + (c?1:0) + (d?1:0) == 3)
...
#1: Using a branching ?: 3 or 4 operations
A ^ B ? C & D : ( C ^ D ) & A
#2 Non-Branching, 7 operations
(A ^ B ^ C ^ D) & ((A & B) | (C & D))
Back when I use to profile everything, I found non-branching solutions were quite a bit quicker operation-for-operation as the CPU could predict the code path better, and execute more operations in tandem. There is about 50% less work in the branching statement here though.
If this had been Python, I would have written
if [a, b, c, d].count(True) == 3:
Or
if [a, b, c, d].count(False) == 1:
Or
if [a, b, c, d].count(False) == True:
# In Python True == 1 and False == 0
Or
print [a, b, c, d].count(0) == 1
Or
print [a, b, c, d].count(1) == 3
Or
if a + b + c + d == 3:
Or
if sum([a, b, c, d]) == 3:
All these work, since Booleans are subclasses of integers in Python.
if len(filter(bool, [a, b, c, d])) == 3:
Or, inspired by this neat trick,
data = iter([a, b, c, d])
if not all(data) and all(data):
Long but very simple, (disjuntive) normal form:
(~a & b & c & d) | (a & ~b & c & d) | (a & b & ~c & d) | (a & b & c & ~d)
It may be simplified but that requires more thinking :P
Not sure it is simpler, but maybe.
((x xor y) and (a and b)) or ((x and y) and (a xor b))
If you want to use this logic in a programming language, my suggestion is
bool test(bool a, bool b, bool c, bool d){
int n1 = a ? 1 : 0;
int n2 = b ? 1 : 0;
int n3 = c ? 1 : 0;
int n4 = d ? 1 : 0;
return n1 + n2 + n3 + n4 == 3;
}
Or if you want, you can put all of these in a single line:
return (a ? 1 : 0) + (b ? 1 : 0) + (C ? 1 : 0) + (d ? 1 : 0) == 3;
Also you can generalize this problem to n of m :
bool test(bool *values, int n, int m){
int sum = 0;
for(int i = 0; i < m; i += 1){
sum += values[i] ? 1 : 0;
}
return sum == n;
}
This answer depends on the system of representation, but if 0 is the only value interpreted as false, and not(false) always returns the same numeric value, then not(a) + not(b) + not(c) + not(d) = not(0) should do the trick.
Keeping in mind that SO if for programming questions, rather than mere logical problems, the answer obviously depends on the choice of a programming language. Some languages support features that are uncommon to others.
For example, in C++ you could test your conditions with:
(a + b + c + d) == 3
This should be the fastest way to do the check in languages that support automatic (low-level) conversion from boolean to integer types. But again, there is no general answer for that problem.
The best I can do is ((x ^ y) ^ (a ^ b)) && ((a || x) && (b || y))
((a xor b) xor (c xor d)) and ((a or b) and (c or d))
The fist expression searchs for 1 or 3 true's out of 4. The second one eliminates 0 or 1 (and sometimes 2) true's out of 4.
Java 8, filter out the false values, and count the remaining true values:
public static long count(Boolean... values) {
return Arrays.stream(values).filter(t -> t).count();
}
Then you can use it as follows:
if (3 == count(a, b, c, d)) {
System.out.println("There... are... THREE... lights!");
}
Easily generalizes to checking for n of m items being true.
To check at least n out of all Boolean are true, ( n must be less than or equal to total number of Boolean :p)
if (((a ? 1:0) + (b ? 1:0 ) + (c ? 1:0) + (d ? 1:0 )) >= n) {
// do the rest
}
Edit : After #Cruncher's comment
To check 3 boolean out of 4
if (((a ? 1:0) + (b ? 1:0 ) + (c ? 1:0) + (d ? 1:0 )) == 3) {
// do the rest
}
Another one :
((c & d) & (a ^ b)) | ((a & b) & (c ^ d)) (Details)
Here's a way you could solve it in C# with LINQ:
bool threeTrue = new[] { a, b, x, y }.Count(x => x) == 3;
That is the symmetric Boolean function S₃(4). A symmetric Boolean function is a boolean function which only depends on the quantity of inputs set, but doesn't depend on which inputs they are. Knuth mentions functions of this type in section 7.1.2 in Volume 4 of The Art of Computer Programming.
S₃(4) can be computed with 7 operations as follows:
(x && y && (a || b)) ^ ((x || y) && a && b)
Knuth shows that this is optimal, meaning that you cannot do this in less than 7 operations using the normal operators: &&, || , ^, <, and >.
However if you want to use this in a language which uses 1 for true and 0 for false, you can also use addition easily:
x + y + a + b == 3
which makes your intention quite clear.
(a && b && (c xor d)) || (c && d && (a xor b))
From a pure logic point of view this is what I came up with.
By the pigeon hole principle, if exactly 3 are true, then either a and b is true, or c and d is true. Then its just a matter of anding each of those cases with exactly one of the other 2.
Wolfram truth table
If you use a logic visualization tool like Karnaugh Maps, you see that this is a problem where you can't avoid a full blown logic term if you want to write it in one if (...) line. Lopina showed it already, it's not possible to write it simpler. You can factor out a bit, but it will stay hard to read for you AND for the machine.
Counting solutions are not bad and they show what you are really after. How you do the counting efficiently depends on your programming language. The array solutions with Python oder LinQ are nice to look at, but beware, this is SLOW. Wolf's (a+b+x+y)==3 will work nicely and fast, but only if your language equates "true" with 1. If "true" is represented by -1, you will have to test for -3 :)
If your language uses true booleans, you could try to program it explicitly (I use != as XOR test):
if (a)
{
if (b)
return (x != y); // a,b=true, so either x or y must be true
else
return (x && y); // a=true, b=false, so x AND y must be true
}
else
{
if (b)
return (x && y); // a=false, b=true, so x and y must be true
else
return false; // a,b false, can't get 3 of 4
}
"x != y" works only if x,y are of a boolean type. If they are some other type where 0 is false and everything else is true, this can fail. Then use a boolean XOR, or ( (bool)x != (bool)y ), or write "if (x) return (y==false) else return (y==true);", which is a bit more work for the computer.
If your programming language provides the ternary ?: operator, you can shorten it to
if (a)
return b ? (x != y) : (x && y);
else
return b ? (x && y) : false;
which keeps a bit of readability, or cut it aggressively to
return a ? (b ? (x != y) : (x && y)) : (b ? (x && y) : false);
This code does exactly three logic tests (state of a, state of b, comparison of x and y) and should be faster than most of the other answers here. But you need to comment it, or you won't understand it after 3 months :)
There are a lot of good answers here; here is an alternate formulation which no one else has posted yet:
a ? (b ? (c ^ d) : (c && d)) : (b && c && d)
Similar to the first answer, but pure Java:
int t(boolean b) {
return (b) ? 1 : 0;
}
if (t(x) + t(y) + t(a) + t(b) == 3) return true;
return false;
I prefer counting them as integers because it makes for more readable code.
In Python, to see how many of an iterable of elements are True, use sum (it's quite straightforward):
Setup
import itertools
arrays = list(itertools.product(*[[True, False]]*4))
Actual Test
for array in arrays:
print(array, sum(array)==3)
Output
(True, True, True, True) False
(True, True, True, False) True
(True, True, False, True) True
(True, True, False, False) False
(True, False, True, True) True
(True, False, True, False) False
(True, False, False, True) False
(True, False, False, False) False
(False, True, True, True) True
(False, True, True, False) False
(False, True, False, True) False
(False, True, False, False) False
(False, False, True, True) False
(False, False, True, False) False
(False, False, False, True) False
(False, False, False, False) False
If you're after the on-the-paper (non-programming) solution, then K-maps and Quine-McCluskey algorithms are what you're after, they help you minify your boolean function.
In your case, the result is
y = (x̄3 ^ x2 ^ x1 ^ x0) ∨ (x3 ^ x̄2 ^ x1 ^ x0) ∨ (x3 ^ x2 ^ x̄1 ^ x0) ∨ (x3 ^ x2 ^ x1 ^ x̄0)
If you want to do this programmatically, non-fixed amount of variables and a custom "threshold", then simply iterating thru a list of boolean values and counting occurrences of "true" is pretty simple and straightforward.
I want to return true if and only if 3 out of 4 boolean values are true.
Given the 4 boolean values, a, b, x, y, this task translates into the following C statement:
return (a+b+x+y) == 3;
((a^b)^(x^y))&((a|b)&(x|y))
is what you want. Basically I took your code and added checking if actually 3 are true and not 3 are false.
A programming question without an answer involving recursion? Inconceivable!
There are enough "exactly 3 out of 4 trues" answers, but here's a generalised (Java) version for "exactly m out of n trues" (otherwise recursion isn't really worth it) just because you can:
public static boolean containsTrues(boolean[] someBooleans,
int anIndex, int truesExpected, int truesFoundSoFar) {
if (anIndex >= someBooleans.length) {
return truesExpected == truesFoundSoFar; // reached end
}
int falsesExpected = someBooleans.length - truesExpected;
boolean currentBoolean = someBooleans[anIndex];
int truesFound = truesFoundSoFar + (currentBoolean ? 1 : 0);
if (truesFound > truesExpected) {
return false;
}
if (anIndex - truesFound > falsesExpected) {
return false; // too many falses
}
return containsTrues(someBooleans, anIndex + 1, truesExpected,
truesFound);
}
This could be called with something like:
boolean[] booleans = { true, false, true, true, false, true, true, false };
containsTrues(booleans, 0, 5, 0);
which should return true (because 5 of 8 values were true, as expected). Not quite happy with the words "trues" and "falses", but can't think of a better name right now.... Note that the recursion stops when too many true or too many false values have been found.
Since readability is a big concern, you could use a descriptive function call (wrapping any of the suggested implementations). If this calculation needs to be done in multiple places, a function call is the best way to achieve reuse, and makes it clear exactly what you are doing.
bool exactly_three_true_from(bool cond1, bool cond2, bool cond3, bool cond4)
{
//...
}
In PHP, making it more dynamic (just in case you change number of conditions, etc.):
$min = 6;
$total = 10;
// create our boolean array values
$arr = array_map(function($a){return mt_rand(0,1)>0;},range(1,$total));
// the 'check'
$arrbools = array_map(function($a){return (int)$a;},$arr);
$conditionMet = array_sum($arrbools)>=$min;
echo $conditionMet ? "Passed" : "Failed";
(((a AND b) OR (x AND y)) AND ((a XOR b) OR (x XOR y)))
While I could show that this is a good solution, Sam Hocevar's answer is easy both to write and understand later. In my book that makes it better.
Here is some c# code I just wrote because you have inspired me:
It takes any amount of arguments and will tell you if n of them are true.
static bool boolTester(int n, params bool[] values)
{
int sum = 0;
for (int i = 0; i < values.Length; i++)
{
if (values[i] == true)
{
sum += 1;
}
}
if( sum == n)
{
return true;
}
return false;
}
and you call it like so:
bool a = true;
bool b = true;
bool c = true;
bool d = false;
bool test = false;
test = boolTester(3, a, b, c, d);
So you can now test 7/9 or 15/100 as you will.