For loop isn't running C++ - c++

I am writing a piece of code to make two LED lights blink in a specific sequential order.
my code
int main()
{
int blue = 3;
int green = 4;
int time = 1;
int i = 1;
int j = 1;
greenLED = 1;
blueLED = 1;
wait(1);
for(time; time<green*blue; time++)
{
if (time == green*i)
{
blueLED = 1;
i=i+1;
}
if(time == blue*j)
{
greenLED = 1;
j=j+1;
}
wait(1);
}
}
My problem is that it says my for loop has no effect. I am assuming that it means my for loop is not running because the expression for my for loop doesn't make sense or isn't picking up any of the variables I have? Can someone please help me out and tell me why?
cheers

i think this is what you wanted
int main()
{
int blue = 3;
int green = 4;
int time = 1;
int i = 1;
int j = 1;
int greenLED = 1;
int blueLED = 1;
for(time; time<green*blue; time++)
{
blueLED=0;
greenLED=0;
printf("for loop start\n");
if (time == green*i)
{
printf("if1\n");
blueLED = 1;
i=i+1;
}
if(time == blue*j)
{
printf("if2\n");
greenLED = 1;
j=j+1;
}
printf("endforloop\n");
printf("%d\n",greenLED);
printf("%d\n",blueLED);
}
}
as you see the for loop is running

Related

equal jump between numbers in two arrays

I want to compare two arrays. One of them is a subset of the other one. I want my function to return the minimum and equal gap between the numbers of the first subset array in the other array.
For example if I have
arr1 = 2,1,4,2,8,3
sub= 1,2,3
I want my function to return 1 because the mimimum gap between all this numbers are 1.
arr1 = 2,1,5,2,1,2,3
sub= 1,2,3
I want my function to return 0 because the mimimum gap between 1,2,3 in arr1 is 0
Here is the code I am trying to do: My code always return 0 can you help me understand why, and how can I solve this.
int gap(int* arr, int* sub, int sizeArr, int sizeSub)
{
int index = 0; int gap = 0; bool flag = true;
int i = -1;
for (int jump = 1; jump < sizeArr / sizeSub; jump++)
{
index = 0;
for (i = i +1; i < sizeArr; i++)
{
if (sub[index] == arr[i])
{
for (int j = i + jump, index = 1; j < sizeArr; j = j + jump, index++)
{
if (arr[j] != sub[index]) { flag = false; break; }
else if (arr[j] == sub[index] && index == sizeSub) { flag = true; break; }
}
}
if (!flag) { break; }
else { gap = jump; break; }
}
}
return gap;
}
You initially took gap equally 0 but i think more suit to not store gap
and start iterate jump from 0. And return jump immediately after you found that it is suit.
Also i think that store index in such manner as you it is bad idea, because you code return wrong answer on
int a[] = { 2,1,4,4,2,8,5,3 };
int s[] = { 1,2,3 };
I think you should declare variable as soon as possible, otherwise there will be undesirable side effects.
So you code can be rewritten as
int gap(int *arr, int *sub, int sizeArr, int sizeSub)
{
for (int jump = 0; 1 + (jump + 1) * (sizeSub - 1) <= sizeArr; jump++) {
for (int start_index = 0; start_index + (jump + 1) * (sizeSub - 1) < sizeArr; start_index++) {
bool flag = true;
for (int index = 0; index < sizeSub; ++index) {
if (arr[start_index + index * (jump + 1)] != sub[index]) {
flag = false;
break;
}
}
if (flag) {
return jump;
}
}
}
return -1; //or some value that indicate that there is no answer
}

Ending OpenMP for prematurely

