How to test if exactly one condition is true? - boolean

If I have a set of boolean variables in Pascal, how can I test if exactly one of them is True?

In Pascal you can do this:
if Integer(a) + Integer(b) + Integer(c) = Integer(true) then
writeln("exactly one is true");
It's important to compare to Integer(true), since it could be different values in different versions of Pascal.

Related

string Variable comparison in swift3

i have two variable string both have same time like a= 4:15 PM and b = 4:15 PM
i am trying to compare these two variables in if to perform a specific task but it always returns false
is there any solution?
It would be easier to help if you provided some of the code you are having problems with. If you are absolutely certain both strings have the same exact sequence of characters it should be as simple as comparing them with a == b. You could try using breakpoints in xcode to check the state of the variables before they are compared.

What is the correct way to select real solutions?

Suppose one needs to select the real solutions after solving some equation.
Is this the correct and optimal way to do it, or is there a better one?
restart;
mu := 3.986*10^5; T:= 8*60*60:
eq := T = 2*Pi*sqrt(a^3/mu):
sol := solve(eq,a);
select(x->type(x,'realcons'),[sol]);
I could not find real as type. So I used realcons. At first I did this:
select(x->not(type(x,'complex')),[sol]);
which did not work, since in Maple 5 is considered complex! So ended up with no solutions.
type(5,'complex');
(* true *)
Also I could not find an isreal() type of function. (unless I missed one)
Is there a better way to do this that one should use?
update:
To answer the comment below about 5 not supposed to be complex in maple.
restart;
type(5,complex);
true
type(5,'complex');
true
interface(version);
Standard Worksheet Interface, Maple 18.00, Windows 7, February
From help
The type(x, complex) function returns true if x is an expression of the form
a + I b, where a (if present) and b (if present) are finite and of type realcons.
Your solutions sol are all of type complex(numeric). You can select only the real ones with type,numeric, ie.
restart;
mu := 3.986*10^5: T:= 8*60*60:
eq := T = 2*Pi*sqrt(a^3/mu):
sol := solve(eq,a);
20307.39319, -10153.69659 + 17586.71839 I, -10153.69659 - 17586.71839 I
select( type, [sol], numeric );
[20307.39319]
By using the multiple argument calling form of the select command we here can avoid using a custom operator as the first argument. You won't notice it for your small example, but it should be more efficient to do so. Other commands such as map perform similarly, to avoid having to make an additional function call for each individual test.
The types numeric and complex(numeric) cover real and complex integers, rationals, and floats.
The types realcons and complex(realcons) includes the previous, but also allow for an application of evalf done during the test. So Int(sin(x),x=1..3) and Pi and sqrt(2) are all of type realcons since following an application of evalf they become floats of type numeric.
The above is about types. There are also properties to consider. Types are properties, but not necessarily vice versa. There is a real property, but no real type. The is command can test for a property, and while it is often used for mixed numeric-symbolic tests under assumptions (on the symbols) it can also be used in tests like yours.
select( is, [sol], real );
[20307.39319]
It is less efficient to use is for your example. If you know that you have a collection of (possibly non-real) floats then type,numeric should be an efficient test.
And, just to muddy the waters... there is a type nonreal.
remove( type, [sol], nonreal );
[20307.39319]
The one possibility is to restrict the domain before the calculation takes place.
Here is an explanation on the Maplesoft website regarding restricting the domain:
4 Basic Computation
UPD: Basically, according to this and that, 5 is NOT considered complex in Maple, so there might be some bug/error/mistake (try checking what may be wrong there).
For instance, try putting complex without quotes.
Your way seems very logical according to this.
UPD2: According to the Maplesoft Website, all the type checks are done with type() function, so there is rather no isreal() function.

Simplify boolean expression i.t.o variable occurrence

How to simplify a given boolean expression with many variables (>10) so that the number of occurrences of each variable is minimized?
In my scenario, the value of a variable has to be considered ephemeral, that is, has to recomputed for each access (while still being static of course). I therefor need to minimize the number of times a variable has to be evaluated before trying to solve the function.
Consider the function
f(A,B,C,D,E,F) = (ABC)+(ABCD)+(ABEF)
Recursively using the distributive and absorption law one comes up with
f'(A,B,C,E,F) = AB(C+(EF))
I'm now wondering if there is an algorithm or method to solve this task in minimal runtime.
Using only Quine-McCluskey in the example above gives
f'(A,B,C,E,F) = (ABEF) + (ABC)
which is not optimal for my case. Is it save to assume that simplifying with QM first and then use algebra like above to reduce further is optimal?
I usually use Wolfram Alpha for this sort of thing.
Try Logic Friday 1
It features multi-level design of boolean circuits.
For your example, input and output look as follows:
You can use an online boolean expression calculator like https://www.dcode.fr/boolean-expressions-calculator
You can refer to Any good boolean expression simplifiers out there? it will definitely help.

When are booleans better than integers?

