Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

This is the assignment: Write a program which allocates the integers 1-8 to the

ID: 3626017 • Letter: T

Question

This is the assignment: Write a program which allocates the integers 1-8 to the squares in the figure above, subject to the restrictions that no two adjacent squares contain consecutive integers.
By adjacent we mean vertically, horizontally, or diagonally.

But each time I put it to work it tells me segmentation fault. Please help

#include<iostream>
#include <cmath>
using namespace std;

bool ok(int a[], int pos, int h[][5]);
void backtrack(int &c);
void print(int a[]);


//below is how I label the cross(1D array)
/*
1 2
0 3 4 5
6 7
*/



int main(){

int board[8]={0}, c=1;
int refer[8][5]={{-1,-1,-1,-1,-1},{0,-1,-1,-1,-1},{1,-1,-1,-1,-1},{0,1,2,-1,-1},{1,2,3,-1,-1},{2,4,-1,-1,-1},{0,3,4,-1,-1},{3,4,5,6,-1}}; //helper array tells me which box I shoud check depend on how I label the cross

board[0]=1; //we start with 1 in the zero index of the cross

while (c<9)
{
if(c==8) //the 1d array' max index is 7, if index=8 means we have a solution, print it
{
print(board);
return 0;
}

while(board[c]<10) //set the value in each box does not exceed 9, include 9, because we want to check if it fail to put
{ //a 8 in it.
board[c]++; //each time the box fails the check, we increment it by 1
if(board[c]==9) //till the value of the box becomes 9, and we proceed to backtrack
{
board[c]=0; //we first zero the current box
backtrack(c); //then go to the previous box and continue to increment the previous box's value
continue;
}

if(ok(board, c, refer)) //if the passed, means the value in this box doesn't conflict with surrounding box
break; //then we out of the loop and go to next box

}//while(board[c]<10

c++;
}//while(c<9)


}//main()


void backtrack(int &c)
{
c--;

}


bool ok(int a[], int pos, int h[][5])
{
for(int i=0; i {
if(a[pos]==a[i])
return false;
}


for(int j=0; j<4; j++)
{
if(h[pos][j]==-1)
return false;
if(abs(a[pos]-a[h[pos][j]])==1)
return false;
}

return true;
}

void print(int a[]){
cout<<" "<<a[1] <<a[2] <<endl <<a[0] <<a[3] <<a[4] <<a[5] <<endl <<" " <<a[7] <<a[8] <<" " <<endl; }

Explanation / Answer

A segfault is often caused with a bad index into the array. One obvious instance of a bad index is in your print() method. The array passed - board - has length 8, but you attempt to access a[8].

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote