Check if a variable has any value from a given set - conditional-statements

How can I check if a condition passes multiple values?
Example:
if(number == 1,2,3)
I know that commas don't work.

if (number == 1 || number == 2 || number == 3)

If you are using PHP, then suppose your list of numbers is an array
$list = array(1,3,5,7,9);
then for any element, you can use
if(in_array($element, $list)){
//Element present in list
}else{
//not present.
}
Function structure:
bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )
Hope that helps.

if ((number >= 1) && (number <= 3))

What language?
For example in VB.NET you use the word OR, and in C# you use ||

Since you specify no language I add a Python solution:
if number in [1, 2, 3]:
pass

In T-SQL you can use the IN operator:
select * from MyTable where ID in (1,2,3)
If you are using a collection there may be a contains operator for another way to do this.
In C# for another way that may be easier to add values:
List<int> numbers = new List<int>(){1,2,3};
if (numbers.Contains(number))

I'll assume a C-Style language, here's a quick primer on IF AND OR logic:
if(variable == value){
//does something if variable is equal to value
}
if(!variable == value){
//does something if variable is NOT equal to value
}
if(variable1 == value1 && variable2 == value2){
//does something if variable1 is equal to value1 AND variable2 is equal to value2
}
if(variable1 == value1 || variable2 = value2){
//does something if variable1 is equal to value1 OR variable2 is equal to value2
}
if((variable1 == value1 && variable2 = value2) || variable3 == value3){
//does something if:
// variable1 is equal to value1 AND variable2 is equal to value2
// OR variable3 equals value3 (regardless of variable1 and variable2 values)
}
if(!(variable1 == value1 && variable2 = value2) || variable3 == value3){
//does something if:
// variable1 is NOT equal to value1 AND variable2 is NOT equal to value2
// OR variable3 equals value3 (regardless of variable1 and variable2 values)
}
So you can see how you can chain these checks together to create some pretty complex logic.

For a list of integers:
static bool Found(List<int> arr, int val)
{
int result = default(int);
if (result == val)
result++;
result = arr.FindIndex(delegate(int myVal)
{
return (myVal == val);
});
return (result > -1);
}

In Java you have objects that wrap primitive variables (Integer for int, Long for long, etc). if you look to compare values between a lot of complete numbers (ints), what you can do is initiate a bunch of Integer objects, stuff them inside an iterable such as an ArrayList, iterate over them and compare.
something like:
ArrayList<Integer> integers = new ArrayList<>();
integers.add(13);
integers.add(14);
integers.add(15);
integers.add(16);
int compareTo = 17;
boolean flag = false;
for (Integer in: integers) {
if (compareTo==in) {
// do stuff
}
}
of course for a few values this may be a bit unwieldy, but if you want to compare against a lot of values, it'll work nicely.
Another option is to use java Sets, you can place a lot of different values (the collection will sort your input, which is a plus) and then invoke the .contains(Object) method to locate equality.

Related

how do i correctly use >= and <= in code?