I have a problem with writing a routine in C++ using OpenMP for. The code of the routine is as follows:
int sudokuSolution [9][9];
bool solvep(int s[9][9], int row, int col) {
bool solution = false;
#pragma omp parallel for
for (int val = 1; val < 10; val++) {
if (isPossible(s,row,col,val)) {
s[row][col] = val;
if (solve(s, row + col / 9, (col + 1) % 9)) {
sudokuSolution[row][col] = val;
solution = true;
}
}
}
return solution;
}
when running this routine without the parallel clause, everything works fine (i.e. routine returns true every time it's called). However, when I use the parallel for, it sometimes returns false. I wasn't able to figure out, why is this happening and the only way of removing this bug is from my perspective ending the whole parallel block prematurely after solution is set to true. However, if I did my research properly, there is no way to prematurely end a parallel block. Could you please suggest me an alternative?
EDIT: Adding minimal functioning example as requested:
#include <omp.h>
#include <iostream>
#include <list>
#include <chrono>
using namespace std;
bool solutionFound = false;
int sudoku [9][9] = { 5,7,0,9,0,0,0,0,8,
0,0,0,0,0,5,0,3,9,
0,0,0,0,0,0,2,0,4,
0,0,0,0,9,0,6,8,0,
0,0,0,8,0,2,0,0,0,
0,5,2,0,7,0,0,0,0,
6,0,5,0,0,0,0,0,0,
7,9,0,4,0,0,0,0,0,
2,0,0,0,0,9,0,7,6};
int sudokuSolution [9][9];
bool isPossible(int s[9][9], int row, int col, int val) {
for(int i = 0; i < 9; i++) {
if (s[row][i] == val)
return false;
if (s[i][col] == val)
return false;
if (s[row / 3 * 3 + i / 3][col / 3 * 3 + i % 3] == val)
return false;
}
return true;
}
bool solve(int s[9][9], int row, int col) {
while(s[row][col] != 0) {
col = (col + 1) % 9;
row = row + col / 8;
if(row == 9)
return true;
}
for (int val = 1; val < 10; val++) {
if (isPossible(s,row,col,val)){
sudokuSolution[row][col] = val;
s[row][col] = val;
if (solve(s, row + col / 9, (col + 1) % 9))
return true;
sudokuSolution[row][col] = 0;
s[row][col] = 0;
}
}
return false;
}
bool solvep(int sa[9][9], int row, int col) {
int s [9][9];
for(int i = 0; i < 9; i++)
for(int j = 0; j < 9; j++)
s[i][j] = sa[i][j];
while(s[row][col] != 0) {
col = (col + 1) % 9;
row = row + col / 8;
if(row == 9)
return true;
}
bool solution = false;
#pragma omp parallel for
for (int val = 1; val < 10; val++) {
if(!solutionFound) {
if (isPossible(s,row,col,val)){
s[row][col] = val;
if (solve(s, row + col / 9, (col + 1) % 9)) {
sudokuSolution[row][col] = val;
solutionFound = true;
solution = true;
}
}
}
}
return solution;
}
int main() {
for (int k = 0; k < 100; k++) {
for(int i = 0; i < 9; i++)
for(int j = 0; j < 9; j++)
sudokuSolution[i][j] = sudoku[i][j];
solutionFound = false;
solvep(sudokuSolution,0,0);
bool calcResult = solvep(sudoku,0,0);
cout << calcResult;
}
return 0;
}
You have many race conditions in your code, both in the loop itself and the solve function. In code that is executed in parallel you must not write to to shared data (s, solution, sudokuSolution) and especially global variables (solutionFound). You will have to go back to your learning material and catch up with data races and the methods to protect against them.
With some experience it is easy to spot the issues in the loop itself. It's much harder to spot in called functions - which is why its so important to give a complete example in your question. Try to define your interfaces such that mutable no shared data is passed to functions. Conceptually you will have to have a copy of the board for each thread to perform backtracking in parallel.
Once you fix the issues with writing to the board, you can use atomic writes, a critical region or a reduction to "share" the solution. But you have to consider both sudokuSolution[row][col] and solution. Logically I suppose sudokuSolution[row][col] != 0 == solution.
You could reduce the solution values on all threads using the || operator:
int sudokuSolution [9][9];
bool solvep(int s[9][9], int row, int col) {
bool solution = false;
#pragma omp parallel for reduction(||:solution)
for (int val = 1; val < 10; val++) {
if (isPossible(s,row,col,val)) {
s[row][col] = val;
if (solve(s, row + col / 9, (col + 1) % 9)) {
sudokuSolution[row][col] = val;
solution = true;
} else {
solution = false;
}
} else {
solution = false;
}
}
return solution;
}

Infinite while loop with a random number

I have this code:
void generar() {
while (true) {
if (yPos == topOfTheWorld) {
scene[xPos][yPos] = 2;
} else if (yPos >= topOfTheWorld) {
scene[xPos][yPos] = 1;
} else if(yPos < topOfTheWorld) {
scene[xPos][yPos] = 0;
} else {
scene[xPos][yPos] = 0;
}
yPos++;
if(yPos>worldHeight) {
topOfTheWorld += 0;
yPos = 0;
xPos++;
}
if (xPos>worldWidth) {
break;
}
}
std::ofstream output("mapa.txt");
for(int y=0;y<worldHeight;y++) {
for(int x=0;x<worldWidth;x++) {
output<<scene[x][y];
if(x<(worldWidth-1)){output<<",";}
}
if(y<(worldHeight-1)){output<<std::endl;}
}
MessageBox(0, "World generation has finished!", "Finished!", MB_OK);
}
That generates a world based in an array. But when I add:
slope = random(5)-2;
To:
if(yPos == worldHeight) {
topOfTheWorld += 0; //There would be the slope var...
if(yPos == worldHeight) {
slope = random(5)-2;
topOfTheWorld += slope;
For some reason the while becomes an infinite loop, and I don't know why.
(Random Function)
#include <time.h>
#include <windows.h>
int random(int n = 0) {
srand(time(NULL));
if(n!=0){
return rand() % n;
} else {
return rand();
}
}
(Variables)
const int worldWidth = 50;
const int worldHeight = 26;
int topOfTheWorld = worldHeight/2;
int xPos = 0;
int yPos = 0;
int scene[worldWidth][worldHeight];
int slope;
What can I do?
You show that scene is defined as:
int scene[worldWidth][worldHeight];
However, your code has this:
if (xPos>worldWidth) {
break;
}
Which means you will actually write a value outside the array boundary when xPos == worldWidth, and this causes undefined behavior. Adding the slope variable may cause your variable organization to change in a way that the undefined behavior ends up affecting the values of and or all of your loop control variables.
To fix, you should change the erroneous check with:
if (xPos>=worldWidth) {
break;
}
You have since edited your question with code that makes your yPos check incorrect in a similar way.
There's a repeated calls to srand in your random function
Fixes : -
void generar() {
srand(time(NULL)); //Remove srand() from random(), add it here
bool finished = false;
while (!finished) {
if (yPos == topOfTheWorld) {
scene[xPos][yPos] = 2;
} else if (yPos >= topOfTheWorld) {
scene[xPos][yPos] = 1;
} else if(yPos < topOfTheWorld) {
scene[xPos][yPos] = 0;
} else {
scene[xPos][yPos] = 0;
}
yPos++;
if(yPos == worldHeight) {
// slope = random(5)-2; your random call
topOfTheWorld += 0;
yPos = 0;
xPos++;
}
if (xPos>worldWidth) {
finished = true;
//goto Guardar; not required,
//also use of goto is bad programming practice
}
}

Checking for overlapping characters in a wordsearch game

I am developing a wordsearch generator to learn c++ better and I am stuck on preventing non-overlapping words from overlapping, such as a side-to-side word writing over a letter in a top-down word. Here is the code snippet:
else if (random_choice == 1 && random_word.size() <= 10-j && words_vector.size() != 0) {
flag = true;
for (int x = 0; x < random_word.size(); x++) {
if (wordsearch[i][j+x] != '0') {
flag = false;
break;
}
}
if (flag = true) {
for (int x = 0; x < random_word.size(); x++) {
wordsearch[i][j] = random_word[x];
j += 1;
}
j -= 1;
words_found_vector.insert(words_found_vector.begin(),words_vector[random_word_number]);
//words_vector.erase(words_vector.begin()+random_word_number);
}
else {
wordsearch[i][j] = '1';
}
}
What I have done was create a two dimensional array [10][11] filled with the 0 (zero) character so when I iterate through it all spaces are filled with 0 except for the 11th space in each line with a newline character to make a 10X10 grid. In my else if loop, the first part already has a word chosen and it tests if the word will fit in its proper space by checking if a 0 is present. If it runs into a non-zero character (such as if it runs into a letter from a top-down or diagonal word) the inner loop terminates, sets the boolean flag, and inputs a 1 (or any random letter) instead of the whole word. What happens is that the whole word is inserted anyways and overwrites one letter from the top down word. What am I doing wrong? Here is the rest of the code:
#include <iostream>
#include <cstdlib>
#include <time.h>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
srand(time(NULL));
const char* const a_to_z = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ;
int random_char;
char wordsearch [10][11] = {0};
bool flag;
string words_array[] = {"CAT", "HELLO", "GOODBYE", "DOG", "BAT", "NEW", "SAY", "MAY", "DAY", "HAY"};
vector<string> words_vector (words_array, words_array + sizeof(words_array) / sizeof(string));
string words_found_array[] = {};
vector<string> words_found_vector (words_found_array, words_found_array + sizeof(words_found_array) / sizeof(string));
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 11; j++) {
int random_choice = rand() % 5;
int random_word_number = rand() % words_vector.size();
string random_word = words_vector[random_word_number];
if (j == 10) {
wordsearch[i][j] = '\n';
}
else if (random_choice == 1 && random_word.size() <= 10-j && words_vector.size() != 0) {
flag = true;
for (int x = 0; x < random_word.size(); x++) {
if (wordsearch[i][j+x] != '0') {
flag = false;
break;
}
}
if (flag = true) {
for (int x = 0; x < random_word.size(); x++) {
wordsearch[i][j] = random_word[x];
j += 1;
}
j -= 1;
words_found_vector.insert(words_found_vector.begin(),words_vector[random_word_number]);
//words_vector.erase(words_vector.begin()+random_word_number);
}
else {
wordsearch[i][j] = '1';
}
}
else if (random_choice == 2 && random_word.size() <= 10-i && words_vector.size() != 0) {
int temp_i = i;
flag = true;
for (int x = 0; x < random_word.size(); x++) {
if (wordsearch[i+x][j] != '0') {
flag = false;
break;
}
}
if (flag = true) {
for (int x = 0; x < random_word.size(); x++) {
wordsearch[i][j] = random_word[x];
i += 1;
}
i = temp_i;
words_found_vector.insert(words_found_vector.begin(),words_vector[random_word_number]);
//words_vector.erase(words_vector.begin()+random_word_number);
}
else {
wordsearch[i][j] = '1';
}
}
else {
int random_char = rand() % 26 + 0;
wordsearch[i][j] = a_to_z[random_char];
}
}
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 11; j++) {
cout<<wordsearch[i][j];
}
}
cout<<"Your words are:"<<endl;
for (int x = 0; x < words_found_vector.size(); x++) {
cout<<words_found_vector[x]<<endl;
}
}
One more thing:
//words_vector.erase(words_vector.begin()+random_word_number);
crashes my program. I think it is a scoping issue with this:
int random_choice = rand() % 5;
int random_word_number = rand() % words_vector.size();
string random_word = words_vector[random_word_number];
What I want to do is eventually have the user give me a list of words they want to search for and this function chooses some of them and presents it to the user when playing the game. This not functioning correctly also causes duplicates to appear in the crossword and words-to-find-list.
Thank you for your help!
You have this error twice in your code:
if (flag = true)
That is not a condition, it's an assignment. It assigns true to flag, and the if-block will always execute. You need to make it a comparison condition by using ==
if (flag == true)
A more common way to write that in C++ would be just
if (flag)

