C Recursion segmentation fault - c

I am new to C and trying to do a maze problem where 0 and letters are passing points and 1 is a barrier.
My 2D maze array are below where the starting point is at(0,4) and every time I have to check for 4 directions (N,S,E,W), and I have also the path array (initially contains "0" as chars) where I will put the routes as "R" which is also the same size:
1111S11110
0000010001
110100010d
t001111110
0100000001
0111111101
1111111101
00000D01T1
0111110001
0000E01110
I am using recursive solution for pathfinding and in total use 3 functions which are below:
int isSafe(char Mazearray[matrixSize][matrixSize],int x,int y){
if(x >= 0 && x < matrixSize && y >= 0 && y < matrixSize && Mazearray[x][y] != '1'){
return 1;
}
return 0;
}
void MazeSolution(char Mazearray[matrixSize][matrixSize],int x,int y,char pathArray[matrixSize][matrixSize]){
if(recursiveMaze(Mazearray,x,y,pathArray) == 0){
printf("There does not exist a possible solution!!!");
}
else{
int i,j;
for (i = 0; i < matrixSize; ++i){
for (j = 0; j < matrixSize; ++j){
printf("%c",pathArray[i][j]);
}
printf("\n");
}
}
}
int recursiveMaze(char Mazearray[matrixSize][matrixSize],int x,int y,char pathArray[matrixSize][matrixSize]){
if(x == exitX && y == exitY){
pathArray[x][y] == 'E';
return 1;
}
// check if the coordinate is safe to go(not 1)
if(isSafe(Mazearray,x,y) == 1){
pathArray[x][y] == 'R';
// Move North
if(recursiveMaze(Mazearray,x-1,y,pathArray) == 1){
return 1;
}
// Move South
if(recursiveMaze(Mazearray,x+1,y,pathArray) == 1){
return 1;
}
// Move East
if(recursiveMaze(Mazearray,x,y+1,pathArray) == 1){
return 1;
}
// Move West
if(recursiveMaze(Mazearray,x-1,y-1,pathArray) == 1){
return 1;
}
pathArray[x][y] == '0';
return 0;
}
return 0;
}
When I run the MazeSolution(), the program terminates with error code 255 and segmentation fault. When I debugged the problem appears at recursiveMaze() function.
So that, starting from first if statement it does not execute and the other problem is it goes and comes back between south and north control points.

Here is a call sequence that leads to an infinite loop:
recursiveMaze(M, x, y, p)
recursiveMaze(M, x-1, y, p)
recursiveMaze(M, x-1, y, p) -> run to completion
recursiveMaze(M, x+1, y, p) -> infinite loop
It is infinite because in the second recursive call, you increment back the value that had been decremented in the first recursive call, which takes you back to the same state as the initial call.

Related

Replace a character with another character + Setting a tie game