I have tried many thing involving this, >=, >==, =>, ==>.i can not find one that works. hey all return either primary expression needed or expected initializer before '>'. I am creating a IR receiver latch switch and thus have to create parameters for the code because the receiver is not constant in all conditions. Full code below. Any suggestions to fix the code please reply and don't DM me. Thank you.
code:
int LEDState = 0;
int LEDPin = 8;
int dt = 100;
int recieverOld ==> 500 and recieverOld ==< 2000;
int recieverNew;
int recieverPin = 12;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(LEDPin, OUTPUT);
pinMode(recieverPin, INPUT);
}
void loop() {
// put your main code here, to run repeatedly:
recieverNew = digitalRead(recieverPin);
if((recieverOld >== 0 && recieverOld <== 10) && (recieverNew >== 500 && recieverNew <== 2000) {
if(LEDState == 0) {
digitalWrite(LEDPin, HIGH);
LEDState = 1;
}
}
recieverOld = recieverNew;
delay(dt);
}
error:
expected initializer before '==' token
if one = used line 4 and related, return error expected primary-expression before '>' token
if > before = line 4 and related, return error expected initializer before '>=' token
Any solutions or suggestions welcome.
TL;DR
Operators that do no exist, and that you should NOT use:
==>, ==<, >==, <==
Operators that works and you can use them:
>= - MORE THAN OR EQUAL, compare operator, for example X >= 5
<= - LESS THAN OR EQUAL, compare operator, for example X <= 5
> - MORE THAN, compare operator, for example X > 5
< - LESS THAN, compare operator, for example X < 5
== - compare operator, when you want to compare values of the variables if they have the same value, for example X == 5, Y == X, 10 == 7
=== - equality operator, similar to compare operator ==, but aditionally checks the type of a variable. for example X === Y, '10' === 10
= - assign operator, when you want to assign something to the variable, for example X = 5
<> OR != - NOT EQUAL, compare operator, for example X != 5, Y <> 10
!== - similar to != or <>, but also checks the type of a value. For example 10 !== '10', and will return opposite result of the equality operator ===

Using in operator to compare string with range of strings

I am using in operator to check whether a value is in range. But I am not able to understand exactly how the comparison with range of strings is done. Below are the few arguments and their output which I have tried:
println("KOTLIN" in "J".."K")
false
println("KOTLIN" in "Java".."Scala")
true
println("KOTLIN" in "Java".."Bhuv")
false
in is compiled down to the following function (defined in kotlin.ranges.Range.kt):
public operator fun contains(value: T): Boolean = value >= start && value <= endInclusive
So "KOTLIN" in "J".."K" results in:
("J".."K").contains("KOTLIN")
The comparison in this case relies on normal String comparisons since >= and <= are compiled down to variations of compareTo. The implementation looks as follows:
public int compareTo(String anotherString) {
int len1 = value.length;
int len2 = anotherString.value.length;
int lim = Math.min(len1, len2);
char v1[] = value;
char v2[] = anotherString.value;
int k = 0;
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) {
return c1 - c2;
}
k++;
}
return len1 - len2;
}
So, "KOTLIN" in "Java".."Scala" is equal to the following:
"KOTLIN".compareTo("Java") >=0 && "KOTLIN".compareTo("Scala") <= 0
Based on your question, I think you are confused about this result:
println("KOTLIN" in "J".."K") is false
Basically, if you were to sort these using Java's String comparison implementation, you would see this:
Bhuv
J
Java
K
KOTLIN
KZ
Since K is lexicographically before KOTLIN, the result you are seeing makes total sense.
Lexicographic Order aka Dictionary Order, e.g.. when scrolling down the words in a dictionary, the order of the words will be
1.Java
2.Kotlin
3.Scala
Hence,
(Kotlin in Java..Scala) will return true.
In normal english, the code above is stating that by using the Dictionary Order, the word Kotlin is found in between the word Java and Scala.

Can an integer in Kotlin be equal to an math expression?

I am making a program that solves a math expression, for example, 2+2. Can I set an integer equal to something like this:
val input = "2+2"
input.toInt()
Kotlin doesn't have any built in ways for evaluating arbitrary expressions. The toInt function can only parse a String containing a single whole number (it's just a wrapper for Integer.parseInt).
If you need this functionality, you'll have to parse and evaluate the expression yourself. This problem is no different than having to do it in Java, for which you can find discussion and multiple solutions (including hacks, code samples, and libraries) here.
No you cannot convert directly a String Mathematical Expression to Integer.
But you can try following approach to convert String Mathematical Expression to Integer ->>
var exp: String = "2+3-1*6/4"
var num: String = ""
var symbol: Char = '+'
var result: Int = 0
for(i in exp)
{
if(i in '0'..'9')
num += i
else
{
if(symbol == '+')
result += Integer.parseInt(num)
else if(symbol == '-')
result -= Integer.parseInt(num)
else if(symbol == '*')
result *= Integer.parseInt(num)
else if(symbol == '/')
result /= Integer.parseInt(num)
num=""
symbol = i
}
}
//To calculate the divide by 4 ( result/4 ) in this case
if(symbol == '+')
result += Integer.parseInt(num)
else if(symbol == '-')
result -= Integer.parseInt(num)
else if(symbol == '*')
result *= Integer.parseInt(num)
else if(symbol == '/')
result /= Integer.parseInt(num)
println("result is $result") //Output=> result is 6
}
No you can't.
You can like this:
val a = "2"
val b = "2"
val c = a.toInt() + b.toInt()
Or
val input = "2+2"
val s = input.split("+")
val result = s[0].toInt() + s[1].toInt()
This can be done with the kotlin script engine. For details see Dynamically evaluating templated Strings in Kotlin
But in a nutshell it's like this:
val engine = ScriptEngineManager().getEngineByExtension("kts")!!
engine.eval("val x = 3")
val res = engine.eval("x + 2")
Assert.assertEquals(5, res)
No, Integer cannot be equal to math expression.
You may use String Templates
Strings may contain template expressions, i.e. pieces of code that are evaluated and whose results are concatenated into the
string.
A template expression starts with a dollar sign ($) and consists of either a simple name:
val i = 10
val s = "i = $i" // evaluates to "i = 10"

