rand() not working properly?

I'm trying to get a board game randomly initialized with either "X" or "O". For some reason it seems that my algorithm is causing all "X" to appear on the board, when I would simply like a randomized amount of each respective letter.

Here are the function definitions (with both functions being called on back to back lines in main)...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
int initialize(int board[x][y]){
   int diff;
   cout << "Indicate whether you would like to play with 1) A board initialized with more live cells or 2) A board initialized with less live cells... (1/2): " << endl;
   cin.clear();
   cin.ignore(10000, '\n');
   cin >> diff;

   if (diff == 1){
      for(int i = 1; i < x; i++){ //globally defined x constant
	 for(int j = 1; j < x; j++){ // globally defined y constant
	    int random = (rand()%2);
	    if(random == 1){
	       board[i][j] == 1;
	 }
	    else{
	       board[i][j] == 0;
		
			}
  		}
      	}
}
   else if (diff == 2){
   	
   	for(int i = 1; i < x; i++){

	   for(int j = 1; j < x; j++){
		 int random = (rand()%4);
		 if(random == 1)
		    board[i][j] == 1;
		 else{
		    board[i][j] == 0;	   
	      		}    
		}
	 }
   }

	else {
	   cout << "What???" << endl;
	   initialize(board);
	}
	return board[x][y];
}
void print(int board[x][y]){
	for(int i = 1; i < x; i++){
	
		for(int j = 1; j < y; j++){

			if(board[i][j] == 1){
				cout << "O";
			}
			else{
				cout << "X";
				}
			}
	cout << endl;
	}
}
I recommend you turn up the warning level on your compiler. When I compile your program using g++ and passing the -Wall flag it tells me that line 13, 16, 29 and 31 has no effect. This is because you use == instead of =.

Another thing I noticed was that you use x instead of y on line 10 and 26.
Last edited on
Topic archived. No new replies allowed.