This is for Homework
I have to create a game of TicTacToe for a project and I have two issues. Also I apologize if I'm violating a rule by having two questions within one post, If it's not allowed then I'd appreciate someone notifying me in the comments and I'll go ahead and break this into two separate posts. I'll post my code then ask my questions following the code.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
char table[3][3];
void clear_table();
void player1_move();
void player2_move();
void the_matrix(); // Like the movie
char check_three();
int main() {
srand(time(NULL));
char win;
printf("This program plays the game of Tic Tac Toe.\n");
win = ' ';
clear_table();
do {
the_matrix(); // Like the movie
player1_move();
win = check_three(); // Check win for player 1
if (win != ' ')
break;
player2_move();
win = check_three(); // Check win for player 2
}
while (win == ' ');
the_matrix(); // Shows the final move+Like the movie
if (win == 'O')
printf("Congratulations, Player 1 wins!\n");
else
printf("Congratulations, Player 1 lost!\n");
// the_matrix (); //Shows the final move+Like the movie
return 0;
}
void clear_table() {
// Creates empty spaces for the user and computer to enter stuff in
int i, j, k;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++)
// for(l = 0; k < 3; j++)
table[i][j] = ' ';
}
}
void player1_move() {
// Moves that player 1 can and can't make
int x, y, z;
printf("Player 1 enter your selection[row, col]: ");
scanf("%d, %d", &x, &y);
x--;
y--;
// z--;
if (table[x][y] != ' ') {
printf("Space already taken, please try again.\n");
player1_move();
}
else
table[x][y] = 'O'; // O goes first for some reason
}
void player2_move() {
// Needs work!!
// Call srand in the main
int a = rand() % 3;
int b = rand() % 3;
// Make it so the game would end in a tie when possible
for (a = rand() % 3; a < 3; a++) {
for (b = rand() % 3; b < 3;
b++) // For loops causing issues in randomization?
// for(c = 0; c < 3; c++)
if (table[a][b] == ' ')
break;
if (table[a][b] == ' ') // Checks the rows and columns
break;
}
if (a * b == 9)
**Kinda works ? ** {
printf("Game Over, No Player Wins\n");
exit(0);
}
else
table[a][b] = 'X';
}
void the_matrix() { // Like the movie
**Get rid of the underscores **
int m;
printf("The current state of the board:\n");
for (m = 0; m < 3; m++) {
printf("%c_ %c_ %c_\n", table[m][0], table[m][1], table[m][2]);
}
printf("\n");
}
char check_three() {
int w;
// char table[3][3];
for (w = 0; w < 3; w++) {
if (table[w][0] == table[w][2] && table[w][0] == table[w][1])
return table[w][0]; // Row Check
}
for (w = 0; w < 3; w++) {
if (table[0][w] == table[2][w] && table[0][w] == table[1][w])
return table[0][w]; // Col Check
}
if (table[0][0] == table[1][1] && table[1][1] == table[2][2])
return table[0][0];
if (table[0][2] == table[1][1] && table[1][1] == table[2][0])
return table[0][2]; // Diag Check
return ' ';
}
First Question
So my first question is with a draw game. On the player two function I have a snip of code set to determine a draw game. Initially I assumed that if the X's and O's were to multiply to 9 then that would mean that the board would be filled up then that would result in a draw game. [This is within my third function - player2_move near the end of the function] It kind of works, but sometimes the program just preemptively ends the game. It's a bit hard to test it because the computers moves are randomized and most of the times I've tried, I ended up winning accidentally. My question is what would I need to do to set up my program to essentially have a better way of determining a draw game.
Second Question
On my 4th function called the_matrix I need help with formatting. The assignment requires the format to be a little like this where if I were to enter in the coordinates 1,1 then the board would look like this:
O _ _ with the proceeding lines near the bottom to be blank. However as my program is right now, it looks like this:
O_ _ _
What I want to do is swap or replace the underscore with the user's input. Not entirely sure how to do that and any help would be appreciated.
I apologize if I violated any rules for stackoverflow by having two questions in one and I'm also sorry for this huge post.

Solve a maze backtracking

