c++ sudoku program using Back tracking, Segmentation fault (core dumped) ,all suggestions are welcomed [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
#include <iostream>
using namespace std;
//defining 9X9 grid.
int a[9][9] ={{0,0,3,0,9,2,6,0,0},
{1,0,0,3,0,0,8,0,0},
{0,0,5,0,1,0,0,4,0},
{0,3,0,0,0,0,2,5,8},
{2,4,0,0,5,0,0,0,0},
{0,0,0,6,2,0,0,0,3},
{0,1,4,0,0,9,0,3,0},
{6,0,0,7,0,0,1,0,0},
{3,0,0,0,0,4,0,0,2} };
// class sudoku.
class sudoku{
public:
int row,col,i,j,num;
//to check presence of element in particular row.
bool rowCheck(int a[9][9],int &row,int num)
{
for(j=0;j<9;j++)
{
if(a[row][j]==num)
return true;
}
return false;
}
//to check presence of element in particular column.
bool colCheck(int a[9][9], int &col, int num)
{
for(j=0;j<9;j++)
{
if(a[j][col]==num)
return true;
}
return false;
}
//to check presence of element in particular 3X3 grid.
bool boxCheck(int a[9][9],int &row ,int &col ,int num)
{
int x,y;
if(row<3)
x=0;
else if(row>=3 && row<6)
x=3;
else
x=6;
if(col<3)
int y=0;
else if(col>=3 && col<6)
y=3;
else
y=6;
for(i=x;i<x+3;i++)
{
for(j=y;j<y+3;j++)
{
if(a[i][j]==num)
return true;
}
}
return false;
}
//to check index which is unassigned.
bool unAssigned(int a[9][9],int &row,int &col)
{
for(row=0;row<9;row++)
{
for(col=0;col<9;col++)
{
if(a[row][col]==0){
return true;}
}
}
return false;
}
//to return true if position is suitable to insert .
bool isSafe(int a[9][9],int &row,int &col,int num)
{
if(!rowCheck(a,row,num) && !colCheck(a,col,num) &&
!boxCheck(a,row,col,num))
return true;
else
return false;
}
//function to solve sudoku.
bool sudokuSolver(int a[9][9])
{
if(!unAssigned(a,row,col))
return true;
for(i=1;i<=9;i++)
{
if(isSafe(a,row,col,i))
{
a[row][col]=i;
cout<<a[row][col];
if(sudokuSolver(a))
return true;
a[row][col]=0;
}
}
return false;
}
void display(int a[9][9])
{
for(i=0;i<9;i++)
{
for(j=0;j<9;j++)
{
cout<<a[i][j]<<" ";
}
cout<<endl;
}
}
//class ends
};
//main method
int main()
{
sudoku s;
s.sudokuSolver(a);
s.display(a);
return 0;
}

After calling: unAssigned(a,row,col) the value of row is 9 and the value of colis 9 when unAssigned() returns false. This is a consequence of using references to row and col.
bool unAssigned(int a[9][9],int &row,int &col)
{
for(row=0;row<9;row++)
{
for(col=0;col<9;col++)
{
if(a[row][col]==0){
return true;}
}
}
// here: row is 9 and col is 9
return false;
}
This means that you can return from sudokuSolver() with row and col out of bounds. This will trigger a segmentation fault in the following line:
if(sudokuSolver(a))
return true;
// here row or col are equal to 9 which is out of bounds
a[row][col]=0; // seg-fault here

You never initialize row and col which leads to undefined behaviour once you use their values.
Apart from that, I would suggest you to avoid hard coded array bounds and raw loops. If you use containers and iterators instead you can avoid out of bounds errors completely (not the problem here, but a line for(i=1;i<=9;i++) looks very suspicious and makes me think twice to realize that it is ok).
Moreover, dont pass by reference if the parameter is actually not modified by the method. E.g. bool colCheck(int a[9][9], int &col, int num) does not modify col, thus it is rather confusing why it takes col as reference. Also it is confusing that both row and col are members of the class but at the same time you pass them between the methods. I would suggest to rename the members to max_row and max_col, respectively.

Related

why doesnt the bool function return false?

I'm soo sorry I searched for and read similar questions but couldn't understand/use them to solve my own.
Im writing a bool function within an if statement but the function doesn't seem to return false, what am I doing wrong.
My bool function just checks if there are more than one of the given number in an array:
bool findsame(int a[], int b){
int k=0;
for(int i=0;i<20;i++){
if(a[i]==b){
k++;
}
}
if(k>1){
return true;
}
else{
return false;
}
}
int main()
{
const int size=20;
int a[size]={4,4};
int b=4;
if(findsame(a,b)){
cout<<"true";
}
}
I think you got confused why "false" is not getting printed on console with the function returning the false value.
You need to add to an extra else statement to print false on the console:
if(findsame(a,b)){
std::cout<<"true";
}else{
std::cout<<"false";
}
Also, there are two 4 values in the array, therefore always true will get printed.
Try passing value of b other than 4 and 0.
Have a look at the following implementation where value of variable b is equal to 1:
#include<iostream>
bool findsame(int a[], int b){
int k=0;
for(int i=0;i<20;i++){
if(a[i]==b){
k++;
}
}
if(k>1){
return true;
}
else{
return false;
}
}
int main()
{
const int size=20;
int a[size]={4,4};
int b=1;
if(findsame(a,b)){
std::cout<<"true";
}else{
std::cout<<"false";
}
}
Output:
false
PS: I have also tested code for the value of b = 4 and it prints true. Check and Run the code here: https://onlinegdb.com/S1LR5PtvD

How to solve 8-puzzle problem using Breadth-First search in C++

I want to build a c++ program that would solve 8-puzzle problem using BFS.
I want to show every generated state.
But the problem is, I don't know how to generate state.
I just want some clean function which will efficiently generate states and there will be a Explored array which will assure that there is no redundant state.
I've explored GitHub but there is too much complex solutions
I've written the following code till now
#include<iostream>
#include<conio.h>
using namespace std;
class puzzle{
private:
int initial[3][3],goal[3][3] = {{1,2,3},{4,5,6},{7,8,0}};
int queue[1000];
string data;
public:
void genratePuzzle();
void showState();
bool check_goal(int initial);
};
void puzzle::genratePuzzle(){
cout<<"\n***Create initial state 0-8***\n";
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
cout<<"Insert at ["<<i<<"]["<<j<<"] : ";
cin>>initial[i][j];
}
}
}
void puzzle::showState(){
cout<<"\n***State***\n";
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
cout<<initial[i][j]<<" ";
}
cout<<endl;
}
}
bool puzzle::check_goal(int initial){
bool check = true;
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
if(initial[i][j] != goal[i][j]){
check = false;
}
}
}
return check;
}
int main(){
puzzle p1;
p1.genratePuzzle();
p1.showState();
getch();
}
Goal state
1 2 3
4 5 6
7 8 0
Put your state into
struct state {
int data[3][3];
bool operator < (const state & other) {
for (int y=0; y<3; ++y) {
for (int x=0; x<3; ++x) {
if (data[y][x] < other.data[y][x]) {
return true;
}
if (data[y][x] > other.data[y][x]) {
return false;
}
}
}
return false; // all were equal
}
}
Now you can use values of type state as keys in a std::map e.g. make a std::map<state, bool> explored if you want. It behaves like an array indexed by states, so:
state a;
// do something to the state...
// and you can do this
explored[a] = true;
How do you generate new states? You start with an existing state and try all valid moves on it. Repeat until done.