In most programming languages, 1 and 0 can be used instead of True and False. However, from my experience, integers seem to always be easier to use.
Here are some examples of what I mean:
if x is True: x = False
else: x = True
vs
x = abs(x-1)
__
if x is False: a = 0
else: a = 5
vs
a = 5*x
In what cases are booleans simpler/more efficient to use than 1 or 0?
You should always use any boolean built-in type for boolean values in high-level languages. Your second example would be a horror to debug in the case that x is true, but equal to a value different from 1, and a tricky one to figure out for any developer new to the code - especially one not familiar with your coding style.
What's wrong with
x = !x;
or
a = x ? 5 : 0;
One example where an integer could be more efficient than a boolean would be in a relational database. A bit column generally can't be indexed (I can't necessarily speak for all databases on that statement, hence "generally"), so something like a tinyint would make more sense if indexing is required.
Keep in mind that, depending on the use and on the system using it, while a boolean "takes less space" because it's just a single bit (depending on the implementation), an integer is the native word size of the hardware. (Certain systems likely use a full word for a boolean, essentially saving no space when it actually runs on the metal, just to use a simple word size.)
In high-level programming languages, the choice between a boolean and an int is really more of code readability/supportability than one of efficiency. If the values are indeed limited to "true" or "false" then a boolean makes sense. (Is this model in a given state, such as "valid," or is it not? It will never be a third option.) If, on the other hand, there are currently two options but there could be more someday, it might be tempting to use a boolean (even just "for now") but it would logically make more sense to use an int (or an enum).
Keep that in mind also when doing "clever" things in code. Sure, it may look sleeker and cooler to do some quick int math instead of using a boolean, but what does that do to the readability of the code? Being too clever can be dangerous.
For readibility and good intentions, it's always better to choose booleans for true/false.
You know that you have only two possible choices. With integers, things can get a bit tricky, especially if you're using 0 as false and anything else as true.
You can get too clever when using integers for true/false, so be careful.
Using booleans will make your intentions clearer to you 6 months later and other people who will maintain your code. The less brain cycles you have to use, the better.
I'd say in your examples that the boolean versions are more readable (at least as far as your intentions). It all depends on the context too. If you're sacrificing readability in an attempt to make micro optimizations, that's just evil.
I'm not sure about efficiency but I prefer booleans in many cases.
Your first example could be easily written as x = !x and x = abs(x-1) looks really obscure to me.
Also when using integers, you can't really be sure if x is 1 and not 2 or -5 or anything. When using booleans, it's always just true or false.
It's always more efficient to use Boolean because it's easier to process and uses less processing/memory. Whenever possible, use Boolean
Booleans obviously can only accept true/false or 0/1, not only that they use less processing power and memory as Webnet has already stated.
Performance points aside, I consider booleans and integers to be two fundamentally different concepts in programming. Boolean represents a condition, an integer represents a number. Bugs are easy to introduce if you don't strictly keep the value of your integer-boolean 0 or not 0, and why bother even with that when you can just use booleans, that allow for compile-time security / typechecking? I mean, take a method:
doSomething(int param)
The method alone does /not/ imply the param is interpreted as a boolean. Nobody will stop me from passing 1337 to it, and nobody will tell me what'll happen if I do - and even if it's clearly documented not to pass the 1337 value to the method (but only 0 or 1), I can still do it. If you can prevent errors at compile time, you should.
doSomething(bool param)
only allows two values: true and false, and neither are wrong.
Also, your examples about why integers would be better than booleans are kinda flawed.
if x is True: x = False
else: x = True
could be written as
x != x
whereas your integer alternative:
x = abs(x-1)
would require me to know:
What possible values x can have
what the abs() function does
why 1 is subtracted from x
what this actually /does/. What does it do?
Your second example is also a big wtf to me.
if x is False: a = 0
else: a = 5
could be written as:
a = (x) ? 5 : 0;
whereas your integer alternative
a = 5*x
again requires me to know:
What is X?
What can X be?
What happens if x = 10? -1? 2147483647?
Too much conditionals. Use booleans, for both readability, common sense, and bug-free, predictable code.
I love booleans, so much more readable and you've basically forced a contract with the user.
E.g. "These values are ONLY TRUE or FALSE".

Methods of simplifying ugly nested if-else trees in C#

