Ending OpenMP for prematurely - c++

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;
}

Related

(C++) openmp leading to segmentation fault

I'm new to using OpenMP on C++ and facing some issues with it:
#include <algorithm>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using boost::multiprecision::cpp_int;
// generates prime numbers under n
vector<int> generatePrime(int n) {
vector<int> primes;
for (int i = 2; i <= n; i++) {
bool isPrime = true;
for (int j = 0; j < primes.size(); j++) {
if (i % primes[j] == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
primes.push_back(i);
}
}
return primes;
}
// checks if an integer is a prime number
bool chkPrime(vector<int> vec, vector<int> ref) {
for (int i = 0; i < vec.size(); i++) {
if (find(ref.begin(), ref.end(), vec[i]) == ref.end()) {
return false;
}
}
return true;
}
int main() {
vector<int> primes = generatePrime(100);
vector<cpp_int> row(1, 1);
int maxAlleles = 1000;
vector<vector<int>> rowPrime;
for (int alleles = 1; alleles <= maxAlleles; alleles++) {
vector<cpp_int> row1 = row;
row1.push_back(0);
row1.push_back(0);
vector<cpp_int> row2 = row1;
vector<cpp_int> row3 = row1;
vector<cpp_int> rowFinal;
rotate(row2.begin(), row2.end() - 1, row2.end());
rotate(row3.begin(), row3.end() - 2, row3.end());
for (int i = 0; i < row1.size(); i++) {
// making the next row of the trinomial triangle
rowFinal.push_back(row1[i] + row2[i] + row3[i]);
}
row = rowFinal;
#pragma omp parallel for
// for each number in the row, we will make the number into a string and divide it by 2 letters
// and put it into a vector (splitTwo), starting from the beginning of the string
for (int num = 0; num < row.size(); num++) {
string item = to_string(row[num]);
vector<int> splitTwo;
int i = 0;
if (item.length() % 2 == 0) {
while (i <= item.length() - 2) {
splitTwo.push_back(stoi(item.substr(i, 2)));
i += 2;
}
}
else {
if (item.length() > 2) {
while (i <= item.length() - 3) {
splitTwo.push_back(stoi(item.substr(i, 2)));
i += 2;
}
}
int last_letter = item[item.length() - 1] - '0';
splitTwo.push_back(last_letter);
}
// we are going to push back splitTwo in rowPrime if all items in splitTwo are prime numbers
if (chkPrime(splitTwo, primes) == true) {
splitTwo.push_back(alleles);
splitTwo.push_back(num);
rowPrime.push_back(splitTwo);
}
}
}
vector<int> sum;
for (int k = 0; k < rowPrime.size(); k++) {
sum.push_back(
accumulate(begin(rowPrime[k]), end(rowPrime[k]) - 2, 0, plus<int>()));
}
int idx = distance(begin(sum), max_element(begin(sum), end(sum)));
for (int &i : rowPrime[idx]) {
cout << i << ' ';
}
cout << sum[idx] << ' ' << rowPrime.size();
return 0;
}
When I use pragma omp parallel for on the code above and make an executable file, it leads to different results each time I execute the code: either 1) outputs the answer properly, or 2) gives a segmentation fault error, or 3) gives a Incorrect checksum for freed object 0x7fd0ef904088: probably modified after being freed. Corrupt value: 0x0 malloc: *** set a breakpoint in malloc_error_break to debug error. When I remove pragma omp parallel for it does not give me these errors. Any suggestions?

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
}

C++ Getting a "Control may reach end of a non-void function on a Johnson-Trotter code

