Best way to test if all elements of an array/list satisfy a condition - for-loop

I would like to test if all elements in an array (or list) satisfy a condition. But I would like to do it in the cleanest and most optimized way I can.
I used to do something like this (exemple in c++) :
vector<unsigned> vct; // put anything in it
bool verified = true;
for (unsigned elmt: vct) {
if (!mycondition) {
verified = false;
break;
}
} // then use verified to check if condition is satisfied for each element
But then someone told me that you usally want to initialize verified to false and then turn it to true. This made me do :
vector<unsigned> vct; // put anything in it
bool verified = false;
unsigned count = 0;
for (unsigned elmt: vct) {
if (mycondition) {
++count;
}
}
if(count == vct.size())
verified = true; // then use verified to check if condition is satisfied for each element
But this solution does not seem optimized at all because we use a counter and we have to loop through all the elements while the first solution stopped as soon as it finds a "bad" element.
So here is my question.
What is the cleaner and most optimized way to test if all elements in array satisfy a condition ?

Related

Sudoku solver with backtracking can't always detect multiple solutions

This is the code I wrote to check if there are multiple solutions to a KenKen puzzle (Similar to Sudoku). Technically it should return true if there are 2 solutions, but it doesn't appear to work because of a logic error in the algorithm.
I can't seem to find the error and after spending a whole day debugging the whole thing step by step I feel like I'll never find out what's wrong.
The code can solve the puzzle without any problems but it doesn't always seem to detect when there are multiple solutions, which is just weird.
boolean solutionFlag = false;
static boolean backtrackingUniqueSolution(int startIndex) {
for (int i=1; i<=sudokuGridElements.length; i++){
sudokuGridCells[startIndex] = i;
if(checkConditons()){
if(endOfBounds || backtrackingUniqueSolution(startIndex + 1))){
if(!solutionFlag){ //Used to "count to 1"
solutionFlag = true;
} else {
return true; //Should return true only after it finds the second solution
}
}
}
sudokuGridCells[startIndex] = null;
}
return false;
}
When you find the first solution, you set the flag, but return false, so that you don't know whether a solution was found further up the recursion stack. The flag tells you that, but you must still look for a second solution to get your answer.
You should distinguish between actually finding a solution when the last cell is reached and cutting recursion short when you already have found a second solution. In the first case, do the delayed counting via the flag. In the second case, just return true if a second solution was found, that is when the recursive function has returned true.
boolean solutionFlag = false;
static boolean multiSolution(int startIndex) {
for (int i = 1; i <= sudokuGridElements.length; i++) {
sudokuGridCells[startIndex] = i;
if(checkConditons()) {
if (endOfBounds) {
if (solutionFlag) return true;
solutionFlag = true;
} else {
if (multiSolution(startIndex + 1)) return true;
}
}
sudokuGridCells[startIndex] = null;
}
return false;
}
(You could get rid of the non-local state flag, if you made the function return an integer or enumerated value which tells you whether no, a single or many solutions were found.)

std::vector erase issue with MSVC 2010

ALL,
I have a class defined that just holds the data (different types of data). I also have std::vector that holds a pointers to objects of this class.
Something like this:
class Foo
{
};
class Bar
{
private:
std::vector<Foo *> m_fooVector;
};
At one point of time in my program I want to remove an element from this vector. And so I write following:
for (std::vector<Foo *>::iterator it = m_fooVector.begin(); it <= m_fooVector.end(); )
{
if( checking it condition is true )
{
delete (*it);
(*it) = NULL;
m_fooVector.erase( it );
}
}
The problem is that the erase operation fails. When I open the debugger I still see this element inside the vector and when the program finishes it crashes because the element is half way here.
In another function I am trying to remove the simple std::wstring from the vector and everything works fine - string is removed and the size of the vector decreased.
What could be the problem for such behavior? I could of course try to check the erase function in MSVC standard library, but I don't even know where to start.
TIA!!!
Your loop is incorrect:
for (std::vector<Foo *>::iterator it = m_fooVector.begin(); it != m_fooVector.end(); )
{
if (/*checking it condition is true*/)
{
delete *it;
// *it = NULL; // Not needed
it = m_fooVector.erase(it);
} else {
++it;
}
}
Traditional way is erase-remove idiom, but as you have to call delete first (smart pointer would avoid this issue), you might use std::partition instead of std::remove:
auto it = std::partition(m_fooVector.begin(), m_fooVector.end(), ShouldBeKeptFunc);
for (std::vector<Foo *>::iterator it = m_fooVector.begin(); it != m_fooVector.end(); ++it) {
delete *it;
}
m_fooVector.erase(it, m_fooVector.end());

Methods, more than one return?

I have the following method:
From what I learned methods which are not voids need a return. For the following examples I can see two returns, once after if(), and one at the end.
For this example if String s is not a digit it will return the boolean as false. Which makes sense. If it is a digit then it will check whether it is in the interval. I guess I am confused regarding whether we can have multiple returns in such cases and what the limitations are, if there are any. thank you.
private boolean ElementBienFormat(String s) {
for (int i = 0; i < s.length(); i++) {
if (!Character.isDigit(s.charAt(i))) {
return false;
}
}
int n = Integer.valueOf(s);
return (n>=0 && n <=255);
A method will "quit" (return) when control reaches a return. So in this case as soon as a character is not a digit in the input String control will go back to the caller (with the appropriate value).
boolean success = ElementBienFormat( "a" ); // <-- control would go back here with the value of false.
Another quick note is that a void method can have multiple return statements as well
private void Method( int n )
{
if( n < 0 )
return;
//...
//implicit
//return;
}

What is the accepted practise for returning from boolean methods

Okay, this is a simple question, but I'd like some oppinions on the correct practice here. I am not looking at this for performance concerns, because CPU's are so powerful that this wouldn't make any perceivable difference unless called without a looping contruct with thousands of iterations. I just want views on what is the accepted standard.
I have a method that bascially just does a check returns a boolean. However, there are numerous ways to implement this.
Here is how I would normally implement this.
public bool CanUndo()
{
if (_nCurrentUndoIndex > 0)
return true;
else
return false;
}
However, it is often frowned upon to return from the middle of a method. The only time I normally do this is when performing a check on a form submission like this.
if (String.IsNullOrEmpty(firstName.Text))
{
MessageBox.Show("Please enter a first name", "Incomplete");
return;
}
I consider that acceptable.
Back to the undo question, an alternative way to code it would be this.
public bool CanUndo()
{
bool returnVal;
if (_nCurrentUndoIndex > 0)
returnVal = true;
else
returnVal = false;
return returnVal;
}
This however unncessarily allocates a variable and is more verbose code. Another option would be.
public bool CanUndo()
{
bool returnVal = false;
if (_nCurrentUndoIndex > 0)
returnVal = true;
return returnVal;
}
This is more streamlined as it gets rid of the else. However, if the value is true is makes an unneccesary assignment by initializing it to false.
public bool CanUndo () {
return _nCurrentUndoIndex > 0;
}
Personally I don't have a problem with returning from the middle of a method. It complicates cleanup code for C functions but with RAII that argument disappears.
I prefer to exit as soon as is suitable otherwise you get
if (x) {
if (y) {
if (z) {
complete
}
}
}
rather than
if (!x)
return
if (!y)
return
if (!z)
return
complete
This way you avoid nesting, wide lines (horizontal screen space is expensive, vertical space is cheap) and you always know that if you're still in a function then you're not in an error path. Code which works well with this design also works well with exceptions, which is very important.
you should always contract boolean returns to their logical aquivalent, because this is much easier to read for developers, it is faster to write for you and it get contracted by the compiler anyways.
consider an expanded or:
if (a == 1)
return true;
else if (a == 2)
return true;
else if (a == 3)
return true;
else
return false;
and the reason should become obvious when you compare it to the contracted version
return (a == 1) || (a == 2) || (a == 3)
public bool CanUndo()
{
return (_nCurrentUndoIndex > 0);
}

Is my programming logic correct here?

const char IsPressed = 1; // 1
const char WasHeldDown = 2; // 10
const char IsFirstPress = 4; // 100
char* keystates[256];
Class::CalculateKeyStates()
{
for(int i = 0; i < 256; ++i)
{
if(this->IsDown(i))
{
keystates[i] |= IsPressed; // turn on
if(keystates[i] & WasHeldDown)
{
//keystates[i] |= IsFirstPress;
keystates[i] &= ~IsFirstPress; // turn off
}
else
{
keystates[i] |= WasHeldDown + IsFirstPress; // Turn on
}
}
else
{
keystates[i] = 0; // Turn ALL off
}
}
}
This function would be a member function of a class, Class. The other member function, IsDown, will return a true if the key in question is down and false if not.
Can you see any way of further improving this function?
Thanks
EDIT:
I will expand a bit as to what is done why. This is a modification of an bit of code that works through an array keyStates (which was a struct of three bools) setting IsPressed to false for all of the keys. then again setting Ispressed to the value of this->IsDown and then a third time looping through checking if the key had been held, if it has then its no longer the first press so set that to false. if it was not held down, then set first press to true and was held to true as well, so next time it is flagged as having been held.
EDIT2:
Added some comments to code and corrected one line
Personally, I would define the key-states as disjoint states and write a simple state-machine, thus:
enum keystate
{
inactive,
firstPress,
active
};
keystate keystates[256];
Class::CalculateKeyStates()
{
for (int i = 0; i < 256; ++i)
{
keystate &k = keystates[i];
switch (k)
{
inactive:
k = (isDown(i)) ? firstPress : inactive;
break;
firstPress:
k = (isDown(i)) ? active : inactive;
break;
active:
k = (isDown(i)) ? active : inactive;
break;
}
}
}
This is easier to extend, and easier to read if it gets any more complex.
You are always setting IsFirstPress if the key is down, which might not be what you want.
I'm not sure what you want to achieve with IsFirstPress, as the keystate cannot remember any previous presses anyways. If you want to mark with this bit, that it's the first time you recognized the key being down, then your logic is wrong in the corresponding if statement.
keystates[i] & WasHeldDown evaluates to true if you already set the bit WasHeldDown earlier for this keystate.
In that case, what you may want to do is actually remove the IsFirstPress bit by xor-ing it: keystates[i] ^= IsFirstPress

Resources