I am trying to solve a maze using backtracking in C. To solve the maze the following rules:
You begin from the position of S and need to go towards E
You can only go on '.' path
Convert all the '.' into '#' including S and E
The input consists of a m x n matrix:
Input example:
11 11
+-+-+-+-+-+
S.|...|...|
+.+.+.+-+.+
|.|.|.....|
+.+-+-+-+.+
|...|.|...|
+.+.+.+.+-+
|.|...|.|.|
+.+-+.+.+.+
|...|.....E
+-+-+-+-+-+
Expected solution :
+-+-+-+-+-+
##|...|...|
+#+.+.+-+.+
|#|.|.....|
+#+-+-+-+.+
|###|.|...|
+.+#+.+.+-+
|.|###|.|.|
+.+-+#+.+.+
|...|######
+-+-+-+-+-+
I am trying really hard to solve it but for some reason my program doesn't go back once I reached a point in the maze from where I can't go further.It just go in all the directions where it sees a '.'
My idea was to start from the position of S and using at each recursion step the old position that we were.
I will go in all the direction from the position where I am standing if the position that I am looking at is a '.' and if that point was not my old position.
I also think that I have a problem when i reach a point where it was a crossroad when I backtrack. For example:
+-+-+-+-+-+
##|...|...|
+#+.+.+-+.+
|#|.|.....|
+#+-+-+-+.+
|0##|.|...|
+.+#+.+.+-+
|.|###|.|.|
+.+-+#+.+.+
|..1|######
+-+-+-+-+-+
Imagine that I am in the position 0. And I backtracked from 1 changing back the # into '.'.How can I make a statement saying that you have 2 # possibilities to go back , yet you should stop?
My code :
#include <stdio.h>
#include <stdlib.h>
void *safeMalloc(int n) {
void *p = malloc(n);
if (p == NULL) {
printf("Error: malloc(%d) failed. Out of memory?\n", n);
exit(EXIT_FAILURE);
}
return p;
}
char ** readMatrix(int m,int n,int* startI,int* startJ,int* endI,int* endJ){
char **arr = safeMalloc(m*sizeof(char *));
int row;
for (row=0; row < m; row++) {
arr[row] = safeMalloc(n*sizeof(char));
}
int i,j;
for(i=0;i<m;i++){
for(j=0;j<m;j++){
scanf(" %c",&arr[i][j]);
if(arr[i][j]=='S'){
*startI=i;
*startJ=j;
}
if(arr[i][j]=='E'){
*endI=i;
*endJ=j;
}
}
getchar();
}
return arr;
}
void printNumber(char **arr,int m,int n){
int i,j;
for(i=0;i<m;i++){
for(j=0;j<n;j++){
printf("%c", arr[i][j]);
}
printf("\n");
}
}
void findPath(char** arr,int m,int n,int startI,int startJ,int endI,int endJ,int oldI,int oldJ){
int i=startI,j=startJ;
int stepsPossible=4;
//going up
if(i-1>=0){
if((arr[i-1][j]=='.') && ((i-1!=oldI) || (j!=oldJ))){
arr[i][j]='#';
oldI=i;
oldJ=j;
findPath(arr,m,n,i-1,j,endI,endJ,oldI,oldJ);
}else{
stepsPossible--;
}
}
//going right
if(j+1<n){
if((arr[i][j+1]=='.') && ((i!= oldI) || (j+1!=oldJ))){
arr[i][j]='#';
oldI=i;
oldJ=j;
findPath(arr,m,n,i,j+1,endI,endJ,oldI,oldJ);
}else{
stepsPossible--;
}
}
//going left
if(j-1>=0){
if((arr[i][j-1]=='.') && ((i!= oldI) || (j-1!=oldJ))){
arr[i][j]='#';
oldI=i;
oldJ=j;
findPath(arr,m,n,i,j-1,endI,endJ,oldI,oldJ);
}else{
stepsPossible--;
}
}
//going down
if(i+1<m){
if((arr[i+1][j]=='.') && ((i+1!= oldI) || (j!=oldJ))){
arr[i][j]='#';
oldI=i;
oldJ=j;
findPath(arr,m,n,i+1,j,endI,endJ,oldI,oldJ);
}else{
stepsPossible--;
}
}
//if the next block is E then we can stop.
if((arr[i-1][j]=='E') || (arr[i][j+1]=='E') || (arr[i][j-1]=='E') || (arr[i+1][j]=='E')){
if(arr[i-1][j]=='E'){
arr[i-1][j]='#';
}
if(arr[i][j+1]=='E'){
arr[i][j+1]='#';
}
if(arr[i][j-1]=='E'){
arr[i][j-1]='#';
}
if(arr[i+1][j]=='E'){
arr[i+1][j]='#';
}
return;
}
if(stepsPossible==0){
if(arr[i-1][j]=='#'){
arr[i][j]='.';
oldI=i;
oldJ=j;
findPath(arr,m,n,i-1,j,endI,endJ,oldI,oldJ);
}else{
return;
}
if(arr[i][j+1]=='#' ){
arr[i][j]='.';
oldI=i;
oldJ=j;
findPath(arr,m,n,i,j+1,endI,endJ,oldI,oldJ);
}else{
return;
}
if(arr[i][j-1]=='#' ){
arr[i][j]='.';
oldI=i;
oldJ=j;
findPath(arr,m,n,i,j-1,endI,endJ,oldI,oldJ);
}else{
return;
}
if(arr[i+1][j]=='#' ){
arr[i][j]='.';
oldI=i;
oldJ=j;
findPath(arr,m,n,i+1,j,endI,endJ,oldI,oldJ);
}else{
return;
}
}
}
int main()
{
int m,n;
scanf("%d %d",&m,&n);
int startI,startJ,endI,endJ;
char** arr;
arr=readMatrix(m,n,&startI,&startJ,&endI,&endJ);
findPath(arr,m,n,startI,startJ,endI,endJ,startI,startJ);
printNumber(arr,m,n);
return 0;
}
Make proper use of the return value, as you can utilize it to simplify your logic. Choose different return values on findPath for the error case (backtracking necessary) and the success case (end reached).
Now you can put setting the # unconditionally in the start of that function, and resetting back to . unconditionally in the end for the backtracking case.
There is no need to count possible directions either, only checking if some call returned success.
Also no need to write the boundary checks over and over again, if you just check them at the start of the function you can just pass invalid coordinates without any issues.
bool findPath(char** arr, size_t sx, size_t sy, int x, int y) {
if (x < 0 || x >= sx || y < 0 || y >= sy) return false;
if (arr[x][y] == 'E') {
are[x][y] = '#';
return true;
}
if (arr[x][y] != '.') return false;
arr[x][y] = '#';
bool success = findPath(arr, sx, sy, x-1, y) ||
findPath(arr, sx, sy, x+1, y) ||
findPath(arr, sx, sy, x, y-1) ||
findPath(arr, sx, sy, x, y+1);
if (!success) arr[x][y] = '.';
return success;
}
Implementations for backtracking algorithms usually all follow the same pattern:
Try to either trivially reject or accept the current solution.
Modify the current solution.
Try variations.
Clean up the modifications if not successful.
I would suggest to use BFS because
BFS will find the shortest solution.
DFS handles certain mazes very very poorly.
Here is short description of BFS for your case:
Find 'S' in your maze and add it into queue
While queue is not empty check get element from queue.
Replace element with "#". If element is E, you are done. Check neighbours(up, down, left right) of the element, if they are ".", then add into queue.
If queue is empty and E not found, then there is no direct path from S to E