How to make a general logic comparison function in ObjC

Maybe my title is a little bit confusing so I'll illustrate with a scenario
Let say I want to compare between 2 int values and return me a boolean based on the logical comparison.
if (int1 > int2) return true;
if (int3 < int4) return true;
if (int5 == int6) return true;
if (int7 >= int8) return true;
if (int9 <= int10) return true;
But instead of writing this manually, I wish to do something like
- (bool)compareVal1: (int)val1 withVal2: (int)val2 usingLogical: (NSString*)logic
{
if (val1 "logic" val2) return true;
}
I want a general function which can be used to represent the 5 logical comparison that I want.
I'm not sure whether this is achievable but if you have any other solutions, please advise :)
Well first off, I would use an enum instead of an NSString to decide which logical operator to use. So try something like this:
typedef enum {
GREATER_THAN,
LESS_THAN,
LESS_THAN_OR_EQUAL,
GREATER_THAN_OR_EQUAL,
EQUALS
} logicalOperator;
And the actual function would look like this:
+ (bool)compareVal1: (int)val1 withVal2: (int)val2 usingLogical: (logicalOperator)op
{
switch(op) {
case GREATER_THAN:
return (val1 > val2);
case LESS_THAN:
return (val1 < val2);
case LESS_THAN_OR_EQUAL:
return (val1 <= val2);
case GREATER_THAN_OR_EQUAL:
return (val1 >= val2);
case EQUALS:
return (val1 == val2);
}
}
I would also make the function a static/class function because it does not truly affect a specific instance of a class, but rather it is a utility function that operates on the values passed in. An example of this functions usage would be this:
bool isGreater = [MyClass compareVal1: 4 withVal2: 3 usingLogical: GREATER_THAN];
Not sure why you can't just directly parse the string and return the result of the expression. For example (only illustrating two operators):
- (bool)compareVal1: (int)val1 withVal2: (int)val2 usingLogical: (NSString*)operator
{
if([operator isEqualTo:#">"])
{
return (val1 > val2);
}
else if ([operator isEqualTo:#"<"])
{
return (val1 < val2);
}
// similar logic statements for other operators
}
More pertinently, though, why do you need a method to do this when you can just write the evaluation itself instead?

Shorthand for all bools YES or all bools NO?

Often in my code I need to check whether the state of x amount of bools are all true OR all bools are false. So I do:
BOOL first, second, third;
if((first && second && third) || (!first && !second && !third))
//do something
Being a lazy programmer, I want to know if there is some mathematical shorthand for this kind of query, instead of having to type out this whole thing every time?
The shorthand for all bools the same is testing for (pairwise) equality:
(first==second && second==third)
Of course you can expand this to any number of booleans, having N-1 equality checks joined with the and operator.
If this is something you frequently require then you're better off using an integer and reading bits individually.
For instance, instead of:
BOOL x; // not this
BOOL y; // not this
BOOL z; // not this
...and instead of bit fields (because their layout is implementation-defined):
unsigned int x : 1; // not this
unsigned int y : 1; // not this
unsigned int z : 1; // not this
...use a single field such as:
unsigned int flags; // do this
...and assign every value to a bit; for example:
enum { // do this
FLAG_X = (1 << 0),
FLAG_Y = (1 << 1),
FLAG_Z = (1 << 2),
ALL_FLAGS = 0x07 // "all bits are on"
};
Then, to test "all false" you simply say "if (!flags)" and to test "all true" you simply say "if (flags == ALL_FLAGS)" where ALL_FLAGS is a number that sets all valid bits to 1. Other bitwise operators can be used to set or test individual bits as needed.
Note that this technique has an upper limit of 32 Boolean values before you have to do more (e.g. create an additional integer field to store more bits).
Check if the sum is 0 or equal to the number of bools:
((first + second + third) % 3 == 0)
This works for any number of arguments.
(But don't take this answer serious and do it for real.)
When speaking about predicates, you can usually simplify the logic by using two variables for the quantification operations - universal quantification (for all) and existential quantification (there exists).
BOOL allValues = (value1 && value2 && value3);
BOOL anyValue = (value1 || value2 || value3);
if (allValues || !anyValue) {
... do something
}
This would also work if you have a lot of boolean values in an array - you could create a for cycle evaluating the two variables.