Sometimes I'm writing ugly if-else statements in C# 3.5; I'm aware of some different approaches to simplifying that with table-driven development, class hierarchy, anonimous methods and some more.
The problem is that alternatives are still less wide-spread than writing traditional ugly if-else statements because there is no convention for that.
What depth of nested if-else is normal for C# 3.5? What methods do you expect to see instead of nested if-else the first? the second?
if i have ten input parameters with 3 states in each, i should map functions to combination of each state of each parameter (really less, because not all the states are valid, but sometimes still a lot). I can express these states as a hashtable key and a handler (lambda) which will be called if key matches.
It is still mix of table-driven, data-driven dev. ideas and pattern matching.
what i'm looking for is extending for C# such approaches as this for scripting (C# 3.5 is rather like scripting)
http://blogs.msdn.com/ericlippert/archive/2004/02/24/79292.aspx
Good question. "Conditional Complexity" is a code smell. Polymorphism is your friend.
Conditional logic is innocent in its infancy, when it’s simple to understand and contained within a
few lines of code. Unfortunately, it rarely ages well. You implement several new features and
suddenly your conditional logic becomes complicated and expansive. [Joshua Kerevsky: Refactoring to Patterns]
One of the simplest things you can do to avoid nested if blocks is to learn to use Guard Clauses.
double getPayAmount() {
if (_isDead) return deadAmount();
if (_isSeparated) return separatedAmount();
if (_isRetired) return retiredAmount();
return normalPayAmount();
};
The other thing I have found simplifies things pretty well, and which makes your code self-documenting, is Consolidating conditionals.
double disabilityAmount() {
if (isNotEligableForDisability()) return 0;
// compute the disability amount
Other valuable refactoring techniques associated with conditional expressions include Decompose Conditional, Replace Conditional with Visitor, Specification Pattern, and Reverse Conditional.
There are very old "formalisms" for trying to encapsulate extremely complex expressions that evaluate many possibly independent variables, for example, "decision tables" :
http://en.wikipedia.org/wiki/Decision_table
But, I'll join in the choir here to second the ideas mentioned of judicious use of the ternary operator if possible, identifying the most unlikely conditions which if met allow you to terminate the rest of the evaluation by excluding them first, and add ... the reverse of that ... trying to factor out the most probable conditions and states that can allow you to proceed without testing of the "fringe" cases.
The suggestion by Miriam (above) is fascinating, even elegant, as "conceptual art;" and I am actually going to try it out, trying to "bracket" my suspicion that it will lead to code that is harder to maintain.
My pragmatic side says there is no "one size fits all" answer here in the absence of a pretty specific code example, and complete description of the conditions and their interactions.
I'm a fan of "flag setting" : meaning anytime my application goes into some less common "mode" or "state" I set a boolean flag (which might even be static for the class) : for me that simplifies writing complex if/then else evaluations later on.
best, Bill
Simple. Take the body of the if and make a method out of it.
This works because most if statements are of the form:
if (condition):
action()
In other cases, more specifically :
if (condition1):
if (condition2):
action()
simplify to:
if (condition1 && condition2):
action()
I'm a big fan of the ternary operator which get's overlooked by a lot of people. It's great for assigning values to variables based on conditions. like this
foobarString = (foo == bar) ? "foo equals bar" : "foo does not equal bar";
Try this article for more info.
It wont solve all your problems, but it is very economical.
I know that this is not the answer you are looking for, but without context your questions is very hard to answer. The problem is that the way to refactor such a thing really depends on your code, what it is doing, and what you are trying to accomplish. If you had said that you were checking the type of an object in these conditionals we could throw out an answer like 'use polymorphism', but sometimes you actually do just need some if statements, and sometimes those statements can be refactored into something more simple. Without a code sample it is hard to say which category you are in.
I was told years ago by an instructor that 3 is a magic number. And as he applied it it-else statements he suggested that if I needed more that 3 if's then I should probably use a case statement instead.
switch (testValue)
{
case = 1:
// do something
break;
case = 2:
// do something else
break;
case = 3:
// do something more
break;
case = 4
// do what?
break;
default:
throw new Exception("I didn't do anything");
}
If you're nesting if statements more than 3 deep then you should probably take that as a sign that there is a better way. Probably like Avirdlg suggested, separating the nested if statements into 1 or more methods. If you feel you are absolutely stuck with multiple if-else statements then I would wrap all the if-else statements into a single method so it didn't ugly up other code.
If the entire purpose is to assign a different value to some variable based upon the state of various conditionals, I use a ternery operator.
If the If Else clauses are performing separate chunks of functionality. and the conditions are complex, simplify by creating temporary boolean variables to hold the true/false value of the complex boolean expressions. These variables should be suitably named to represent the business sense of what the complex expression is calculating. Then use the boolean variables in the If else synatx instead of the complex boolean expressions.
One thing I find myself doing at times is inverting the condition followed by return; several such tests in a row can help reduce nesting of if and else.
Not a C# answer, but you probably would like pattern matching. With pattern matching, you can take several inputs, and do simultaneous matches on all of them. For example (F#):
let x=
match cond1, cond2, name with
| _, _, "Bob" -> 9000 // Bob gets 9000, regardless of cond1 or 2
| false, false, _ -> 0
| true, false, _ -> 1
| false, true, _ -> 2
| true, true, "" -> 0 // Both conds but no name gets 0
| true, true, _ -> 3 // Cond1&2 give 3
You can express any combination to create a match (this just scratches the surface). However, C# doesn't support this, and I doubt it will any time soon. Meanwhile, there are some attempts to try this in C#, such as here: http://codebetter.com/blogs/matthew.podwysocki/archive/2008/09/16/functional-c-pattern-matching.aspx. Google can turn up many more; perhaps one will suit you.
try to use patterns like strategy or command
In simple cases you should be able to get around with basic functional decomposition. For more complex scenarios I used Specification Pattern with great success.