What can I do to silence this warning? Do I need to add another return statement somewhere or do I need to change something within the functions?
Also could someone help me add arrows into the Johnson-Trotter algorithm. It would be nice to have them to show the direction but I am very confused on how to do it; though this isn't the main concern right now I just want the program to run. Thank you in advance.
These are the two functions with the warning:
int searchArr(int k[], int n, int mobile)
{
for(int i = 0; i < n; i++)
{
if (k[i] == mobile)
{
return i + 1;
}
}
}
int printOnePerm(int k[], bool dir[], int n)
{
int mobile = getMobile(k, dir, n);
int pos = searchArr(k, n, mobile);
if (dir[k[pos - 1] - 1] == RIGHT_TO_LEFT)
{
swap(k[pos - 1], k[pos -2]);
}
else if (dir[k[pos - 1] - 1] == LEFT_TO_RIGHT)
{
swap(k[pos], k[pos -1]);
}
for(int i = 0; i < n; i++)
{
if (k[i] > mobile)
{
if (dir[k[i] - 1] == LEFT_TO_RIGHT)
{
dir[k[i] - 1] = RIGHT_TO_LEFT;
}
else if(dir[k[i] - 1] == RIGHT_TO_LEFT)
{
dir[k[i] - 1] = LEFT_TO_RIGHT;
}
}
}
for(int i = 0; i < n; i++)
{
cout << k[i];
}
cout << endl;
}
For the first function, searchArr(), one question is what do you expect it to return if the value is not found. Since the return values are in the range [1,n], I'm guessing that zero means not found.
I prefer to design functions which have a single return at the end, whenever possible. A default fail value can be set at the start of the function. I would exit the loop when the value is found, or fall through with the default value set.
Here is what I would write:
int searchArr(int k[], int n, int mobile)
{
int ret = 0; /* not found value */
for(int i = 0; i < n; i++)
{
if (k[i] == mobile)
{
ret = i + 1;
break;
}
}
return ret;
}
Alternately, and perhaps a bit more obscurely, if the value is not found in the array, then i will equal n when the for loop completes. This would be a possible function:
int searchArr(int k[], int n, int mobile)
{
for(int i = 0; i < n; i++)
{
if (k[i] == mobile)
{
break;
}
}
if (i < n)
return i + 1;
else
return 0;
}
The for loop can be shrunk to
for(int i = 0; i < n && k[i] != mobile; i++) ;
And the return can be shrunk to
return (i < n) ? i + 1 : 0;
Although I generally discourage using the ?: operator.
As mentioned above, the second function doesn't return any value and should be declared "void".
The first one:
int searchArr(int k[], int n, int mobile)
{
for(int i = 0; i < n; i++)
{
if (k[i] == mobile)
{
return i + 1;
}
}
}
will not return anything if for some reason nothing in your array matches. In that case, you need to return a default or error value:
int searchArr(int k[], int n, int mobile)
{
for(int i = 0; i < n; i++)
{
if (k[i] == mobile)
{
return i + 1;
}
}
return -1; // not found
}
The second one doesn't seem to want to return anything. In C++, the way to do this is with a void, not an int (That was okay in C. C++ not so much):
// assuming we don't want to return anything
void printOnePerm(int k[], bool dir[], int n)

Generate numbers from 2 to 10,000. The numbers printed can only be a multiple of 2 prime numbers