Search of an element on a unsorted array recursively

This is an exercise that I took from an exam. It asks to write a function that receives an unsorted array v[] and a number X and the function will return 1 if X is present in v[] or 0 if X is not present in v[]. The function must be recursive and must work in this manner:
1. Compares X with the element in the middle of v[];
2. The function calls itself (recursion!!) on upper half and on the lower half of v[];
So I've written this function:
int occ(int *p,int dim,int X){
int pivot,a,b;
pivot=(dim)/2;
if(dim==0) //end of array
return 0;
if(*(p+pivot)==X) //verify if the element in the middle is X
return 1;
a=occ(p,pivot,X); //call on lower half
b=occ(p+pivot,dim-pivot,X); //call on upper half
if(a+b>=1) //if X is found return 1 else 0
return 1;
else{
return 0;
}
}
I tried to simulated it on a sheet of paper and it seems to be correct (Even though I'm not sure) then I've written it on ideone and it can't run the program!
Here is the link: https://ideone.com/ZwwpAW
Is my code actually wrong (probably!) or is it a problem related to ideone. Can someone help me? Thank you in advance!!!
The problem is with b=occ(p+pivot,dim-pivot,X); when pivot is 0. i.e. when dim is 1.
the next function call becomes occ(p,1,X); This again leads to the call occ(p,1,X); in a continuous loop.
It can be fixed by adding a condition to the call, as shown in the code below.
int occ(int *p,int dim,int X){
int pivot,a=0,b=0;
pivot=(dim)/2;
if(dim==0){
return 0;
}
if(*(p+pivot)==X)
return 1;
if (pivot != 0)
{
a=occ(p,pivot,X);
b=occ(p+pivot,dim-pivot,X);
}
if(a+b>=1)
return 1;
else{
return 0;
}
}
The implemetation is causing a stack overflow, as the recursion does not terminate if the input contains only one element. This can be fixed as follows.
int occ(int *p, int dim, int X)
{
int pivot, a, b;
pivot = (dim) / 2;
if (dim == 0)
{
return 0;
}
if (*(p + pivot) == X)
{
return 1;
}
if (dim == 1)
{
if (*(p + pivot) == X)
{
return 1;
}
else
{
return 0;
}
}
a = occ(p, pivot, X);
b = occ(p + pivot, dim - pivot, X);
if (a + b >= 1)
{
return 1;
}
else
{
return 0;
}
}
It's enought to change only this one line in the source code to avoid the endless loop with occ(p,1,X):
//if(dim==0) //end of array
if (pivot == 0)
return 0;

Find number of paths in a 2d binary array (C)

I have been asked this question during an interview, and have been struggling to find an elegant solution (in C), Problem statement:
You are given a two-dimensional array with M rows and N columns.
You are initially positioned at (0,0) which is the top-left cell in
the array.
You are allowed to move either right or downwards.
The array is filled with 1′s and 0′s. A 1 indicates that you can move
through that cell, a 0 indicates that you cannot move through the
cell.
Write a function in C ‘numberOfPaths’ which takes in the above two dimensional array, return the number of valid paths from the top-left cell to the bottom-right cell (i.e. [0,0] to [M-1,N-1]).
Edit: forgot to mention that the requirement is for a recursive solution
help would be greatly appreciated!
Thanks
If you are looking for a recursive solution you can use DFS.
DFS (array, x, y)
{
if (array [x][y]==0 || x>M || y>N){
return;
}
if (x==M && y==N){
count++;
return;
}
DFS (array, x, y+1);
DFS (array, x+1, y);
}
The number of paths to a given point is just the number of paths to the point above, plus the number of paths to the point to the left. So, the pseudo-code would roughly be:
num_paths[0][0] = 1;
for (x = 0; x < M; ++x)
for (y = 0; y < N; ++y)
if (!allowed_through[x][y])
num_paths[x][y] = 0;
else
num_paths[x][y] = num_paths[x-1][y] + num_paths[x][y-1];
You need special cases for x=0 and y=0, but otherwise, I think that should do.
#include <stdio.h>
int count=0;
int maxrows = 10;
int maxcols = 10;
int M, N;
void DFS (int array[][10], int x, int y)
{
int r, c;
/* process element at input row and column */
if (array [x][y]==0 || x>M || y>N){
/* no path forward; return */
return;
}
if (x==M-1 && y==N-1){
/* found path; increment count */
count++;
return;
}
/* recurse: to matrix starting from same row, next column */
r = x;
c = y +1;
if (c < N-1) {
DFS (array, r,c);
} else {
/* if last column - check to see */
/* if rest of rows in last column allow for a path */
int tr = r;
while ( tr <= M-1) {
if (array[tr][c] == 1) {
tr++;
}
else {
return;
}
}
/* reached last node - path exists! */
count++;
}
/* recurse: to matrix starting from next row, same column */
r = x+1;
c = y;
if (r < M-1) {
DFS (array, r,c);
} else {
/* if last row - check to see */
/* if rest of columns in last row allow for a path */
int tc = c;
while ( tc <= N-1) {
if (array[r][tc] == 1) {
tc++;
} else {
return;
}
}
/* reached last node - path exists! */
count++;
}
}
int main () {
int i, j;
scanf("%d %d",&M,&N);
int a[10][10] = {};
int row, col;
for(i=0;i<M;i++)
for(j=0;j<N;j++)
scanf("%d", &a[i][j]);
if ((M > maxrows) || (N > maxcols)) {
printf("max of 10 rows and 10 cols allowed for input\n");
return (-1);
};
/* print input matrix */
for(row=0;row<M;row++) {
for(col=0;col<N;col++){
printf("%d ",a[row][col]);
}
printf(" EOR\n");
}
DFS(a,0,0);
printf("number of paths is %d\n", count);
return 0;
}
Try this function its a preliminary step before printing all the paths.
If the size of the vector Out is 0 then the # of paths are 0, but if size(Out) > 0 then the size of vector Nodes + 1 are the total number of paths from top left to bottom right.
#include <iostream>
#include <vector>
using namespace std;
typedef vector<pair<int,int> > vPii;
bool pathTL2BR( int Arr2D[][4], vPii &Out, vPii &Nodes,
int _x,int _y, int _M, int _N)
{
bool out1 = false;
bool out2 = false;
if( Arr2D[_x][_y] == 1 )
{
if( _y+1 < _N )
out1 = pathTL2BR( Arr2D, Out, Nodes, _x, _y+1, _M, _N);
if( _x+1 < _M )
out2 = pathTL2BR( Arr2D, Out, Nodes, _x+1, _y, _M, _N);
if( (out1 || out2) ||
( (_x == (_M-1)) && (_y == (_N-1)) ) )
{
if(out1 && out2)
Nodes.push_back( make_pair(_x,_y ) );
Out.push_back( make_pair(_x,_y ) );
return true;
}
else
return false;
}
else
return false;
}
// Driver program to test above function
int main()
{
int Arr2D[][4] = {
{1,1,1,1},
{0,1,0,1},
{0,1,0,1},
{0,1,0,1}
};
vPii Out;
vPii Nodes;
vector<vPii> Output;
pathTL2BR( Arr2D, Out, Nodes, 0, 0, 4, 4);
return 0;
}
This is a python solution, I have put explanations in the comments.
def find_num_paths(arr_2D, i, j):
# i,j is the start point and you have to travel all the way back to 0,0
if i == j and i == 0:
return 1 # you have reached the start point
if i < 0 or j < 0 or arr_2D[i][j] == 0: # out of range or no path from that point
return 0
if arr_2D[i][j] == 1:
return find_num_paths(arr_2D, i, j-1) + find_num_paths(arr_2D, i-1, j) + find_num_paths(arr_2D, i-1, j-1) # you could go one step above, to the left or diagonally up.

Saving Data in a Basic Tic-Tac-Toe Game

I'm relatively new to C. In Kochan's "Programming in C" I'm currently on if-else statements. I'm trying to program a basic tic-tac-toe game but I've run into some difficulty. I'm not sure how to save the board once a player has placed an x or an o. Here's the code I have so far:
#include <stdio.h>
int main (void)
{
int board = "_|_|_\n
_|_|_\n
| | \n";
int player1, player2;
printf ("Print %i", board)
printf("Player 1, it's your move:")
scanf("%i", player1)
if(player1 == "upLeft")
printf("x|_|_\n
_|_|_\n
_|_|_\n
etc.
Am I still too much of a beginner to implement this feature?
First of all, this doesn't make sense:
int board = "_|_|_\n
_|_|_\n
| | \n";
An int is not a string, and you can't assign a string to an int. In C, strings are arrays of characters:
char board[] = "_|_|_\n_|_|_\n | | \n";
That makes more sense. But it's really not a good way to store the state of a tic tac toe board. What you should do instead is store some value for each position on the board. Don't worry about the actual format of the board, you can format it as you like when you display it. So store your board this way:
char board[9] = "---------";
where a "-" means the space is empty. When the player moves, you replace the character at the appropriate position in the array with an "X" or an "O" (or 1 and 2, or any other values that work for you). When you get some input from the user, you'll change just the corresponding value in the board array. If you number the positions 0-8 starting from the top left corner, the rightmost position in the middle row would be position 5, for example. (Remember, C arrays are zero-based, so the first index is 0.) So if the user wants to put an X at that spot, you'd say:
board[5] = 'X';
Next, you might want to write a function that prints the board. That is where you'll insert whatever characters you like to draw the board.
Finally, you're going to want to use some sort of loop to repeatedly read the user's input, modify the state of the board, print the board, and maybe display a prompt.
First-things-first, you cannot store
"_|_|_\n
_|_|_\n
| | \n";
in an integer variable. You need variables of other types (like char *, char a[][], etc).
OTOH, the pseudocode is as follows. Please try and follow this to write a C program on your own.
Let row = 3 and column = 3
Declare an array[row][column] and fill it all with 0
Let 1 represent the input of user-1 and 2 represent the input of user-2 (in the array)
i.e. if a[2][2] = 1 means, user-1 marked that location.
while ( ! all_locations_filled() ) {
take input from user-1
if user-1 chooses a valid_location(location) to mark, then mark_location(user-1, location)
check if user-1 won_the_game(user-1), if so break and congratulate user-1!
take input from user-2
if user-2 chooses a valid_location(location) to mark, then mark_location(user-2, location)
check if user-2 won_the_game(user-2), if so break and congratulate user-2!
}
valid_location(location l)
{
return array[l.row][l.column] == 0;
}
mark_location(user u, location l)
{
array[l.row][l.column] = (u==user-1) ? 1 : 2;
}
display_board()
{
for i=0 to row
for j=0 to col
if array[i][j] == 0 print ""
else print array[i][j]
/* print blank when that location is not yet marked */
}
all_locations_filled()
{
for i=0 to row
for j=0 to col
if array[i][j] == 0
return false
return true
}
won_the_game(user u)
{
/* You need to write the logic here */
:P
}
You can use a 2d array to represent the board, and maybe some small int, with 0 as nothing there, 1 as X and 2 as 0.
You cant save the like that
int board = "X|_|_\n
_|_|_\n
| | \n";
you can have something like board[0][0]=1;
then you can iterate that array and if its 1 print the X.
It's a bit of a beginner question, but you're a beginner, so that's okay! Let's go with some leading questions:
So, you're saying you want to save the board state. What do you want to save? At any point in the program, what do you want to be able to look up? The history of the moves? What the board looks like? What each corner contains? Each of these suggests a different way to change a variable when you get some input from the user.
As other people have said, you can't do all those things with int type, and even if you could, this program is still way too hard and frustrating until you have a few more tools in your toolbox. Chapter 7 is Arrays, which will be very useful, and Chapter 10 is Character Strings, which will show you how to deal with all these strings the right way in C. So my suggestion to you is go through a few more chapters of the book and the big picture will start to make a bit more sense. Happy hacking!
Here is a small template like thing I have given write your own logic inside the GetBestMove() function for the computers move (if you are building AI) else replace the call for the GetBestMove by GetMove function in the StartGame function
#include<stdio.h>
#define HUMAN_WIN 1
#define DRAW 0
#define HUMAN_LOSE -1
#define HUMAN_COIN 'X'
#define COMP_COIN 'O'
#define DEFAULT 0xFFF
int main(void)
{
StartGame();
}
enum turnOf{ Human = 0, Computer};
enum gameEndState{Lose = -1, Draw, Win};
int humanMove = 1;
int computerMove = 1;
char _board[3][3] = {'-', '-', '-', '-', '-', '-', '-', '-', '-'};
void StartGame()
{
enum turnOf turn = 0;
enum gameEndState state = -2;
while(1)
{
turn = 1 - turn;
if(turn == Human)
{
GetMove();
UpdateBoard(humanMove, turn);
}
else if(turn == Computer)
{
GetBestMove(turn);
UpdateBoard(computerMove, turn, _board);
}
state = win(_board);
switch(state)
{
case Win:
NotifyUser("You win.");exit(0);
case Draw:
NotifyUser("Match draw.");exit(0);
case Lose:
NotifyUser("You Lose.");exit(0);
}
}
}
int depth = 0;
int GetBestMove(enum turnOf turn, int *x, int *y)
{
depth++;
int i, j, MOV = -10, BESTMOVx, BESTMOVy;
enum turnOf now = turn;
char pebble = (now == Human) ? HUMAN_COIN : COMP_COIN;
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
if(_board[i][j] == '-')
{
_board[i][j] = pebble;
now = 1 - now;
int condition = win(_board);
if(condition != DRAW || condition != DEFAULT)
{
return (condition == HUMAN_LOSE) ? (depth - 10) : (10 - depth);
}
else
{
int state = GetBestMove(now, BESTMOVx, BESTMOVy);
if(state > MOV)
{
MOV = state;
}
}
}
}
}
}
int win(char a[3][3])
{
char pebble = HUMAN_COIN;
int i, j, p = 0;
i=0;
for(j = 0; j < 3; j++)
if(a[i][j] == pebble && a[i+1][j] == pebble && a[i+2][j] == pebble) return HUMAN_WIN;
j=0;
for(i = 0; i < 3; i++)
if(a[i][j] == pebble && a[i][j+1] == pebble && a[i][j+2] == pebble) return HUMAN_WIN;
if(a[0][0] == pebble && a[1][1] == pebble && a[2][2] == pebble) return HUMAN_WIN;
else if(a[0][2] == pebble && a[1][1] == pebble && a[2][0] == pebble) return HUMAN_WIN;
/// Recheck for lose
pebble = COMP_COIN;
i=0;
for(j = 0; j < 3; j++)
if(a[i][j] == pebble && a[i+1][j] == pebble && a[i+2][j] == pebble) return HUMAN_LOSE;
j=0;
for(i = 0; i < 3; i++)
if(a[i][j] == pebble && a[i][j+1] == pebble && a[i][j+2] == pebble) return HUMAN_LOSE;
if(a[0][0] == pebble && a[1][1] == pebble && a[2][2] == pebble) return HUMAN_LOSE;
else if(a[0][2] == pebble && a[1][1] == pebble && a[2][0] == pebble) return HUMAN_LOSE;
for(i = 0; i < 3; i++)
for(j = 0; j < 3; j++)
if(a[i][j] == '-') p++;
if(p == 0) return DRAW;
return DEFAULT;
}
void GetMove()
{
int x, y;
LoadFrame(_board);
printf("\nEnter your move : ");
humanMove = getche() - 48;
if(!(humanMove > 0 && humanMove < 10))
{
NotifyUser("Enter a valid location.");
GetMove();
}
GetCordinates(&x, &y, humanMove);
if(_board[x][y] != '-')
{
NotifyUser("The place is nonEmpty.");
GetMove();
}
}
void UpdateBoard(int move, enum turnOf player, char board[3][3])
{
int x, y;
char pebble = (player == Human) ? HUMAN_COIN : COMP_COIN;
GetCordinates(&x, &y, move);
board[x][y] = pebble;
LoadFrame(board);
}
void LoadFrame(char board[3][3])
{
int x, y;
system("cls");
for(x = 0; x < 3; x++)
{
printf("\n\t ");
for(y = 0; y < 3; y++)
{
printf(" %c ", board[x][y]);
}
}
}
void GetCordinates(int *x, int *y, int move)
{
switch(move)
{
case 1: *x = 0; *y = 0; break;
case 2: *x = 0; *y = 1; break;
case 3: *x = 0; *y = 2; break;
case 4: *x = 1; *y = 0; break;
case 5: *x = 1; *y = 1; break;
case 6: *x = 1; *y = 2; break;
case 7: *x = 2; *y = 0; break;
case 8: *x = 2; *y = 1; break;
case 9: *x = 2; *y = 2; break;
}
}
void NotifyUser(const char* message)
{
printf("\n\n%s\a", message);
getch();
system("cls");
LoadFrame(_board);
}

Resources