Program works fine only for one test case - Debugging [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I want to know whether my graph is bipartite or not, I have several test cases. If I run more than one test case it doesn't work properly, it always shows Bipartite. I am having a hard time figuring it out. For just one case, it works fine for any graph.
Here goes my code.
#include <iostream>
#include <cstdio>
#include <stack>
#include <list>
using namespace std;
class Graph
{
public:
int V;
list<int> *adj;
Graph(int V);
void addEdge(int v, int w);
};
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w);
adj[w].push_back(v);
}
class Bipartite
{
private:
bool isBipartite;
bool *color;
bool *marked;
int *edgeTo;
stack<int> cycle;
public:
Bipartite(Graph G)
{
isBipartite = true;
color = new bool [G.V];
marked = new bool [G.V];
edgeTo = new int [G.V];
for (int v = 0; v < G.V; v++)
{
if (!marked[v])
{
color[v] = false;
dfs(G, v);
}
}
delete color;
delete marked;
delete edgeTo;
}
void dfs(Graph G, int v)
{
marked[v] = true;
list<int>::iterator w;
for (w = G.adj[v].begin(); w != G.adj[v].end(); w++)
{
if (!cycle.empty())
return;
if (!marked[*w])
{
edgeTo[*w] = v;
color[*w] = !color[v];
dfs(G, *w);
}
else if (color[*w] == color[v])
{
isBipartite = false;
cycle.push(*w);
for (int x = v; x != *w; x = edgeTo[x])
{
cycle.push(x);
}
cycle.push(*w);
}
}
}
bool isBi()
{
return isBipartite;
}
};
void solve(int n,int **p){
long long int x,y;
Graph g(n);
for(x=0;x<n;x++)
for(y=0;y<n;y++)
{
if(p[x][y]==1)
g.addEdge(x,y);
}
Bipartite b(g);
if (b.isBi())
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
int main()
{
long long int i,j,t,x,m,y,a,b;
int **p,n;
cin>>t;
for(i=0;i<t;i++)
{
cin>>n>>m;
p=new int*[n]();
for(x=0;x<n;x++)
{
p[x]=new int[n]();
}
for(j=0;j<m;j++)
{
cin>>a>>b;
a=a-1;
b=b-1;
p[a][b]=1;
p[b][a]=1;
}
for(x=0;x<n;x++)
{
for(y=0;y<n;y++)
{
if(x!=y)
{
p[x][y]=1-p[x][y];
}
}
}
/* for(x=0;x<n;x++)
{
for(y=0;y<n;y++)
cout<<p[x][y]<<" ";
cout<<"\n";
}
*/
solve(n,p);
}
return 0;
}
You never explicitly initialize the contents of marked, or, more accurately, the contents of the array that it points to.
The loop in your constructor reads elements of marked to decide how to assign to color, but you never initialized the elements of marked being read.
Similiar argument for color and edgeTo.
This means that, while they may have had the expected initializations for the first case, may well be using whatever value happened to be there in later cases.
Also Bipartite(Graph G) is calling the default copy constructor of Graph. Probably not what you want.
Try Bipartite(const Graph & G) instead (also in dfs).
And don't do new without delete.
Rather use vector<vector<int>> adj;, why even list? And reinit it in constructor with adj.resize(V);.
After your edit of code in question, as you use new to allocate array, you should delete it as array too, so use delete[] color;.
Or stop using new/delete completely. Again you can use std::vector<bool> color(G.V);, avoiding both new/delete hassle, and also having all values initialized to false by default.
In modern C++ there're very few (more like "none") reasons to ever use new or delete (unless you write some low level library, or you are optimizing for performance, and you know what you are doing).

Beginning of an nQueens game in c++. Where is the error located in my code? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I keep getting errors when trying to compile the following code. The error is
expected ',' or ';' before '{' token.
It says there's an error on the parentheses after the bool check_row(x)
If I comment it out the same happens for bool check_col(x).
I kept looking back at my books if I didn't define my functions properly but they seem correct, logically.
This is the beginning of an nQueens game on a 4x4 board.
The Queen is represented by the number 1.
The two boolean functions are to check if the row and columns are free.
startGame() assigns 0 to all boxes, and showBoard() shows results of the board.
#include <cstdlib>
#include <iostream>
using namespace std;
int x=0, y=0;
int square[4][4];
void startGame()
{
for(x=0;x<4;x++)
{
for(y=0;y<4;y++)
{
square[x][y]=0;
}
}
}
void showBoard()
{
for(int x=0;x<4;x++)
{
if(x!=0)
{
cout<<endl;
}
for(int y=0;y<4;y++)
{
cout<<square[x][y];
}
}
cout<<endl;
}
bool check_row(x)
{
for(y=0;y<4;y++)
{
if(square[x][y]==1)
{
return false;
}
else if(square[x][y]==0)
{
if(y==3)
{
return true;
}
continue;
}
}
}
bool check_col(y)
{
for(int x=0;x<4;x++)
{
if(square[x][y]==1)
{
return false;
}
else if(square[x][y]==0)
{
if(x==3)
{
return true;
}
continue;
}
}
}
int main(){
startGame();
showBoard();
return 0;
}
bool check_col(y) isn't a valid prototype. You need to provide a type for y - for example bool check_col(int y). The same applies to bool check_row(x).
you have to specify the datatype which you are passing as a parameter in your function..considering x and y are of int type and are local, your function prototype should be
bool check_row(int x)
bool check_col(int y)
If x and y are global then there is no need to pass them..simply
bool check_row()
bool check_col()
will work as the visibility of global variables will be throughout the program, unless shadowed

Generating permutation of string without duplicates [duplicate]

This question already has answers here:
Finding all the unique permutations of a string without generating duplicates
(5 answers)
Closed 9 years ago.
I have writing a general program to generate permutation of string but removing the duplicate cases . For this I am using memorization by using .
void permute(char *a,int i, int n,set<char*> s)
{
if(i==n)
{
if(s.find(a)==s.end()){
cout<<"no dublicate"<<endl;
cout<<a<<endl;
s.insert(a)
}
}
else{
for(int j=i;j<n;j++)
{
swap(a[i],a[j]);
permute(a,i+1,n,s);
swap(a[i],a[j]);
}
}
}
int main()
{
char a[]="aba";
set <char*> s;
permute(a,0,3,s);
return 0;
}
But the result is not as desired. It prints all the permutation. Can anyone help me in figuring out the problem.
First, you pass set<> s parameter by value, which discards your each insert, because it's done in the local copy of s only. However even if you change it to pass by reference, it won't work, because every time you insert the same char* value, so only one insert will be done. To make your code work correctly I suggest to change the prototype of your function to
void permute(string a,int i, int n,set<string>& s)
and this works all right.
update: source code with described minor changes
void permute(string a,int i, int n,set<string>& s)
{
if(i==n)
{
if(s.find(a)==s.end()){
cout<<"no dublicate"<<endl;
cout<<a<<endl;
s.insert(a);
}
}
else{
for(int j=i;j<n;j++)
{
swap(a[i],a[j]);
permute(a,i+1,n,s);
swap(a[i],a[j]);
}
}
}
int main()
{
string a ="aba";
set <string> s;
permute(a,0,3,s);
return 0;
}