I have a 2D array of structures (called Element) as a gameboard that I initialize from a function. I have a seperate function that checks that the returned game board is solvable.
Element** gameBoard = createGameBoard(length, space);
while(!checkIfSolvable(gameBoard, length)){
free(gameBoard);
gameBoard = createGameBoard(length, space);
}
createGameBoard returns the 2D gameboard and fills it up, checkIfSolvable returns 1 if the game board is solvable, or 0 otherwise. I don't really know how to re initialize the game board if it isn't solvable, and this kind of logic seems to be exiting my program if it isn't. Both functions work correctly.
A user suggested I share the createGameBoard function:
Element** createGameBoard(int length, SpacePosition* space){
/*
Allocates memory for a square gameboard (length x length) , that holds
Element structures indicating the value of the square, and whether or not
that square is a space
*/
Element** temp = malloc(sizeof(Element*) * length);
for(int i = 0; i < length; i++){
temp[i] = malloc(sizeof(Element) * length);
}
/*
Array for the elements that will be fed into the 2-D array game board,
setting the values 1 - (range - 1) , and the last element will be a space.
Needs to be shuffled before it is inserted into the game board.
*/
Element* arr = malloc(sizeof(Element) * length);
int range = (length * length);
for(int i = 0; i < range - 1; i++){
arr[i].value = i + 1;
arr[i].isSpace = 0;
}
arr[range-1].value = 999;
arr[range-1].isSpace = 1;
// Shuffle the array with the range values, to be able to insert into 2D array in a random order.
shuffle(arr, range);
// Read in the shuffled array into the game board
int count = 0;
for(int i = 0; i < length; i++){
for(int j = 0; j < length; j++){
Element tempNum = arr[count];
temp[i][j] = tempNum;
count++;
if(tempNum.isSpace == 1){
space->i = i;
space->j = j;
}
}
}
return temp;
}