Loop flow control - arrays

I have an array of objects, each object has a function that returns a Boolean value. What I need to do, is have a loop continuously running until each object returns a true value when the function is called on each object.
EDIT: Sorry I wasn't clear enough, I meant that I want the loop to break, when ALL of the objects functions return true.
Any ideas?

Java style syntax:
boolean good;
while (true) {
good = true;
foreach (MyObject o : myArray) {
if (!o.someFunction()) {
good = false;
break;
}
}
if (good) break;
}
I interpreted it as meaning that every object needed to have its function evaluated to true each time, and once they all evaluate to true break out of the loop.

If I got your question, you can do like this...
do
{
test = 0;
for(all functions)
{
char test_array[] = function_call();
}
int i = 0;
for(test_array.length)
{
if(test_array[i] == true)
{
count_no_true = i++;
}
}
if(count_no_true == no of function)
{test == 1;}
else
{test == 0;}
}while(test == 1)

Related

Bool function to check if a word is in an array C++

I'm working on some code check if word is in ignoreWords array. The function keeps returning true for the first value and then false for the rest of the elements even if some of the words are in the ignoreWords array. I'm not sure what I'm doing wrong, I'd appreciate any help or advice.
bool isIgnoreWord(string word, string ignoreWords[])
{
int length;
string copy[length];
for(int i=0; i < length; i++){
copy[length] = ignoreWords[i]; //to find out length of ignoreWords
//cout << copy[length] << endl;
if(copy[length] == word)
return true;
else
return false;
}
//function returns whether word is in the ignoreWords array
}
edit: fixed it. I made it so much more complicated than it really is. This is the code that works:
bool isIgnoreWord(string word, string ignoreWords[])
{
for(int i=0; i < 50; i++){
if(ignoreWords[i] == word){
return true;
}
}
return false;
//function returns whether word is in the ignoreWords array
}
That would be because your if-else statement in the for loop returns in both conditions.
Imagine you're the computer, and you start the for loop:
if (copy[length] == word) {
return true;
}
else {
return false;
}
So you get to the first element in the array, and let's say it doesn't match the word you're checking against. This if-else statement says to return false if it's not, and immediately stops the function because a return statement was found.
What you probably want is for your program to only return false if it exits the for-loop without finding any matches, e.g.
for (...) {
if (matches) return true;
}
return false;
Another thing to note is that you're not initializing length before using it in a statement, and initializing a variable-length array like that isn't supported on all compilers.

Will an If inside An If always be read? Not nested, but put right in front of the last one

The second if is always executing, no matter what the values from the first one was, I´m comparing char arrays from a struct.
Tried doing all of the comparisons in one If, like this:
if(strcmp(t[j].NomePeca, t[n].NomePeca) == 0 && strcmp(t[j].nroPoltrona, t[n].nroPoltrona) == 0 && strcmp(t[j].hora, t[n].hora) == 0 && strcmp(t[j].data,t[n].data) == 0) { ... }
Same thing.
struct TabelaIngresso {
char NomePeca[30];
char data[10];
char hora[5];
int aPagar;
char nroPoltrona[3];
};
// ............................
if (strcmp(t[j].NomePeca, t[n].NomePeca) == 0 && strcmp(t[j].nroPoltrona, t[n].nroPoltrona) == 0) {
if((strcmp(t[j].hora,t[n].hora) == 0) && (strcmp(t[j].data,t[n].data) == 0)) {
anulado = 1;
printf("\nCompra anulada pois a poltrona nao esta disponivel!\n");
strcpy (t[j].NomePeca, "Anulado");
strcpy (t[j].data, "Anulado");
strcpy (t[j].hora, "Anulado");
t[j].nroPoltrona[3] = '0';
t[j].aPagar = 0;
}
}
This If should only be executed if all of the strings are the same.
You might be asking about behavior called Short-circuit evaluation. It is the default behavior of the majority of the commonly used programming languages. The idea is that in a boolean expression the next argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression. Have a look at the example:
function foo() {
console.log('foo');
return false;
}
function bar() {
console.log('bar');
return true;
}
if (foo() && bar()) {
console.log('bar() will not ever be called');
} else {
console.log('calling foo() is enough');
}
The code above is equivalent to:
const bool = && bar();
if (foo()) {
if (bar()) {
console.log('bar() will not ever be called');
}
} else if (!bar()) {
console.log('calling foo() is enough');
}
But it's much easier to read the code from the first snippet.

