Check if same list element contains true or false - c++

Let's say that I have a list std::list<MyClass> myList like this:
ID Valid
--------------
1000 true
1000 false
1000 true
2000 false
2000 false
3000 true
3000 true
And this boolean value comes from a function bool isExpired(MyClass &a).
How can I check if one group of elements have equal or different boolean values?
For example in this case 1000 should be false because second 1000 in list has false value.
This is false
1000 true
1000 false //because of this
1000 true
This is false
2000 false
2000 false
This is true
3000 true
3000 true
I tried to create a new map which will override the key and value.
std::map<long, bool> status;
for(const auto &it : myList)
{
status[it.ID] = status[it.ID] || isExpired(it);
}
But it does not work as expected. It returns true for the element with an ID 1000.

You don't want to use ||, you want to use &&, which means that you have to default to true:
std::map<long, bool> status;
for(const auto &it : myList)
{
auto entry = status.find(it.ID);
if (entry != status.end()) {
entry->second = entry->second && isExpired(it);
} else {
status[it.ID] = true;
}
}

Related

Very simple if/else statements seem to be working backwards

I have been looking at this simple if/else statement in another larger project and I can't seem to find what I am doing wrong.
I have inserted Logger.log() in both if statements to try to root out the problem.
When I run the code, I get the following Log:
[19-02-24 08:50:05:427 PST] var Campus = Baylor
[19-02-24 08:50:05:428 PST] var TSTCCampus = TSTC
[19-02-24 08:50:05:428 PST] if IS= statement executed
[19-02-24 08:50:05:428 PST] else NOT= executed
The two variables are clearly NOT equal but the if = executes and the else != executes.
What am I doing wrong?
function myFunction() {
// call the Current Reults sheet and identify the Last Row of Responses
var RawFormResponsesSheet = SpreadsheetApp.getActive().getSheetByName("Current Results");
var CurrentSubmission = RawFormResponsesSheet.getLastRow(); // Retruns the Value of the Last Submission Row Number
var Campus = RawFormResponsesSheet.getRange(CurrentSubmission,3).getValue();
// call the Email Data sheet and identify certain cell values
var EmailDataSheet = SpreadsheetApp.getActive().getSheetByName("Email Data")
var TSTCCampus = EmailDataSheet.getRange(3, 4).getValue();
var BaylorCampus = EmailDataSheet.getRange(4, 4).getValue();
Logger.log("var Campus = " + Campus)
Logger.log("var TSTCCampus = " + TSTCCampus)
if (Campus = TSTCCampus){Logger.log ("if IS= statement executed")}
else {Logger.log ("else IS= executed")}
if (Campus != TSTCCampus){Logger.log ("if NOT= statement executed")}
else {Logger.log ("else NOT= executed")}
}
You need to use == as comparison operator.
There are 3 = operators/commands:
= is used to set the value of a variable
== equality operator, returns true if the elements have same value, performs type conversion
=== identity operator, similar to ==, but no type conversion
The following explains what type conversion is.
"5" == "5" returns true
"5" == 5 returns true
"5" === "5" returns true
"5" === 5 returns false
somevar = 5 assigns and returns 5, which is a truthy value, and thus if (x = 5) { will always execute the conditional body. Similarly if (x = 0) { will never execute the conditional body, because it assigns and returns 0, which is falsy.

What is the difference between this two condition?

What is the difference between this two conditions?. I tried to use both conditions but different output.
if(!(data1 == true || data2 == true))
{
// do something
}
And
if(data1 != true || data2 != true)
{
// do something
}
!(data1 == true || data2 == true) this condition is same as data1 != true && data2 != true
Using ! operator with == gives != and using ! operator with || will give &&.
Your 2nd condition data1 != true || data2 != true will be same as your 1 st condition If you replace || with && in 2nd condition
!(data1 == true || data2 == true)
This is equivalent of (see also De Morgan's laws):
(data1 != true && data2 != true)
Which is obviously different from
(data1 != true || data2 != true)
fist condition :
if(!(data1 == true || data2 == true))
{
// do something
}
It will false the evaluated result if the result is true and if the result is false then the result will be true.
If data1 == true is true it will not check data2 condition and make all condition false. so if data1 == true then whole condition is false. Same as data1. And if data1 or data2 is false (one is false) then the code will be executed.
Second Condition
if(data1 != true || data2 != true)
{
// do something
}
It will do the reverse of the first condition. First it will check that if data1 is not equal to true, so if data1 is false then the code will be executed.

Why i cant check if a variable have a value using == true?

if(10) it is true, but if(10 == true) is false. Can someone tell me why the first case convert the number to bool but the second case didnt?
if (10) is equivalent to if (10 != 0), whereas if (10 == true) is if (10 == 1) (since true is promoted to the value 1 of type int).
In layman's terms: Two things that both happen to satisfy some property aren't automatically the same thing.
(E.g. doughnuts and frisbees are both round, but that doesn't mean a doughnut is equal to a frisbee. Integers and booleans can both be evaluated in a boolean context, but that doesn't mean that every integer that evaluates as true is equal to every true boolean.)
if( ... )
{
// if statement
}
To execute if statement in C++, ... should have a true value.
When you wrote if( 10 ){//something useful}
I think 10 treats as int but not bool variable. The following logic should be applied then
if( 10 ) -> if( bool( 10 ) ) -> if( true )
When you write if( 10 == true ){//something useful}, according to C++ standard, there should be the following logic behind the scene
if( 10 == true ) -> if( 10 == int( true ) ) -> if( 10 == 1 ) -> if( false )
You may write something like
if( 10 != false )
or
if( !!10 == true )
also
if( ( bool ) 10 == true ) // alternatively, if( bool ( 10 ) == true )
In old C (before C99), there is no false or true, but there are 0 or non-0 values.
In modern C (from C99), there is false or true (<stdbool.h>), but they are syntactic sugar for 0 and 1, respectively.
if( 10 ) // evaluates directly since 10 is non-zero value
if( 10 == true ) -> if( 10 == 1 ) -> if( 0 )
Because they are entirely different things.
In C, anything that is NOT false is automatically true, and C has a very strict definition of false.
You can think of if(10) as if(10 != false)
and likewise if (10 == true) as if((10 == true) != false)
10 is clearly not true, in the sense that 10 is a number and true is a boolean.
When you're in an if statement, the compiler has to evaluate the condition until it reaches either a true or a false. If it does not reach a true or a false, it has to convert it to a true or a false. As a general rule, 0 evaluates to false, and everything else evaluates to true.
So if(-1) is true, as is if(234) and so on.
The expression 10 == true already evaluates to false, so no further conversion is needed. if(10) is neither true or false, so the compiler has to convert it, using our rule above, and it becomes true.

java.util.NoSuchElementException when using inject method of groovy List

i try to get the AND logic among boolean elments from groovy list .
def list=[true,false,true];
For example , when i apply inject as following :
list.inject{a,b->a && b};
i get
true && false && true=false
However , when i apply this closure to an empty list i get this error message
Cannot call inject() on an empty collection without passing an initial value.
How can passing initial value to avoid this exception ?
thanks
Inject with no initial parameter uses the first element in the list as the initial value, and then runs the closure over all further elements in the list.
If the list is empty, it cannot get the initial value, so you need to specify an initial parameter to inject:
ie:
list.inject( true ) { a, b -> a && b }
This will return true for empty lists, but in your original example will return false, as it will evaluate:
true && true && false && true
Obviously, if you're doing or instead of and, you should pass false as the inital parameter:
list.inject( false ) { a, b -> a || b }

Search for an item in a Lua list

If I have a list of items like this:
local items = { "apple", "orange", "pear", "banana" }
how do I check if "orange" is in this list?
In Python I could do:
if "orange" in items:
# do something
Is there an equivalent in Lua?
You could use something like a set from Programming in Lua:
function Set (list)
local set = {}
for _, l in ipairs(list) do set[l] = true end
return set
end
Then you could put your list in the Set and test for membership:
local items = Set { "apple", "orange", "pear", "banana" }
if items["orange"] then
-- do something
end
Or you could iterate over the list directly:
local items = { "apple", "orange", "pear", "banana" }
for _,v in pairs(items) do
if v == "orange" then
-- do something
break
end
end
Use the following representation instead:
local items = { apple=true, orange=true, pear=true, banana=true }
if items.apple then
...
end
You're seeing firsthand one of the cons of Lua having only one data structure---you have to roll your own. If you stick with Lua you will gradually accumulate a library of functions that manipulate tables in the way you like to do things. My library includes a list-to-set conversion and a higher-order list-searching function:
function table.set(t) -- set of list
local u = { }
for _, v in ipairs(t) do u[v] = true end
return u
end
function table.find(f, l) -- find element v of l satisfying f(v)
for _, v in ipairs(l) do
if f(v) then
return v
end
end
return nil
end
Write it however you want, but it's faster to iterate directly over the list, than to generate pairs() or ipairs()
#! /usr/bin/env lua
local items = { 'apple', 'orange', 'pear', 'banana' }
local function locate( table, value )
for i = 1, #table do
if table[i] == value then print( value ..' found' ) return true end
end
print( value ..' not found' ) return false
end
locate( items, 'orange' )
locate( items, 'car' )
orange found
car not found
Lua tables are more closely analogs of Python dictionaries rather than lists. The table you have create is essentially a 1-based indexed array of strings. Use any standard search algorithm to find out if a value is in the array. Another approach would be to store the values as table keys instead as shown in the set implementation of Jon Ericson's post.
This is a swiss-armyknife function you can use:
function table.find(t, val, recursive, metatables, keys, returnBool)
if (type(t) ~= "table") then
return nil
end
local checked = {}
local _findInTable
local _checkValue
_checkValue = function(v)
if (not checked[v]) then
if (v == val) then
return v
end
if (recursive and type(v) == "table") then
local r = _findInTable(v)
if (r ~= nil) then
return r
end
end
if (metatables) then
local r = _checkValue(getmetatable(v))
if (r ~= nil) then
return r
end
end
checked[v] = true
end
return nil
end
_findInTable = function(t)
for k,v in pairs(t) do
local r = _checkValue(t, v)
if (r ~= nil) then
return r
end
if (keys) then
r = _checkValue(t, k)
if (r ~= nil) then
return r
end
end
end
return nil
end
local r = _findInTable(t)
if (returnBool) then
return r ~= nil
end
return r
end
You can use it to check if a value exists:
local myFruit = "apple"
if (table.find({"apple", "pear", "berry"}, myFruit)) then
print(table.find({"apple", "pear", "berry"}, myFruit)) -- 1
You can use it to find the key:
local fruits = {
apple = {color="red"},
pear = {color="green"},
}
local myFruit = fruits.apple
local fruitName = table.find(fruits, myFruit)
print(fruitName) -- "apple"
I hope the recursive parameter speaks for itself.
The metatables parameter allows you to search metatables as well.
The keys parameter makes the function look for keys in the list. Of course that would be useless in Lua (you can just do fruits[key]) but together with recursive and metatables, it becomes handy.
The returnBool parameter is a safe-guard for when you have tables that have false as a key in a table (Yes that's possible: fruits = {false="apple"})
function valid(data, array)
local valid = {}
for i = 1, #array do
valid[array[i]] = true
end
if valid[data] then
return false
else
return true
end
end
Here's the function I use for checking if data is in an array.
Sort of solution using metatable...
local function preparetable(t)
setmetatable(t,{__newindex=function(self,k,v) rawset(self,v,true) end})
end
local workingtable={}
preparetable(workingtable)
table.insert(workingtable,123)
table.insert(workingtable,456)
if workingtable[456] then
...
end
The following representation can be used:
local items = {
["apple"]=true, ["orange"]=true, ["pear"]=true, ["banana"]=true
}
if items["apple"] then print("apple is a true value.") end
if not items["red"] then print("red is a false value.") end
Related output:
apple is a true value.
red is a false value.
You can also use the following code to check boolean validity:
local items = {
["apple"]=true, ["orange"]=true, ["pear"]=true, ["banana"]=true,
["red"]=false, ["blue"]=false, ["green"]=false
}
if items["yellow"] == nil then print("yellow is an inappropriate value.") end
if items["apple"] then print("apple is a true value.") end
if not items["red"] then print("red is a false value.") end
The output is:
yellow is an inappropriate value.
apple is a true value.
red is a false value.
Check Tables Tutorial for additional information.
function table.find(t,value)
if t and type(t)=="table" and value then
for _, v in ipairs (t) do
if v == value then
return true;
end
end
return false;
end
return false;
end
you can use this solution:
items = { 'a', 'b' }
for k,v in pairs(items) do
if v == 'a' then
--do something
else
--do something
end
end
or
items = {'a', 'b'}
for k,v in pairs(items) do
while v do
if v == 'a' then
return found
else
break
end
end
end
return nothing
A simple function can be used that :
returns nil, if the item is not found in table
returns index of item, if item is found in table
local items = { "apple", "orange", "pear", "banana" }
local function search_value (tbl, val)
for i = 1, #tbl do
if tbl[i] == val then
return i
end
end
return nil
end
print(search_value(items, "pear"))
print(search_value(items, "cherry"))
output of above code would be
3
nil