Game of Life array edges acting weird

I saw Conway's Game of Life and decided to make my own.
I have a bool array to represent the world, but the edges (Top and bottom) are acting weird, random cells becomes live.
In this code, it does not print the bottom and top of the world, but this is a bad solution.
The world "wraps" at the right and the left, causing even more problems, but that is for another time.
#include <iostream>
const int height = 20;
const int width = 20;
bool now_world[height][width];
bool then_world[height][width];
void clear_world();
void place_random_live_cells();
void then_world_initialization();
void print_world();
void generation_pass();
void update_worlds();
int main(int argc, const char * argv[])
{
using namespace std;
srand((unsigned)time(NULL));
int timer = 0;
int generation = 0;
clear_world();
place_random_live_cells();
then_world_initialization();
bool running = true;
while (running) {
if (timer == 50000000) {
cout << "Generation #" << generation << endl;
print_world();
generation_pass();
update_worlds();
++generation;
timer = 0;
}
++timer;
}//While (running) ends here
return 0;
}
void place_random_live_cells()
{
int percent = 30;
int max_live_cells = ((height * width) / 100) * percent;
int current_live_cells = 0;
while (current_live_cells < max_live_cells) {
int ycoords = 0 + (rand() % (height + 1));
int xcoords = 0 + (rand() % (width + 1));
if (now_world[ycoords][xcoords] == false) {
now_world[ycoords][xcoords] = true;
} else {
current_live_cells--;
}
++current_live_cells;
}
}
//A generation pass and cells die and some cells come to life
void generation_pass()
{
using namespace std;
int neighbours = 0;
for (int iii = 0; iii < height; iii++) {
for (int jjj = 0; jjj < width; jjj++) {
//Count neighbouring cells that are alive
if (now_world[iii+1][jjj+1] == true) {
++neighbours;
}
if (now_world[iii+1][jjj ] == true) {
++neighbours;
}
if (now_world[iii+1][jjj-1] == true) {
++neighbours;
}
if (now_world[iii ][jjj+1] == true) {
++neighbours;
}
if (now_world[iii ][jjj-1] == true) {
++neighbours;
}
if (now_world[iii-1][jjj+1] == true) {
++neighbours;
}
if (now_world[iii-1][jjj ] == true) {
++neighbours;
}
if (now_world[iii-1][jjj-1] == true) {
++neighbours;
}
//Apply rules to the cells
//Dead cells with three live neighbours becomes alive
if (then_world[iii][jjj] == false && neighbours == 3) {
then_world[iii][jjj] = true;
}
//Alive with fewer than two, they die
if (then_world[iii][jjj] == true && neighbours < 2) {
then_world[iii][jjj] = false;
}
//Alive with 2 or three live neighbours live on unchanged
if (then_world[iii][jjj] == true && neighbours == 2) {
then_world[iii][jjj] = true;
}
if (then_world[iii][jjj] == true && neighbours == 3) {
then_world[iii][jjj] = true;
}
//Alive with more than three, they die
if (then_world[iii][jjj] == true && neighbours > 3) {
then_world[iii][jjj] = false;
}
//Dead cells without exactly three live neighbours remain dead
//Reset neighbour value to zero
neighbours = false;
}
}
}
//Make next generation identical to current
//This is only called once
void then_world_initialization()
{
for (int iii = 0; iii < height; iii++) {
for (int jjj = 0; jjj < width; jjj++) {
then_world[iii][jjj] = now_world[iii][jjj];
}
}
}
//Make the next generation be today
//This is called every generation
void update_worlds()
{
for (int iii = 0; iii < height; iii++) {
for (int jjj = 0; jjj < width; jjj++) {
now_world[iii][jjj] = then_world[iii][jjj];
}
}
}
//Set all cells to dead
void clear_world()
{
for (long iii = 0; iii < height; iii++) {
for (long jjj = 0; jjj < width; jjj++) {
now_world[iii][jjj] = false;
then_world[iii][jjj] = false;
}
}
}
//Print world
void print_world()
{
using namespace std;
char live = 'X';
char dead = '.';
for (long iii = height; iii > 0; iii--) {
for (long jjj = width; jjj > 0; jjj--) {
if (iii != 0 && iii != height) {
if (now_world[iii][jjj]) {
cout << live;
} else {
cout << dead;
}
cout << " ";
}
}
cout << endl;
}
cout << endl;
}
Having done this for a course I taught in the past, the most common issue I always see people having is going outside the bounds of the array they're using.
If you look at the if statements in your nested for loop, I think you'll find some issues. For instance, in this case, what happens when iii equals (height-1) or jjj equals (width-1)?
for (int iii = 0; iii < height; iii++) {
for (int jjj = 0; jjj < width; jjj++) {
//Count neighbouring cells that are alive
if (now_world[iii+1][jjj+1] == true) {
++neighbours;
You're going outside the bounds of your array and so your results will be undefined. You may get segfaults, but you may just also get spurious data. C++ doesn't enforce you staying within the bounds of the array you define.
Make sure you also handle cases like this:
if (now_world[iii-1][jjj+1] == true) {
++neighbours;
}
What if iii equals zero?
Hope that helps.
You're trying to access out-of-boundary indexes in your array.
I'm not sure what behaviour you expect, but an easy way is to not calculate updates for cells on the edges.
So in generation_pass the loops should go from 1 till height-1.