checking an arrray and returning a bool

I'm in a CS class and I'm trying to create a tic tac toe program. This is my first time using functions and I need help checking a 2d array to see if it is full with 'x' or 'o' s. I initialized to start off with all the elements to '_' and I want a return value of true or false so I'm using #include <stdbool.h>. Here is the function:
bool check_table_full(char board[SIZE][SIZE]){
if(board[0][0] == '_'){
return false;
}else if(board[1][0] == '_'){
return false;
}else if(board[2][0] == '_'){
return false;
}else if(board[0][1] == '_'){
return false;
}else if(board[1][1] == '_'){
return false;
}else if(board[2][1] == '_'){
return false;
}else if(board[0][2] == '_'){
return false;
}else if(board[1][2] == '_'){
return false;
}else if(board[2][2] == '_'){
return false;
}else{
return true;
}
I know there is a better optimization then using if else statement but this is just is simple in my head. I use printf("%s", check_table_full?"true":"false"); to check if it returns false as it should since all elements in the array are '_'. No matter what I do it prints true, and if I change the "true" in the printf statement it prints whatever is inside the first quote.
Everything else works like SIZE is defined, the array is defined, I just can't get this function to return false.
Sorry if this is lengthy, this is my first time asking a question on here.
If you do printf("%s", check_table_full?"true":"false");, you are not calling the function.
check_table_full is the address of the function. You want check_table_full()
You may want to use nested for-loops. I have learned C++ syntax and not C syntax, so the syntax may be a little off.
Example Code...
#include <stdio.h>
int main() {
char board[2][2];
int outer_count, inner_count;
//It will use nested for loops
for (outer_count = 0; outer_count <= 2; count++) {
for (inner_count = 0; inner_count <= 2; count ++) {
if (board[outer_count][inner_count] == '_'){
return false;
}
}
}
return True
}
Your method of traversing the matrix is not scalable, you can easily introduce errors and is unnecessary complex. My 'check method' is 2 lines of code for any matrix size.
#include <stdio.h>
#include <stdbool.h>
#define MXSIZE 3
bool is_full(char *block) {
for (int l=0;l<MXSIZE*MXSIZE;l++)if(*(block+l)=='_')return false;
return true;
}
int main() {
char my2DArray[MXSIZE][MXSIZE]={{'O','O','O'},{'O','O','O'},{'O','O','_'}};
printf("%s",is_full(&my2DArray[0][0])?"The array is full\n":"The array is not full\n");
return 0;
}

getting out of a loop in C

I am trying to get out of a while loop using C, but using breaks, returns or changing the while condition are not working.
Basically, I want to know why in the last else if, when I state back = true my code keeps entering the for.
I would expect an output like: enter1, enter1, enter1, enter1, enter2.
Instead, the output is something like enter1, enter1, enter1, enter2, enter2, enter2, enter1, enter1, enter1....
This is my code work:
void SolveMap8(Core* core_building, Building* new, Stack* solve, bool goingBack){
Core* coreBuilding = core_building;
Building* first = new -> linked[0];
Building* next = NULL;
bool back = goingBack;
while (back == false) {
for (int i = 0; i < (first -> zone -> building_count); i++) {
if (first -> zone -> buildings[i] != NULL) {
if (first != first -> zone -> buildings[i]) {
next = first -> zone -> buildings[i];
if(next -> color == coreBuilding -> buildings[0] -> color && !city_client_is_taken(next)) {
puts("enter0");
Building_Pair* newPair = Building_Tuple_Create(first, next);
stack_push(solve, newPair);
city_client_link(first, next);
break;
}
else if(!city_client_is_taken(next)) {
if (city_client_is_blank(next)) {
if (!(next -> cored)) {
puts("enter1");
Building_Pair* newPair = Building_Tuple_Create(first, next);
stack_push(solve, newPair);
city_client_link(first, next);
SolveMap8(coreBuilding, next, solve, false);
}
}
}
else if (city_client_is_taken(next)) {
if (i == first -> zone -> building_count - 1) {
puts("enter2");
back = true;
}
}
}
}
}
}
}
Update Sorry, missed the recursion. In that case your problem has nothing to do with a missing break statement, but that you are trying to escape from a for loop at a different scope than you are currently in. You will need special logic to handle a global "done" condition. Perhaps something like this:
void process(Core* core, bool& done) {
for (int i = 0; i < core->size() && !done; ++i) {
if (!core[i]->is_taken()) {
process(core[i], done);
} else if (core[i]->is_taken() {
// done procesing
done = true;
}
}
}
// use via
bool done = false;
process(myCore, done);
In the version you have, the goingBack flag is passed by value, so every function gets its own copy and there is no way to pass the value of back to the parent in the recursive call chain. In my code above, done is passed as a reference, so changing the value at some point in the recursion chain will make it visible at parent scope (because the scope of the variable is outside the function itself). Hope this is more helpful.

How can we ensure that a while loop would not be an infinite loop?

This is a method where I am using the while loop. I strongly suspect that an infinite loop is possible. How to check and eliminate that?
I am using two while loops here. Sould I totally dismantle the while loop?
public class ReferenceListSaveHandler
{
public PublishReferenceListUpdates populateResponse(SearchQueryResponse pSearchQueryResponse,SearchQueryResponse pListResponse, ObjectFactory objFactory) throws IOException, ParserConfigurationException, SAXException,SipException, Exception
{
ReferenceDataProcessor lRefPro = new ReferenceDataProcessor();
PublishReferenceListUpdates lResponse = null;
Record listRecord = null;
ReferenceDataListItemListType lReferenceDataListItemListType = objFactory
.createReferenceDataListItemListType();
ReferenceDataListType lReferenceDataListType = null;
ReferenceDataListItemType lReferenceDataListItemType = null;
boolean ifSynonym = false;
String lRowIdObject = null;
final int lRowIdLength = 14;
if (refListItemItr.hasNext())
{
Record record = (Record)refListItemItr.next();
boolean continueProcessing = true;
boolean lastRecord = false;
while (continueProcessing)
{ // first use of while loop
if (refListItemItr.hasNext() || lastRecord)
{
continueProcessing = true;
lastRecord = false;
}
else
{
continueProcessing = false;
}
if (continueProcessing)
{
lSynonymListType = objFactory
.createSynonymListType();
Field itemLSIDField = record
.getField(ReferenceDataConstants.FIELD_COMPOUND_ASSET_ID);
if (itemLSIDField == null)
{
continue;
}
else
{
currentItemLSID = itemLSIDField
.getStringValue().trim();
}
lReferenceDataListItemType = objFactory
.createReferenceDataListItemType();
lReferenceDataListItemType = setListDetails(record,
lReferenceDataListItemType,
lId, lName, objFactory);
while (refListItemItr.hasNext()
&& continueProcessing)
{ // second use of while loop
SynonymType lSynonymType = null;
if (continueProcessing)
{
if (lSynonymType != null)
lSynonymListType.getSynonym().add(lSynonymType);
}
}
continueProcessing = true;
}
}//while loop
}
}
}
Please help.
Problem number one: refListItemItr, whatever that is (its definition is not shown), has a .next() method but it's never called inside the loop.
Problem number two: The second while loop is always infinite if you enter it:
while (refListItemItr.hasNext()
&& continueProcessing)
{
SynonymType lSynonymType = null;
if (continueProcessing)
{
if (lSynonymType != null)
lSynonymListType.getSynonym().add(lSynonymType);
}
}
Neither refListItemItr.hasNext(), nor continueProcessing can change inside this loop. That's why it's an infinite loop.
EDIT:
I can't tell you how to change the code because there are many possible ways to change it, depending on what's supposed to happen. You can try this but it may or may not work:
Remove the second loop entirely (it does nothing right now).
Add this line just before the end of the first loop:
record = (Record)refListItemItr.next(); // ADD THIS LINE
} //while loop BEFORE THIS LINE
This is an infinit loop , the outer loop depends on lastrecord which is not beeing set to true anywhere in the program
I throw in a loop counter whenever I write the word while, like this:
int loopCounter = 0, maxLoops = 1000; //just an example
while((loopCounter++) < maxLoops && (myConditions))
{
// loop away, this can't ever be infinite
}
or this
int loopCounter = 0, maxLoops = 1000; //just an example
do
{
// loop away, this can't ever be infinite
}
while((loopCounter++) < maxLoops && (myConditions))
Of course, maxLoops is always sized to be orders of magnitude greater than any reasonable number of iterations... Then I add a check:
if (loopCounter == maxLoops) { throw new InvalidOperationException("Infinite loop detected!"); }

Resources