Homework: I'm just stumped as hell. I have algorithms set up, but I have no idea how to code this
Just to be clear you do not need arrays or to pass variables by reference.
The purpose of the project is to take a problem apart and using Top-Down_Design or scratch pad method develop the algorithm.
Problem:
Examine the numbers from 2 to 10000. Output the number if it is a Dual_Prime.
I will call a DualPrime a number that is the product of two primes. Ad where the two primes are not equal . So 9 is not a dual prime. 15 is ( 3 * 5 ) .
The output has 10 numbers on each line.
My Algorithm set-up
Step 1: find prime numbers.:
bool Prime_Number(int number)
{
for (int i = 2; i <= sqrt(number); i++)
{
if (number % 1 == 0)
return false;
}
return true;
}
Step 2: store prime numbers in a array
Step 3: Multiply each array to each other
void Multiply_Prime_Numbers(int Array[], int Size)
{
for (int j = 0; j < Size- 1; j++)
{
Dual_Prime[] = Arr[j] * Arr[j + 1]
}
}
Step 4: Bubble sort
void Bubble_Sort(int Array[], int Size) // Sends largest number to the right
{
for (int i = Size - 1; i > 0; i--)
for (int j = 0; j < i; j++)
if (Array[j] > Array[j + 1])
{
int Temp = Array[j + 1];
Array[j + 1] = Array[j];
Array[j] = Temp;
}
}
Step 5: Display New Array by rows of 10
void Print_Array(int Array[], int Size)
{
for (int i = 0; i < Size; i++)
{
cout << Dual_Prime[i] << (((j % 10) == 9) ? '\n' : '\t');
}
cout << endl;
}
I haven't learned dynamic arrays yet,
Although dynamic arrays and the sieve of Eratosthenes are more preferable, I tried to write minimally fixed version of your code.
First, we define following global variables which are used in your original implementation of Multiply_Prime_Numbers.
(Please check this post.)
constexpr int DP_Size_Max = 10000;
int DP_Size = 0;
int Dual_Prime[DP_Size_Max];
Next we fix Prime_Number as follows.
The condition number%1==0 in the original code is not appropriate:
bool Prime_Number(int number)
{
if(number<=1){
return false;
}
for (int i = 2; i*i <= number; i++)
{
if (number % i == 0)
return false;
}
return true;
}
In addition, Multiply_Prime_Numbers should be implemented by double for-loops as follows:
void Multiply_Prime_Numbers(int Array[], int Size)
{
for (int i = 0; i < Size; ++i)
{
for (int j = i+1; j < Size; ++j)
{
Dual_Prime[DP_Size] = Array[i]*Array[j];
if(Dual_Prime[DP_Size] >= DP_Size_Max){
return;
}
++DP_Size;
}
}
}
Then these functions work as follows.
Here's a DEMO of this minimally fixed version.
int main()
{
int prime_numbers[DP_Size_Max];
int size = 0;
for(int j=2; j<DP_Size_Max; ++j)
{
if(Prime_Number(j)){
prime_numbers[size]=j;
++size;
}
}
Multiply_Prime_Numbers(prime_numbers, size);
Bubble_Sort(Dual_Prime, DP_Size);
for(int i=0; i<DP_Size;++i){
std::cout << Dual_Prime[i] << (((i % 10) == 9) ? '\n' : '\t');;
}
std::cout << std::endl;
return 0;
}
The Sieve of Eratosthenes is a known algorithm which speeds up the search of all the primes up to a certain number.
The OP can use it to implement the first steps of their implementation, but they can also adapt it to avoid the sorting step.
Given the list of all primes (up to half the maximum number to examine):
Create an array of bool as big as the range of numbers to be examined.
Multiply each distinct couple of primes, using two nested loops.
If the product is less than 10000 (the maximum) set the corrisponding element of the array to true. Otherwise break out the inner loop.
Once finished, traverse the array and if the value is true, print the corresponding index.
Here there's a proof of concept (implemented without the OP's assignment restrictions).
// Ex10_TwoPrimes.cpp : This file contains the 'main' function. Program execution begins and ends there.
#include "pch.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void Homework_Header(string Title);
void Do_Exercise();
void Sieve_Of_Eratosthenes(int n);
void Generate_Semi_Prime();
bool Semi_Prime(int candidate);
bool prime[5000 + 1];
int main()
{
Do_Exercise();
cin.get();
return 0;
}
void Do_Exercise()
{
int n = 5000;
Sieve_Of_Eratosthenes(n);
cout << endl;
Generate_Semi_Prime();
}
void Sieve_Of_Eratosthenes(int n)
{
// Create a boolean array "prime[0..n]" and initialize
// all entries it as true. A value in prime[i] will
// finally be false if i is Not a prime, else true.
memset(prime, true, sizeof(prime));
for (int p = 2; p*p <= n; p++)
{
// If prime[p] is not changed, then it is a prime
if (prime[p] == true)
{
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
}
bool Semi_Prime(int candidate)
{
for (int index = 2; index <= candidate / 2; index++)
{
if (prime[index])
{
if (candidate % index == 0)
{
int q = candidate / index;
if (prime[q] && q != index)
return true;
}
}
}
return false;
}
void Generate_Semi_Prime()
{
for (int i = 2; i <= 10000; i++)
if (Semi_Prime(i)) cout << i << "\t";
}

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)