I am working on makingthis connect 4 game to be modular with different grid sizes from 3x3 up to a 10x10 as well as a modular amount of winning "pucks". The program below works by passing 3 arguments which is the grid size (grid is square), the continuous amount of pucks needed to win, and who starts first (not implemented yet). So the command to run it would be connectM 6 5 1 for example.
On the code below you will see that attempt. The program works well when you use 4 as the second argument but anything above it and I am getting a segmentation fault around line 338 and I can't put my finger on it. Does anyone have any insight on something I am obviously doing wrong?
#include <stdio.h>
#include <iostream>
#include <vector>
#include <limits.h>
#include <array>
#include <sstream>
#define min(a,b) (((a) < (b)) ? (a) : (b))
#define max(a,b) (((a) > (b)) ? (a) : (b))
using namespace std;
// function declarations
void printBoard(vector<vector<int> >&);
int userMove();
void makeMove(vector<vector<int> >&, int, unsigned int);
void errorMessage(int);
int aiMove();
vector<vector<int> > copyBoard(vector<vector<int> >);
bool winningMove(vector<vector<int> >&, unsigned int);
int scoreSet(vector<unsigned int>, unsigned int);
int tabScore(vector<vector<int> >, unsigned int);
array<int, 2> miniMax(vector<vector<int> >&, unsigned int, int, int, unsigned int);
int heurFunction(unsigned int, unsigned int, unsigned int);
// Avoid magic numbers
unsigned int NUM_COL = 7; // how wide is the board
unsigned int NUM_ROW = 7; // how tall
unsigned int PLAYER = 1; // player number
unsigned int COMPUTER = 2; // AI number
unsigned int MAX_DEPTH = 5; // the default "difficulty" of the computer controlled AI
unsigned int WINNING_PUCKS = 4; //Default winning pucks
unsigned int FIRST_PLAYER = 0;
bool gameOver = false; // flag for if game is over
unsigned int turns = 0; // count for # turns
unsigned int currentPlayer = PLAYER; // current player
vector<vector<int>> board(NUM_ROW, vector<int>(NUM_COL)); // the game board
/**
* game playing function
* loops between players while they take turns
*/
void playGame() {
printBoard(board); // print initial board
while (!gameOver) { // while no game over state
if (currentPlayer == COMPUTER) { // AI move
makeMove(board, aiMove(), COMPUTER);
}
else if (currentPlayer == PLAYER) { // player move
makeMove(board, userMove(), PLAYER);
}
else if (turns == NUM_ROW * NUM_COL) { // if max number of turns reached
gameOver = true;
}
gameOver = winningMove(board, currentPlayer); // check if player won
currentPlayer = (currentPlayer == 1) ? 2 : 1; // switch player
turns++; // iterate number of turns
cout << endl;
printBoard(board); // print board after successful move
}
if (turns == NUM_ROW * NUM_COL) { // if draw condition
cout << "Draw!" << endl;
}
else { // otherwise, someone won
cout << ((currentPlayer == PLAYER) ? "AI Wins!" : "Player Wins!") << endl;
}
}
/**
* function that makes the move for the player
* #param b - the board to make move on
* #param c - column to drop piece into
* #param p - the current player
*/
void makeMove(vector<vector<int> >& b, int c, unsigned int p) {
// start from bottom of board going up
for (unsigned int r = 0; r < NUM_ROW; r++) {
if (b[r][c] == 0) { // first available spot
b[r][c] = p; // set piece
break;
}
}
}
/**
* prompts the user for their move
* and ensures valid user input
* #return the user chosen column
*/
int userMove() {
int move = -1; // temporary
while (true) { // repeat until proper input given
cout << "Enter a column: ";
cin >> move; // init move as input
if (!cin) { // if non-integer
cin.clear();
cin.ignore(INT_MAX, '\n');
errorMessage(1); // let user know
}
else if (!((unsigned int)move < NUM_COL && move >= 0)) { // if out of bounds
errorMessage(2); // let user know
}
else if (board[NUM_ROW - 1][move] != 0) { // if full column
errorMessage(3); // let user know
}
else { // if it gets here, input valid
break;
}
cout << endl << endl;
}
return move;
}
/**
* AI "think" algorithm
* uses minimax to find ideal move
* #return - the column number for best move
*/
int aiMove() {
cout << "AI is thinking about a move..." << endl;
return miniMax(board, MAX_DEPTH, 0 - INT_MAX, INT_MAX, COMPUTER)[1];
}
/**
* Minimax implementation using alpha-beta pruning
* #param b - the board to perform MM on
* #param d - the current depth
* #param alf - alpha
* #param bet - beta
* #param p - current player
*/
array<int, 2> miniMax(vector<vector<int> > &b, unsigned int d, int alf, int bet, unsigned int p) {
/**
* if we've reached minimal depth allowed by the program
* we need to stop, so force it to return current values
* since a move will never (theoretically) get this deep,
* the column doesn't matter (-1) but we're more interested
* in the score
*
* as well, we need to take into consideration how many moves
* ie when the board is full
*/
if (d == 0 || d >= (NUM_COL * NUM_ROW) - turns) {
// get current score to return
return array<int, 2>{tabScore(b, COMPUTER), -1};
}
if (p == COMPUTER) { // if AI player
array<int, 2> moveSoFar = {INT_MIN, -1}; // since maximizing, we want lowest possible value
if (winningMove(b, PLAYER)) { // if player about to win
return moveSoFar; // force it to say it's worst possible score, so it knows to avoid move
} // otherwise, business as usual
for (unsigned int c = 0; c < NUM_COL; c++) { // for each possible move
if (b[NUM_ROW - 1][c] == 0) { // but only if that column is non-full
vector<vector<int> > newBoard = copyBoard(b); // make a copy of the board
makeMove(newBoard, c, p); // try the move
int score = miniMax(newBoard, d - 1, alf, bet, PLAYER)[0]; // find move based on that new board state
if (score > moveSoFar[0]) { // if better score, replace it, and consider that best move (for now)
moveSoFar = {score, (int)c};
}
alf = max(alf, moveSoFar[0]);
if (alf >= bet) { break; } // for pruning
}
}
return moveSoFar; // return best possible move
}
else {
array<int, 2> moveSoFar = {INT_MAX, -1}; // since PLAYER is minimized, we want moves that diminish this score
if (winningMove(b, COMPUTER)) {
return moveSoFar; // if about to win, report that move as best
}
for (unsigned int c = 0; c < NUM_COL; c++) {
if (b[NUM_ROW - 1][c] == 0) {
vector<vector<int> > newBoard = copyBoard(b);
makeMove(newBoard, c, p);
int score = miniMax(newBoard, d - 1, alf, bet, COMPUTER)[0];
if (score < moveSoFar[0]) {
moveSoFar = {score, (int)c};
}
bet = min(bet, moveSoFar[0]);
if (alf >= bet) { break; }
}
}
return moveSoFar;
}
}
/**
* function to tabulate current board "value"
* #param b - the board to evaluate
* #param p - the player to check score of
* #return - the board score
*/
int tabScore(vector<vector<int> > b, unsigned int p) {
int score = 0;
vector<unsigned int> rs(NUM_COL);
vector<unsigned int> cs(NUM_ROW);
vector<unsigned int> set(WINNING_PUCKS);
/**
* horizontal checks, we're looking for sequences of WINNING_PUCKS
* containing any combination of AI, PLAYER, and empty pieces
*/
for (unsigned int r = 0; r < NUM_ROW; r++) {
for (unsigned int c = 0; c < NUM_COL; c++) {
rs[c] = b[r][c]; // this is a distinct row alone
}
for (unsigned int c = 0; c < NUM_COL - (WINNING_PUCKS - 1); c++) {
for (int i = 0; i < WINNING_PUCKS; i++) {
set[i] = rs[c + i]; // for each possible "set" of WINNING_PUCKS spots from that row
}
score += scoreSet(set, p); // find score
}
}
// vertical
for (unsigned int c = 0; c < NUM_COL; c++) {
for (unsigned int r = 0; r < NUM_ROW; r++) {
cs[r] = b[r][c];
}
for (unsigned int r = 0; r < NUM_ROW - (WINNING_PUCKS - 1); r++) {
for (int i = 0; i < WINNING_PUCKS; i++) {
set[i] = cs[r + i];
}
score += scoreSet(set, p);
}
}
// diagonals
for (unsigned int r = 0; r < NUM_ROW - (WINNING_PUCKS - 1); r++) {
for (unsigned int c = 0; c < NUM_COL; c++) {
rs[c] = b[r][c];
}
for (unsigned int c = 0; c < NUM_COL - (WINNING_PUCKS - 1); c++) {
for (int i = 0; i < WINNING_PUCKS; i++) {
set[i] = b[r + i][c + i];
}
score += scoreSet(set, p);
}
}
for (unsigned int r = 0; r < NUM_ROW - (WINNING_PUCKS - 1); r++) {
for (unsigned int c = 0; c < NUM_COL; c++) {
rs[c] = b[r][c];
}
for (unsigned int c = 0; c < NUM_COL - (WINNING_PUCKS - 1); c++) {
for (int i = 0; i < WINNING_PUCKS; i++) {
set[i] = b[r + WINNING_PUCKS - 1 - i][c + i];
}
score += scoreSet(set, p);
}
}
return score;
}
/**
* function to find the score of a set of WINNING_PUCKS spots
* #param v - the row/column to check
* #param p - the player to check against
* #return - the score of the row/column
*/
int scoreSet(vector<unsigned int> v, unsigned int p) {
unsigned int good = 0; // points in favor of p
unsigned int bad = 0; // points against p
unsigned int empty = 0; // neutral spots
for (unsigned int i = 0; i < v.size(); i++) { // just enumerate how many of each
good += (v[i] == p) ? 1 : 0;
bad += (v[i] == PLAYER || v[i] == COMPUTER) ? 1 : 0;
empty += (v[i] == 0) ? 1 : 0;
}
// bad was calculated as (bad + good), so remove good
bad -= good;
return heurFunction(good, bad, empty);
}
/**
* """heuristic function"""
* #param g - good points
* #param b - bad points
* #param z - empty spots
* #return - the score as tabulated
*/
// int heurFunction(unsigned int g, unsigned int b, unsigned int z) {
// int score = 0;
// if (g == 4) { score += 500001; } // preference to go for winning move vs. block
// else if (g == 3 && z == 1) { score += 5000; }
// else if (g == 2 && z == 2) { score += 500; }
// else if (b == 2 && z == 2) { score -= 501; } // preference to block
// else if (b == 3 && z == 1) { score -= 5001; } // preference to block
// else if (b == 4) { score -= 500000; }
// return score;
// }
int heurFunction(unsigned int g, unsigned int b, unsigned int z) {
int score = 0;
if (g == WINNING_PUCKS) { score += 500001; } // preference to go for winning move vs. block
else if (g > z) { score += 5000; }
else if (g == z) { score += 500; }
else if (b == z) { score -= 501; } // preference to block
else if (b > z) { score -= 5001; } // preference to block
else if (b == WINNING_PUCKS) { score -= 500000; }
return score;
}
/**
* function to determine if a winning move is made
* #param b - the board to check
* #param p - the player to check against
* #return - whether that player can have a winning move
*/
bool winningMove(vector<vector<int> > &b, unsigned int p) {
unsigned int winSequence = 0; // to count adjacent pieces
// for horizontal checks
for (unsigned int c = 0; c < NUM_COL - (WINNING_PUCKS - 1); c++) { // for each column
for (unsigned int r = 0; r < NUM_ROW; r++) { // each row
for (int i = 0; i < WINNING_PUCKS; i++) { // recall you need WINNING_PUCKS to win
if ((unsigned int)b[r][c + i] == p) { // if not all pieces match
winSequence++; // add sequence count
}
if (winSequence == WINNING_PUCKS) { return true; } // if WINNING_PUCKS in row
}
winSequence = 0; // reset counter
}
}
// vertical checks
for (unsigned int c = 0; c < NUM_COL; c++) {
for (unsigned int r = 0; r < NUM_ROW - (WINNING_PUCKS - 1); r++) {
for (int i = 0; i < WINNING_PUCKS; i++) {
if ((unsigned int)b[r + i][c] == p) {
winSequence++;
}
if (winSequence == WINNING_PUCKS) { return true; }
}
winSequence = 0;
}
}
// the below two are diagonal checks
for (unsigned int c = 0; c < NUM_COL - (WINNING_PUCKS - 1); c++) {
for (unsigned int r = 3; r < NUM_ROW; r++) {
for (int i = 0; i < WINNING_PUCKS; i++) {
if ((unsigned int)b[r - i][c + i] == p) {
winSequence++;
}
if (winSequence == WINNING_PUCKS) { return true; }
}
winSequence = 0;
}
}
for (unsigned int c = 0; c < NUM_COL - (WINNING_PUCKS - 1); c++) {
for (unsigned int r = 0; r < NUM_ROW - (WINNING_PUCKS - 1); r++) {
for (int i = 0; i < WINNING_PUCKS; i++) {
if ((unsigned int)b[r + i][c + i] == p) {
winSequence++;
}
if (winSequence == WINNING_PUCKS) { return true; }
}
winSequence = 0;
}
}
return false; // otherwise no winning move
}
/**
* sets up the board to be filled with empty spaces
* also used to reset the board to this state
*/
void initBoard() {
for (unsigned int r = 0; r < NUM_ROW; r++) {
for (unsigned int c = 0; c < NUM_COL; c++) {
board[r][c] = 0; // make sure board is empty initially
}
}
}
/**
* function to copy board state to another 2D vector
* ie. make a duplicate board; used for mutating copies rather
* than the original
* #param b - the board to copy
* #return - said copy
*/
vector<vector<int> > copyBoard(vector<vector<int> > b) {
vector<vector<int>> newBoard(NUM_ROW, vector<int>(NUM_COL));
for (unsigned int r = 0; r < NUM_ROW; r++) {
for (unsigned int c = 0; c < NUM_COL; c++) {
newBoard[r][c] = b[r][c]; // just straight copy
}
}
return newBoard;
}
/**
* prints the board to console out
* #param b - the board to print
*/
void printBoard(vector<vector<int> > &b) {
for (unsigned int i = 0; i < NUM_COL; i++) {
cout << " " << i;
}
cout << endl << "---------------" << endl;
for (unsigned int r = 0; r < NUM_ROW; r++) {
for (unsigned int c = 0; c < NUM_COL; c++) {
cout << "|";
switch (b[NUM_ROW - r - 1][c]) {
case 0: cout << " "; break; // no piece
case 1: cout << "O"; break; // one player's piece
case 2: cout << "X"; break; // other player's piece
}
if (c + 1 == NUM_COL) { cout << "|"; }
}
cout << endl;
}
cout << "---------------" << endl;
cout << endl;
}
/**
* handler for displaying error messages
* #param t - the type of error to display
*/
void errorMessage(int t) {
if (t == 1) { // non-int input
cout << "Use a value 0.." << NUM_COL - 1 << endl;
}
else if (t == 2) { // out of bounds
cout << "That is not a valid column." << endl;
}
else if (t == 3) { // full column
cout << "That column is full." << endl;
}
cout << endl;
}
/**
* main driver
*/
int main(int argc, char** argv) {
// int i = -1; bool flag = false;
// if (argc == 2) {
// istringstream in(argv[1]);
// if (!(in >> i)) { flag = true; }
// if (i > (int)(NUM_ROW * NUM_COL) || i <= -1) { flag = true; }
// if (flag) { cout << "Invalid command line argument, using default depth = 5." << endl; }
// else { MAX_DEPTH = i; }
// }
if(argc <= 1){
cout << "No arguments fed. Terminating";
return 0;
}
if(argc == 4){
int gridSize = atoi(argv[1]);
int diskAmount = atoi(argv[2]);
bool firstTurn = (bool)argv[3];
if(gridSize < 3 || gridSize > 10){
cout << "Incorrect Grid size";
return 0;
}
if(diskAmount < 1 || diskAmount > gridSize){
cout << "Incorrect disk amount";
return 0;
}
NUM_COL = gridSize;
NUM_ROW = gridSize;
WINNING_PUCKS = diskAmount;
FIRST_PLAYER = firstTurn;
}
else{
cout << "Incorrect amount of arguments. Terminating";
return 0;
}
//cout << NUM_COL << endl << WINNING_PUCKS << endl << FIRST_PLAYER << endl;
initBoard(); // initial setup
playGame(); // begin the game
return 0; // exit state
}
It looks to me that you didn't change one of the hard-coded values from your earlier version of the game. On line 336, you have
for (unsigned int r = 3; r < NUM_ROW; r++) {
This is only correct when WINNING_PUCKS is set to 4. The general case should be:
for (unsigned int r = (WINNING_PUCKS - 1); r < NUM_ROW; r++) {
Note that while this part should now work correctly, when I ran it, it still crashes when an end-game is reached with the error message:
double free or corruption (out)
Aborted (core dumped)
I haven't determined what caused this yet.
Related
I have a homework where I have to write a C++ program to simulate a disease outbreak using SIR model (Susceptible, Infectious, Recover). The requirement is to use a 2D-array with 7x7 size where user will choose an X and Y coordinate to initialize an infectious person. A Susceptible person (S) will become infected (I) if there is an infected person in adjacent. Then an infected person will recover (R) if there is a Recover person in adjacent. The program will end if all people are recovered.
Example output:
Day 0 Day 1 Day 2
s s s s s s s s s s s s s s s s s s s s s
s s s s s s s s s s s s s s s i i i i i s
s s s s s s s s s i i i s s s i r r r i s
s s s i s s s s s i r i s s s i r r r i s
s s s s s s s s s i i i s s s i r r r i s
s s s s s s s s s s s s s s s i i i i i s
s s s s s s s s s s s s s s s s s s s s s
So far, I can only check the state in position (1,1), (1,7), (7,1), (7,7). If the next three position next to it have an infected person, it will update the state to nextDayState.
Here is my code so far for two functions, SpreadingDisease and RecoverState.
void recoverState(char currentDayState[SIZE][SIZE], char nextDayState[SIZE][SIZE], int sizeOfArray)//It will take in the currentState of Day 0. I also copy the elements in currentState to nextDayState so that it could work.
{
for (int i = 1; i < sizeOfArray + 1; ++i)
{
for (int j = 1; j <= sizeOfArray + 1; ++j)
{
if (currentDayState[i][j] == 'i')//If found any Infected, update it to Recover on the nextDayState array.
{
nextDayState[i][j] == 'r';
}
}
}
for (int i = 1; i < sizeOfArray + 1; ++i)
{
for (int j = 1; j <= sizeOfArray + 1; ++j)
{
currentDayState[i][j] = nextDayState[i][j];
//After all people are recover, update the currentState and output it to terminal.
}
}
}
void spreadDisease(const char currentDayState[SIZE][SIZE], char nextDayState[SIZE][SIZE], int sizeOfArray, int day = 1)
{
for (int i = 1; i < sizeOfArray + 1; ++i)
{
for (int j = 1; j <= sizeOfArray + 1; ++j)
{
if (currentDayState[i][j] == 's')
{
if (i == 1 && j == 1)
{
if (currentDayState[1][2] == 'i' || currentDayState[2][1] == 'i' || currentDayState[2][2] == 'i')
{
nextDayState[1][1] = 'i';
}
}
if (i == 1 && j == 7)
{
if (currentDayState[1][6] == 'i' || currentDayState[2][6] == 'i' || currentDayState[2][7] == 'i')
{
nextDayState[1][7] = 'i';
}
}
if (i == 7 && j == 1)
{
if (currentDayState[6][1] == 'i' || currentDayState[6][2] == 'i' || currentDayState[7][2] == 'i')
{
nextDayState[7][1] = 'i';
}
}
if (i == 7 && j == 7)
{
if (currentDayState[6][6] == 'i' || currentDayState[7][6] == 'i' || currentDayState[6][7] == 'i')
{
nextDayState[7][7] = 'i';
}
}
}
}
}
}
I figure out that If I can somehow get the X and Y coordinate from the user, then I can use that coordinate to update the state of the next day. Unfortunately, I don't know how to assign the X and Y coordinate into the function to start with it.
P/S: Thank you for all of your answers. I very appreciate your kindness. However, I should have mentioned the requirement of my assignment before. Since I only study till the User-Defined Functions part, I am not allowed to use anything else beyond that. So I am limited to use 2D-array, If-else, Looping only to solve this problem. Map and Vector is far beyond my knowledge right now xD.
This assignment remembered me to my days at the University (and that's quite long ago).
It seems like a variant of Conway's Game of Life which I got as assignment when I was first year's student. Hence, I couldn't resist...
Some notes before:
Two dimensional arrays are a bit inconvenient in C++. Either you have to use constant size or resizing them is not possible without using some kind of new[] (or g++'s VAL extension which is not standard conform). The better alternative is usually std::vector. Instead of nesting std::vectors, the two dimensions can be "faked" by appropriate operator overloads. For my luck, I had a minimal working version at hand from another recent answer of mine to Multi-threading benchmarking issues.
Concerning the simulation step i, I came to the following logic:
If patient X is
's': check all neighbours around her/him whether somebody is infected ('i'). If so, infect patient X.
'i' (infected in day before): let her/him recover ('r').
'r' (recovered): do nothing with him i.e. keep her/him recovered ('r').
Please, note that the tests of the different current cases can be done in one iteration of all rows/all columns of the board – no necessity to do this in separate functions.
The most interesting case is 's'. For patient X at [i][j], all neighbours have to be checked. These are the patients at [i + iP][j + jP] with iP in [-1, 1] and jP in [-1, 1]. Iterating over these 9 values will check the patient X itself when iP == 0 and jP == 0. This special case could be checked but I ignored it (as by the above logic) a patient cannot infect itself. This saves an extra check for iP and jP in the most inner loop which is IMHO welcome.
At closer glance, you will realize that [i + iP][j + jP] might result in invalid coordinates if i == 0 or i == number of rows - 1 or j == 0 or j == number of columns - 1. This would require a lot of additional tests to grant valid indices but I use another trick: I make the board respectively larger to provide a border around. I don't use it for writing but this provides me safe read-accesses. All I have to grant is that reading from these border cells will not tamper my simulation logic. I initialize the whole board including border cells with 's'. As border cells are never written (except in initialization) they are never infected what matches my concept.
So, this is my simulation step:
void doSimStep(const Board &board, Board &board1)
{
assert(board.getNumRows() == board1.getNumRows());
assert(board.getNumCols() == board1.getNumCols());
for (size_t i = 1, nRows = board.getNumRows() - 1; i < nRows; ++i) {
for (size_t j = 1, nCols = board.getNumCols() - 1; j < nCols; ++j) {
const char person = board[i][j];
char person1 = person;
switch (person) {
case 's': { // search for infection in neighbourhood
bool infect = false;
for (int iP = -1; !infect && iP <= 1; ++iP) {
for (int jP = -1; !infect && jP <= 1; ++jP) {
infect = board[i + iP][j + jP] == 'i';
}
}
person1 = infect ? 'i' : 's';
} break;
case 'i': // infected -> recover
// fall through
case 'r': // recovered: stable state
person1 = 'r';
break;
default: assert(false); // Wrong cell contents!
}
board1[i][j] = person1;
}
}
}
I don't get why user10522145 believes this cannot be done without recursion. (Btw., I believe the opposite: every recursion can be turned into an iteration which may accumulate or stack intermediate results.) I actually don't know where the recursion would be necessary considering that the OP already planned separate boards for current and new state (which simplifies things much).
Output of a simulation with a 9×9 board:
Init.:
s s s s s s s s s
s s s s s s s s s
s s s s s s s s s
s s s s s s s s s
s s s s s s s s s
s s s s s s s s s
s s s s s s s s s
s s s s s s s s s
s s s s s s s s s
Day 0:
s s s s s s s s s
s s s s s s s s s
s s s s s s s s s
s s s s s s s s s
s s s s i s s s s
s s s s s s s s s
s s s s s s s s s
s s s s s s s s s
s s s s s s s s s
Day 1:
s s s s s s s s s
s s s s s s s s s
s s s s s s s s s
s s s i i i s s s
s s s i r i s s s
s s s i i i s s s
s s s s s s s s s
s s s s s s s s s
s s s s s s s s s
Day 2:
s s s s s s s s s
s s s s s s s s s
s s i i i i i s s
s s i r r r i s s
s s i r r r i s s
s s i r r r i s s
s s i i i i i s s
s s s s s s s s s
s s s s s s s s s
Day 3:
s s s s s s s s s
s i i i i i i i s
s i r r r r r i s
s i r r r r r i s
s i r r r r r i s
s i r r r r r i s
s i r r r r r i s
s i i i i i i i s
s s s s s s s s s
Day 4:
i i i i i i i i i
i r r r r r r r i
i r r r r r r r i
i r r r r r r r i
i r r r r r r r i
i r r r r r r r i
i r r r r r r r i
i r r r r r r r i
i i i i i i i i i
Day 5:
r r r r r r r r r
r r r r r r r r r
r r r r r r r r r
r r r r r r r r r
r r r r r r r r r
r r r r r r r r r
r r r r r r r r r
r r r r r r r r r
r r r r r r r r r
No further progress detected on day 6.
Done.
Live Demo on coliru
And finally (spoiler alert) the complete source code:
#include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>
template <typename VALUE>
class MatrixT; // forward declaration
template <typename VALUE>
void swap(MatrixT<VALUE>&, MatrixT<VALUE>&); // proto
template <typename VALUE>
class MatrixT {
friend void swap<VALUE>(MatrixT<VALUE>&, MatrixT<VALUE>&);
public:
typedef VALUE Value;
private:
size_t _nRows, _nCols;
std::vector<Value> _values;
public:
MatrixT(size_t nRows, size_t nCols, Value value = (Value)0):
_nRows(nRows), _nCols(nCols), _values(_nRows * _nCols, value)
{ }
~MatrixT() = default;
MatrixT(const MatrixT&) = default;
MatrixT& operator=(const MatrixT&) = default;
size_t getNumCols() const { return _nCols; }
size_t getNumRows() const { return _nRows; }
const std::vector<Value>& get() const { return _values; }
Value* operator[](size_t i) { return &_values[0] + i * _nCols; }
const Value* operator[](size_t i) const { return &_values[0] + i * _nCols; }
};
template <typename VALUE>
void swap(MatrixT<VALUE> &mat1, MatrixT<VALUE> &mat2)
{
std::swap(mat1._nRows, mat2._nRows);
std::swap(mat1._nCols, mat2._nCols);
std::swap(mat1._values, mat2._values);
}
typedef MatrixT<char> Board;
bool operator==(const Board &board1, const Board &board2)
{
return board1.getNumRows() == board2.getNumRows()
&& board1.getNumCols() == board2.getNumCols()
&& board1.get() == board2.get();
}
std::ostream& operator<<(std::ostream &out, const Board &board)
{
for (size_t i = 1, nRows = board.getNumRows() - 1; i < nRows; ++i) {
for (size_t j = 1, nCols = board.getNumCols() - 1; j < nCols; ++j) {
out << ' ' << board[i][j];
}
out << '\n';
}
return out;
}
void doSimStep(const Board &board, Board &board1)
{
assert(board.getNumRows() == board1.getNumRows());
assert(board.getNumCols() == board1.getNumCols());
for (size_t i = 1, nRows = board.getNumRows() - 1; i < nRows; ++i) {
for (size_t j = 1, nCols = board.getNumCols() - 1; j < nCols; ++j) {
const char person = board[i][j];
char person1 = person;
switch (person) {
case 's': { // search for infection in neighbourhood
bool infect = false;
for (int iP = -1; !infect && iP <= 1; ++iP) {
for (int jP = -1; !infect && jP <= 1; ++jP) {
infect = board[i + iP][j + jP] == 'i';
}
}
person1 = infect ? 'i' : 's';
} break;
case 'i': // infected -> recover
// fall through
case 'r': // recovered: stable state
person1 = 'r';
break;
default: assert(false); // Wrong cell contents!
}
board1[i][j] = person1;
}
}
}
int main()
{
size_t nRows = 9, nCols = 9;
#if 0 // disabled for demo
std::cout << "N Rows: "; std::cin >> nRows;
std::cout << "N Cols: "; std::cin >> nCols;
/// #todo check nRows, nCols for sufficient values
#endif // 0
// init board
std::cout << "Init.:\n";
Board board(nRows + 2, nCols + 2);
std::fill(board[0], board[nRows + 2], 's');
std::cout << board << '\n';
// infect somebody
size_t i = nRows / 2 + 1, j = nCols / 2 + 1;
#if 0 // disabled for demo
std::cout << "Patient 0:\n";
std::cout << "row: "; std::cin >> i;
std::cout << "col: "; std::cin >> j;
/// #todo check i, j for matching the boundaries
#endif // 0
board[i][j] = 'i';
// simulation loop
for (unsigned day = 0;;) {
std::cout << "Day " << day << ":\n";
std::cout << board << '\n';
// simulate next day
++day;
Board board1(board);
doSimStep(board, board1);
if (board == board1) {
std::cout << "No further progress detected on day "
<< day << ".\n";
break; // exit sim. loop
}
// store data of new day
swap(board, board1);
}
// done
std::cout << "Done.\n";
return 0;
}
You are using C++, so use the standard library to the maximum...
The magically optimized disease simulation function:
/*
*-----------------------
* Key:
* ----------------------
* 0 - Susceptible person
* 1 - Infected person
* 2 - Recovered person
*
* #param init_infect_x Person to infect at x position...
* #param init_infect_y Person to infect at y position...
* #param map_size_x Width of the map...
* #param map_size_y Height of the map...
*/
std::vector<std::vector<std::vector<int>>> disease_simulator(size_t const init_infect_x = 0u,
size_t const init_infect_y = 0u,
size_t const map_size_x = 7u, size_t const map_size_y = 7u)
{
if (map_size_x == 0u || map_size_y == 0u || init_infect_x + 1 > map_size_x || init_infect_x + 1 < 0 || init_infect_y
+ 1 > map_size_y || init_infect_y + 1 < 0) // Well, we can't create a map which is empty...
return std::vector<std::vector<std::vector<int>>>();
std::vector<std::vector<std::vector<int>>> map_list;
std::vector<std::pair<int, int>> spread_pos;
std::vector<std::vector<int>> map(map_size_y, std::vector<int>(map_size_x, 0));
map[init_infect_y][init_infect_x] = 1;
map_list.emplace_back(map);
while (std::adjacent_find(map.begin(), map.end(), std::not_equal_to<>()) != map.end())
{
for (auto i = 0; i < signed(map.size()); i++)
for (auto j = 0; j < signed(map[i].size()); j++)
if (map[i][j] == 1)
{
map[i][j] = 2;
spread_pos.emplace_back(std::make_pair(j, i));
}
for (auto const pos : spread_pos)
{
if (pos.second - 1 >= 0 && map[pos.second - 1][pos.first] == 0) // Up...
map[pos.second - 1][pos.first] = 1;
if (pos.first - 1 >= 0 && map[pos.second][pos.first - 1] == 0) // Left...
map[pos.second][pos.first - 1] = 1;
if (pos.second - 1 >= 0 && pos.first - 1 >= 0 && map[pos.second - 1][pos.first - 1] == 0) // Up left...
map[pos.second - 1][pos.first - 1] = 1;
if (pos.second - 1 >= 0 && pos.first + 2 <= signed(map_size_x) && map[pos.second - 1][pos.first + 1] == 0)
// Up right...
map[pos.second - 1][pos.first + 1] = 1;
if (pos.second + 2 <= signed(map_size_y) && map[pos.second + 1][pos.first] == 0) // Down...
map[pos.second + 1][pos.first] = 1;
if (pos.first + 2 <= signed(map_size_x) && map[pos.second][pos.first + 1] == 0) // Right...
map[pos.second][pos.first + 1] = 1;
if (pos.second + 2 <= signed(map_size_y) && pos.first + 2 <= signed(map_size_x) && map[pos.second + 1][pos.
first + 1] == 0) // Down right...
map[pos.second + 1][pos.first + 1] = 1;
if (pos.second + 2 <= signed(map_size_y) && pos.first - 1 >= 0 && map[pos.second + 1][pos.first - 1] == 0)
// Down left...
map[pos.second + 1][pos.first - 1] = 1;
}
map_list.emplace_back(map);
spread_pos.clear();
}
return map_list;
}
What this function does is that it gives you the map of each day simultaneously, now you can just iterate over them one by one...
Note: Also, don't forget to #include <algorithm> at the beginning for std::adjacent_find()...
Example:
int main()
{
auto days_map = disease_simulator();
for (auto i = 0u; i < days_map.size(); i++)
{
std::cout << "Day " << i << ":" << std::endl;
for (auto elem2 : days_map[i])
{
for (auto elem3 : elem2)
switch (elem3)
{
case 0:
std::cout << "s ";
break;
case 1:
std::cout << "i ";
break;
case 2:
std::cout << "r ";
break;
default:
std::cout << ' ';
break;
}
std::cout << std::endl;
}
std::cout << std::endl;
}
std::cout << "All people have recovered!" << std::endl;
return 0;
}
Edit: Live on coliru (Using 9x9 arrays with center as the infect point)
Well, see if it gives your desired output...
Kind regards,
Ruks.
I guess iteration might not work in this case ill suggest you use recursion with the array boundary values as the condition to stop recursion.
Hope it made sense
I am trying to implement a simple version of Conway's Game of Life which consists of a header file and three .cpp files (two for class functions, one for main). Here I have included my header files and two class function declaration files ( the compiler is having no problem with my Main.cpp file).
Game_Of_Life.h
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
class cell{
public:
cell();
int Current_State(); // Returns state (1 or 0)
void Count_Neighbours(cell* A); // Counts the number of living cells in proximity w/o wraparound
void Set_Future(); // Determines the future value of state from # of neighbbours
void Update(); // Sets state to value of future state
void Set_Pos(unsigned int x, unsigned int y); // Sets position of cell in the array for use in counting neighbours
private:
int state;
int neighbours;
int future_state;
int pos_x;
int pos_y;
};
class cell_array{
public:
cell_array();
void Print_Array(); // Prints out the array
void Update_Array(); // Updates the entire array
void Set_Future_Array(); // Sets the value of the future array
private:
cell** A;
};
Cell_Class_Functions.cpp
#include "Game_Of_Life.h"
cell::cell(){
state = rand() % 2;
return;
}
void cell::Set_Future (){
if (state == 1){
if (neighbours < 2) future_state = 0;
else if (neighbours == 2 || neighbours == 3) future_state = 1;
else if (neighbours > 3) future_state = 0;
}
else{
if (neighbours == 3) future_state = 1;
}
return;
}
void cell::Update (){
state = future_state;
return;
}
int cell::Current_State (){
return state;
}
void cell::Set_Pos (unsigned int x, unsigned int y){
pos_x = x;
pos_y = y;
return;
}
void Count_Neighbours (cell* A){
neighbours = 0;
if (pos_x > 0) neighbours += A[pos_y * 10 + pos_x - 1].Current_State();
if (pos_x < 9) neighbours += A[pos_y * 10 + pos_x + 1].Current_State();
if (pos_y > 0) neighbours += A[(pos_y - 1) * 10 + pos_x].Current_State();
if (pos_y < 9) neighbours += A[(pos_y + 1) * 10 + pos_x].Current_State();
if (pos_x > 0 && pos_y > 0) neighbours += A[(pos_y - 1) * 10 + pos_x - 1].Current_State();
if (pos_x > 0 && pos_y < 9) neighbours += A[(pos_y + 1) * 10 + pos_x - 1].Current_State();
if (pos_x < 9 && pos_y > 0) neighbours += A[(pos_y - 1) * 10 + pos_x + 1].Current_State();
if (pos_x < 9 && pos_y < 9) neighbours += A[(pos_y + 1) * 10 + pos_x + 1].Current_State();
return;
}
Cell_Array_Class_Functions.cpp
#include "Game_Of_Life.h"
cell_array::cell_array(){
A = (cell**) malloc (sizeof(cell*)*100);
for (unsigned int r = 0; r < 10; r++){
for (unsigned int c = 0; c < 10; c++){
*A[r * 10 + c].Set_Pos(r,c);
}
}
return;
}
void cell_array::Update_Array(){
for (unsigned int r = 0; r < 10; r++){
for (unsigned int c = 0; c < 10; c++){
*A[r * 10 + c].Update();
}
}
}
void cell_array::Set_Future_Array(){
for (unsigned int r = 0; r < 10; r++){
for (unsigned int c = 0; c < 10; c++){
*A[r * 10 + c].Count_Neighbours(A);
*A[r * 10 + c].Set_Future();
}
}
return;
}
void cell_array::Print_Array(){
cout << "\n";
for (unsigned int r = 0; r < 10; r++){
for (unsigned int c = 0; c < 10; c++)cout << *A[r * 10 + c].Current_State() << " ";
cout << "\n";
}
return;
}
As far as I understand, since I included the header file with the class declarations, then I should be able to access the private members of the class through the previously declared functions in the class.
Essentially the Error Report Looks Like
Error C2065 'item' : undeclared identifier
This error appears for every private member called from the cell class.
What am I doing wrong?
Also, in your Cell_Array_Class_Functions.cpp you need to adjust your functions.
The . operator is used on objects and references.You have to deference it first to obtain a reference. That is:
(*A[r * 10 + c]).Set_Pos(r,c);
Alternatively, you can use (this is the preferred and easier to read way):
A[r * 10 + c]->Set_Pos(r,c);
The two are equivalent.
I don't see the word item anywhere in your code. However, you need to fix:
void Count_Neighbours (cell* A){ ... }
It should be:
void cell::Count_Neighbours (cell* A){ ... }
So I'm trying to make a Tetris game and I've come across something odd that I'm unsure about.
I have an array called bottom which stores the value of the lowest block - so, if there is no block in the first column, "bottom" will be 20.
If there's a square block occupying that first column, bottom would be 18. The weird thing is, when I set a breakpoint in my code to try to view the values for bottom, it says there is only one value in the array. In addition, my board, which is a 25 by 10 array, has the same problem, it only displays one dimension.
It seems the problem has to do with some kind of pointer issue, because it says (int (*)[10]) and (int *), where I think it should be a (int [25][10]) and (int [10]). I tried looking up array pointers and references, but the main thing I found was how to make an array of pointers and I'm not really quite sure how to word my searches.
If someone might know what's going wrong please let me know!
main.cpp
#include <chrono>
#include "makeboard.h"
int main() {
//declares and defines board
int board[24][10];
for (int y = 0; y < 24; y++) {
for (int x = 0; x < 10; x++) {
board[y][x] = 0;
}
}
makeboard(board);
}
tiles.h
#ifndef tiles_h
#define tiles_h
class O {
int board[24][10];
int x, y;
public:
void set_O (int[24][10], int, int);
};
void O::set_O (int board[24][10], int y, int x) {
board[y][x] = 1;
board[y][x+1] = 1;
board[y-1][x] = 1;
board[y-1][x+1] = 1;
}
class I {
int board[24][10];
int x, y, d;
public:
void set_I (int[24][10], int, int, int);
};
void I::set_I (int board[24][10], int d, int y, int x) {
if (d == 1 || d == 3) {
board[y-3][x] = 1;
board[y-2][x] = 1;
board[y-1][x] = 1;
board[y][x] = 1;
}
if (d == 2 || d == 4) {
board[y][x-1] = 1;
board[y][x] = 1;
board[y][x+1] = 1;
board[y][x+2] = 1;
}
}
class S {
int board[24][10];
int x, y, d;
public:
void set_S (int[24][10], int, int, int);
};
void S::set_S (int board[24][10], int d, int y, int x) {
if (d == 1 || d == 3) {
board[y-1][x] = 1;
board[y-1][x+1] = 1;
board[y][x] = 1;
board[y][x-1] = 1;
}
if (d == 2 || d == 4) {
board[y-2][x] = 1;
board[y-1][x] = 1;
board[y-1][x+1] = 1;
board[y][x+1] = 1;
}
}
class Z {
int board[24][10];
int x, y, d;
public:
void set_Z (int[24][10], int, int, int);
};
void Z::set_Z (int board[24][10], int d, int y, int x) {
if (d == 1 || d == 3) {
board[y][x] = 1;
board[y][x-1] = 1;
board[y+1][x] = 1;
board[y+1][x+1] = 1;
}
if (d == 2 || d == 4) {
board[y-1][x+1] = 1;
board[y][x+1] = 1;
board[y][x] = 1;
board[y+1][x] = 1;
}
}
class T {
int board[24][10];
int d, x, y;
public:
void set_T (int[24][10], int, int, int);
};
void T::set_T (int board[24][10], int d, int y, int x) {
if (d == 1 && (board[y+1][x-1] != 1 || board[y+1][x] != 1 || board[y+1][x+1] != 1)) {
board[y-1][x] = 1;
board[y][x-1] = 1;
board[y][x] = 1;
board[y][x+1] = 1;
}
if (d == 2 && (board[y+2][x] != 1 || board[y+1][x+1] != 1)) {
board[y-1][x] = 1;
board[y][x] = 1;
board[y][x+1] = 1;
board[y+1][x] = 1;
}
if (d == 3 && (board[y+1][x-1] != 1 || board[y+2][x] != 1 || board[y+1][x+1] != 1)) {
board[y][x-1] = 1;
board[y][x] = 1;
board[y][x+1] = 1;
board[y+1][x] = 1;
}
if (d == 4 && (board[y+1][x-1] != 1 || board[y+2][x] != 1)) {
board[y-1][x] = 1;
board[y][x-1] = 1;
board[y][x] = 1;
board[y+1][x] = 1;
}
}
class J {
int board[24][10];
int d, x, y;
public:
void set_J (int[24][10], int, int, int);
};
void J::set_J (int board[24][10], int d, int y, int x) {
if (d == 1) {
board[y-1][x-1] = 1;
board[y-1][x] = 1;
board[y-1][x+1] = 1;
board[y][x+1] = 1;
}
if (d == 2) {
board[y-2][x] = 1;
board[y-1][x] = 1;
board[y][x] = 1;
board[y][x-1] = 1;
}
if (d == 3) {
board[y][x-1] = 1;
board[y][x] = 1;
board[y][x+1] = 1;
board[y-1][x-1] = 1;
}
if (d == 4) {
board[y-2][x] = 1;
board[y-2][x+1] = 1;
board[y-1][x] = 1;
board[y][x] = 1;
}
}
class L {
int board[24][10];
int d, x, y;
public:
void set_L (int[24][10], int, int, int);
};
void L::set_L (int board[24][10], int d, int y, int x) {
if (d == 1) {
board[y-1][x-1] = 1;
board[y-1][x] = 1;
board[y-1][x+1] = 1;
board[y][x-1] = 1;
}
if (d == 2) {
board[y-2][x] = 1;
board[y-1][x] = 1;
board[y][x] = 1;
board[y][x-1] = 1;
}
if (d == 3) {
board[y-1][x-1] = 1;
board[y-1][x] = 1;
board[y-1][x+1] = 1;
board[y][x+1] = 1;
}
if (d == 4) {
board[y-2][x] = 1;
board[y-1][x] = 1;
board[y][x] = 1;
board[y][x+1] = 1;
}
}
#endif
makeboard.cpp
#include <iostream>
#include <limits>
#include <thread>
#include "makeboard.h"
#include "clearscreen.h"
#include "isBottom.h"
#include "isPressed.h"
#include "tiles.h"
using namespace std;
string icon[3] = { " ", " o ", " o " };
void makeboard(int board[24][10]) {
time_t srand( time(NULL) );
int block = srand % 7 ;
block = 3;
//declares pieces
O o;
I i;
S s;
Z z;
T t;
J j;
L l;
//declares and defines initial bottom
int bottom[10];
for (int i = 0; i < 10; i++) bottom[i] = 23;
//declares and defines initial block position
int y = 3;
int x = 4;
int d = 1;
while (!isBottom(board, block, y, x, d, bottom)) {
if (isPressed(0) && x > 0) {
x--;
}
if (isPressed(2) && x < 10) {
x++;
}
if (isPressed(1)) {
d += 1;
if (d == 4) {
d = 1;
}
}
//moves tile down
y++;
//clears screen
clearscreen();
//clears non set pieces
for (int i = 0; i < 24; i++) {
for (int j = 0; j < 10; j++) {
if (board[i][j] == 1) {
board[i][j] = 0;
}
}
}
//adds blocks to board
switch (block) {
case 1:
o.set_O(board, y, x);
break;
case 2:
i.set_I(board, d, y, x);
break;
case 3:
s.set_S(board, d, y, x);
break;
case 4:
z.set_Z(board, d, y, x);
break;
case 5:
t.set_T(board, d, y, x);
break;
case 6:
j.set_J(board, d, y, x);
break;
case 7:
l.set_L(board, d, y, x);
break;
}
//builds board
cout << "╔══════════════════════════════╗" << endl;
for (int i = 4; i < 24; i++) {
cout << "║";
for (int j = 0; j < 10; j++) {
cout << icon[board[i][j]] ;
}
cout << "║" << endl;
}
cout << "╚══════════════════════════════╝" << endl;
cout << " 0 1 2 3 4 5 6 7 8 9 " << endl;
//resets initial tile position
if (isBottom(board, block, y, x, d, bottom)) {
y = 2;
//block = srand % 7;
}
//ends game
if (isBottom(board, block, 3, x, d, bottom)) {
cout << "You lose!";
return;
}
//delay
this_thread::sleep_for (chrono::milliseconds(100));
}
return;
}
clearscreen.cpp
#include <unistd.h>
#include <term.h>
#include <stdlib.h>
#include "clearscreen.h"
void clearscreen()
{
if (!cur_term)
{
void *a;
int result;
setupterm( NULL, STDOUT_FILENO, &result );
a = malloc(sizeof(int) *result);
free (a);
if (result <= 0) free (a); return;
}
putp( tigetstr( "clear" ) );
}
isBottom.cpp
#include "isBottom.h"
bool isBottom(int board[24][10], int block, int y, int x, int d, int bottom[10]) {
switch (block) {
case 1:
if (y == bottom[x] || y == bottom[x+1]) {
board[y][x] = 2;
board[y][x+1] = 2;
board[y-1][x] = 2;
board[y-1][x+1] = 2;
bottom[x] -= 2;
bottom[x+1] -= 2;
return true;
}
return false;
break;
case 2:
if (d == 1 || d == 3) {
if (y == bottom[x]) {
board[y-3][x] = 2;
board[y-2][x] = 2;
board[y-1][x] = 2;
board[y][x] = 2;
bottom[x] -= 4;
return true;
}
return false;
break;
}
if (d == 2 || d == 4) {
if (y == bottom[x-1] || y == bottom[x] || y == bottom[x+1] || y == bottom[x+2]) {
board[y][x-1] = 2;
board[y][x] = 2;
board[y][x+1] = 2;
board[y][x+2] = 2;
bottom[x-1]--;
bottom[x]--;
bottom[x+1]--;
bottom[x+2]--;
return true;
}
return false;
break;
}
case 3:
if (d == 1 || d == 3) {
if (y == bottom[x-1] || y == bottom[x] || y == bottom[x+1]) {
board[y-1][x] = 2;
board[y-1][x+1] = 2;
board[y][x] = 2;
board[y][x-1] = 2;
bottom[x-1] = 23 - y;
bottom[x] -= 2;
bottom[x+1] -= 2;
return true;
break;
}
return false;
break;
}
if (d == 2 || d == 4) {
if (y == bottom[x-1] || y == bottom[x]) {
board[y-2][x] = 2;
board[y-1][x] = 2;
board[y-1][x+1] = 2;
board[y][x+1] = 2;
bottom[x-1]--;
bottom[x] -= 1;
return true;
break;
}
return false;
break;
}
/*
case 3:
s.set_S(board, d, y, x);
break;
case 4:
z.set_Z(board, d, y, x);
break;
case 5:
t.set_T(board, d, y, x);
break;
case 6:
j.set_J(board, d, y, x);
break;
case 7:
l.set_L(board, d, y, x);
break;
*/
}
return true;
}
isPressed.cpp
#include <Carbon/Carbon.h>
#include "isPressed.h"
bool isPressed( unsigned short inKeyCode )
{
unsigned char keyMap[16];
GetKeys((BigEndianUInt32*) &keyMap);
return (0 != ((keyMap[ inKeyCode >> 3] >> (inKeyCode & 7)) & 1));
}
It depends on the scope of your array. For example:
int GetBottom(int* bottom);
int GetBottom2(const int (&bottom)[20]);
int main()
{
int localArray1d[20] = {};
int localArray2d[10][25] = {};
// putting a breakpoint here will allow you to see the full dimensions of the array because this function KNOWS what the object is (e.g. a 1d and 2d array respectively)
int lastBrick = GetBottom(localArray1d);
// When the array is passed to GetBottom, it's passed just as a pointer. Although it IS an array, the function GetBottom doesn't know that. We could just as simply pass it a single int*
int n = 0;
GetBottom(&n); // here we are only passing a single int pointer. GetBottom has no idea that your object is an array, it only knows it has an int*
lastBrick = GetBottom2(localArray1d);
// GetBottom2 only takes an array of 20 elements, so inspecting the object in that function allows you to see all the elements.
return 0;
}
int GetBottom(int* bottom)
{
// Having a breakpoint here will not allow you to see all the elements in an array since this function doesn't even know bottom IS an array.
}
int GetBottom2(const int (&bottom)[20])
{
// A breakpoint here will allow you to fully inspect bottom.
}
It's a little tricky when you refer to arrays the way you do, but an array like int array[5] degrades to int* array when you branch outside the scope in which it is defined. It's because arrays are r-values and need to degrade into a reference or pointer l-value (which lacks that info about how many elements there are) to pass them around. The gotcha part here is that you can still write a function which accepts int parameter[5] and the compiler will accept it, but will silently treat it like int* parameter. The same goes for the debugger.
So depending on your debugger, there's different ways to look at all the elements through a pointer anyway. For example, with this code:
int* ptr = some_array;
... in MSVC, I can only see the first element pointed to by ptr in the watch window. However, if I know that some_array has 10 elements, I can type ptr,10 in the watch window and it'll show me all 10 elements.
Also, again this is debugger-specific, but some debuggers are conveniently programmed to show the contents of standard containers no matter what in a beautifully-readable format. So if you can use contaners like std::vector, it'll make your debugging life easier if you're using such a debugger.
I need to place numbers within a grid such that it doesn't collide with each other. This number placement should be random and can be horizontal or vertical. The numbers basically indicate the locations of the ships. So the points for the ships should be together and need to be random and should not collide.
I have tried it:
int main()
{
srand(time(NULL));
int Grid[64];
int battleShips;
bool battleShipFilled;
for(int i = 0; i < 64; i++)
Grid[i]=0;
for(int i = 1; i <= 5; i++)
{
battleShips = 1;
while(battleShips != 5)
{
int horizontal = rand()%2;
if(horizontal == 0)
{
battleShipFilled = false;
while(!battleShipFilled)
{
int row = rand()%8;
int column = rand()%8;
while(Grid[(row)*8+(column)] == 1)
{
row = rand()%8;
column = rand()%8;
}
int j = 0;
if(i == 1) j= (i+1);
else j= i;
for(int k = -j/2; k <= j/2; k++)
{
int numberOfCorrectLocation = 0;
while(numberOfCorrectLocation != j)
{
if(row+k> 0 && row+k<8)
{
if(Grid[(row+k)*8+(column)] == 1) break;
numberOfCorrectLocation++;
}
}
if(numberOfCorrectLocation !=i) break;
}
for(int k = -j/2; k <= j/2; k++)
Grid[(row+k)*8+(column)] = 1;
battleShipFilled = true;
}
battleShips++;
}
else
{
battleShipFilled = false;
while(!battleShipFilled)
{
int row = rand()%8;
int column = rand()%8;
while(Grid[(row)*8+(column)] == 1)
{
row = rand()%8;
column = rand()%8;
}
int j = 0;
if(i == 1) j= (i+1);
else j= i;
for(int k = -j/2; k <= j/2; k++)
{
int numberOfCorrectLocation = 0;
while(numberOfCorrectLocation != i)
{
if(row+k> 0 && row+k<8)
{
if(Grid[(row)*8+(column+k)] == 1) break;
numberOfCorrectLocation++;
}
}
if(numberOfCorrectLocation !=i) break;
}
for(int k = -j/2; k <= j/2; k++)
Grid[(row)*8+(column+k)] = 1;
battleShipFilled = true;
}
battleShips++;
}
}
}
}
But the code i have written is not able to generate the numbers randomly in the 8x8 grid.
Need some guidance on how to solve this. If there is any better way of doing it, please tell me...
How it should look:
What My code is doing:
Basically, I am placing 5 ships, each of different size on a grid. For each, I check whether I want to place it horizontally or vertically randomly. After that, I check whether the surrounding is filled up or not. If not, I place them there. Or I repeat the process.
Important Point: I need to use just while, for loops..
You are much better of using recursion for that problem. This will give your algorithm unwind possibility. What I mean is that you can deploy each ship and place next part at random end of the ship, then check the new placed ship part has adjacent tiles empty and progress to the next one. if it happens that its touches another ship it will due to recursive nature it will remove the placed tile and try on the other end. If the position of the ship is not valid it should place the ship in different place and start over.
I have used this solution in a word search game, where the board had to be populated with words to look for. Worked perfect.
This is a code from my word search game:
bool generate ( std::string word, BuzzLevel &level, CCPoint position, std::vector<CCPoint> &placed, CCSize lSize )
{
std::string cPiece;
if ( word.size() == 0 ) return true;
if ( !level.inBounds ( position ) ) return false;
cPiece += level.getPiece(position)->getLetter();
int l = cPiece.size();
if ( (cPiece != " ") && (word[0] != cPiece[0]) ) return false;
if ( pointInVec (position, placed) ) return false;
if ( position.x >= lSize.width || position.y >= lSize.height || position.x < 0 || position.y < 0 ) return false;
placed.push_back(position);
bool used[6];
for ( int t = 0; t < 6; t++ ) used[t] = false;
int adj;
while ( (adj = HexCoord::getRandomAdjacentUnique(used)) != -1 )
{
CCPoint nextPosition = HexCoord::getAdjacentGridPositionInDirection((eDirection) adj, position);
if ( generate ( word.substr(1, word.size()), level, nextPosition, placed, lSize ) ) return true;
}
placed.pop_back();
return false;
}
CCPoint getRandPoint ( CCSize size )
{
return CCPoint ( rand() % (int)size.width, rand() % (int)size.height);
}
void generateWholeLevel ( BuzzLevel &level,
blockInfo* info,
const CCSize &levelSize,
vector<CCLabelBMFont*> wordList
)
{
for ( vector<CCLabelBMFont*>::iterator iter = wordList.begin();
iter != wordList.end(); iter++ )
{
std::string cWord = (*iter)->getString();
// CCLog("Curront word %s", cWord.c_str() );
vector<CCPoint> wordPositions;
int iterations = 0;
while ( true )
{
iterations++;
//CCLog("iteration %i", iterations );
CCPoint cPoint = getRandPoint(levelSize);
if ( generate (cWord, level, cPoint, wordPositions, levelSize ) )
{
//Place pieces here
for ( int t = 0; t < cWord.size(); t++ )
{
level.getPiece(wordPositions[t])->addLetter(cWord[t]);
}
break;
}
if ( iterations > 1500 )
{
level.clear();
generateWholeLevel(level, info, levelSize, wordList);
return;
}
}
}
}
I might add that shaped used in the game was a honeycomb. Letter could wind in any direction, so the code above is way more complex then what you are looking for I guess, but will provide a starting point.
I will provide something more suitable when I get back home as I don't have enough time now.
I can see a potential infinite loop in your code
int j = 0;
if(i == 1) j= (i+1);
else j= i;
for(int k = -j/2; k <= j/2; k++)
{
int numberOfCorrectLocation = 0;
while(numberOfCorrectLocation != i)
{
if(row+k> 0 && row+k<8)
{
if(Grid[(row)*8+(column+k)] == 1) break;
numberOfCorrectLocation++;
}
}
if(numberOfCorrectLocation !=i) break;
}
Here, nothing prevents row from being 0, as it was assignd rand%8 earlier, and k can be assigned a negative value (since j can be positive). Once that happens nothing will end the while loop.
Also, I would recommend re-approaching this problem in a more object oriented way (or at the very least breaking up the code in main() into multiple, shorter functions). Personally I found the code a little difficult to follow.
A very quick and probably buggy example of how you could really clean your solution up and make it more flexible by using some OOP:
enum Orientation {
Horizontal,
Vertical
};
struct Ship {
Ship(unsigned l = 1, bool o = Horizontal) : length(l), orientation(o) {}
unsigned char length;
bool orientation;
};
class Grid {
public:
Grid(const unsigned w = 8, const unsigned h = 8) : _w(w), _h(h) {
grid.resize(w * h);
foreach (Ship * sp, grid) {
sp = nullptr;
}
}
bool addShip(Ship * s, unsigned x, unsigned y) {
if ((x <= _w) && (y <= _h)) { // if in valid range
if (s->orientation == Horizontal) {
if ((x + s->length) <= _w) { // if not too big
int p = 0; //check if occupied
for (int c1 = 0; c1 < s->length; ++c1) if (grid[y * _w + x + p++]) return false;
p = 0; // occupy if not
for (int c1 = 0; c1 < s->length; ++c1) grid[y * _w + x + p++] = s;
return true;
} else return false;
} else {
if ((y + s->length) <= _h) {
int p = 0; // check
for (int c1 = 0; c1 < s->length; ++c1) {
if (grid[y * _w + x + p]) return false;
p += _w;
}
p = 0; // occupy
for (int c1 = 0; c1 < s->length; ++c1) {
grid[y * _w + x + p] = s;
p += _w;
}
return true;
} else return false;
}
} else return false;
}
void drawGrid() {
for (int y = 0; y < _h; ++y) {
for (int x = 0; x < _w; ++x) {
if (grid.at(y * w + x)) cout << "|S";
else cout << "|_";
}
cout << "|" << endl;
}
cout << endl;
}
void hitXY(unsigned x, unsigned y) {
if ((x <= _w) && (y <= _h)) {
if (grid[y * _w + x]) cout << "You sunk my battleship" << endl;
else cout << "Nothing..." << endl;
}
}
private:
QVector<Ship *> grid;
unsigned _w, _h;
};
The basic idea is create a grid of arbitrary size and give it the ability to "load" ships of arbitrary length at arbitrary coordinates. You need to check if the size is not too much and if the tiles aren't already occupied, that's pretty much it, the other thing is orientation - if horizontal then increment is +1, if vertical increment is + width.
This gives flexibility to use the methods to quickly populate the grid with random data:
int main() {
Grid g(20, 20);
g.drawGrid();
unsigned shipCount = 20;
while (shipCount) {
Ship * s = new Ship(qrand() % 8 + 2, qrand() %2);
if (g.addShip(s, qrand() % 20, qrand() % 20)) --shipCount;
else delete s;
}
cout << endl;
g.drawGrid();
for (int i = 0; i < 20; ++i) g.hitXY(qrand() % 20, qrand() % 20);
}
Naturally, you can extend it further, make hit ships sink and disappear from the grid, make it possible to move ships around and flip their orientation. You can even use diagonal orientation. A lot of flexibility and potential to harness by refining an OOP based solution.
Obviously, you will put some limits in production code, as currently you can create grids of 0x0 and ships of length 0. It's just a quick example anyway. I am using Qt and therefore Qt containers, but its just the same with std containers.
I tried to rewrite your program in Java, it works as required. Feel free to ask anything that is not clearly coded. I didn't rechecked it so it may have errors of its own. It can be further optimized and cleaned but as it is past midnight around here, I would rather not do that at the moment :)
public static void main(String[] args) {
Random generator = new Random();
int Grid[][] = new int[8][8];
for (int battleShips = 0; battleShips < 5; battleShips++) {
boolean isHorizontal = generator.nextInt(2) == 0 ? true : false;
boolean battleShipFilled = false;
while (!battleShipFilled) {
// Select a random row and column for trial
int row = generator.nextInt(8);
int column = generator.nextInt(8);
while (Grid[row][column] == 1) {
row = generator.nextInt(8);
column = generator.nextInt(8);
}
int lengthOfBattleship = 0;
if (battleShips == 0) // Smallest ship should be of length 2
lengthOfBattleship = (battleShips + 2);
else // Other 4 ships has the length of 2, 3, 4 & 5
lengthOfBattleship = battleShips + 1;
int numberOfCorrectLocation = 0;
for (int k = 0; k < lengthOfBattleship; k++) {
if (isHorizontal && row + k > 0 && row + k < 8) {
if (Grid[row + k][column] == 1)
break;
} else if (!isHorizontal && column + k > 0 && column + k < 8) {
if (Grid[row][column + k] == 1)
break;
} else {
break;
}
numberOfCorrectLocation++;
}
if (numberOfCorrectLocation == lengthOfBattleship) {
for (int k = 0; k < lengthOfBattleship; k++) {
if (isHorizontal)
Grid[row + k][column] = 1;
else
Grid[row][column + k] = 1;
}
battleShipFilled = true;
}
}
}
}
Some important points.
As #Kindread said in an another answer, the code has an infinite loop condition which must be eliminated.
This algorithm will use too much resources to find a solution, it should be optimized.
Code duplications should be avoided as it will result in more maintenance cost (which might not be a problem for this specific case), and possible bugs.
Hope this answer helps...
I need some help. I'm writing a code in C++ that will ultimately take a random string passed in, and it will do a break at every point in the string, and it will count the number of colors to the right and left of the break (r, b, and w). Here's the catch, the w can be either r or b when it breaks or when the strong passes it ultimately making it a hybrid. My problem is when the break is implemented and there is a w immediately to the left or right I can't get the program to go find the fist b or r. Can anyone help me?
#include <stdio.h>
#include "P2Library.h"
void doubleNecklace(char neck[], char doubleNeck[], int size);
int findMaxBeads(char neck2[], int size);
#define SIZE 7
void main(void)
{
char necklace[SIZE];
char necklace2[2 * SIZE];
int brk;
int maxBeads;
int leftI, rightI, leftCount = 0, rightCount=0, totalCount, maxCount = 0;
char leftColor, rightColor;
initNecklace(necklace, SIZE);
doubleNecklace(necklace, necklace2, SIZE);
maxBeads = findMaxBeads(necklace2, SIZE * 2);
checkAnswer(necklace, SIZE, maxBeads);
printf("The max number of beads is %d\n", maxBeads);
}
int findMaxBeads(char neck2[], int size)
{
int brk;
int maxBeads;
int leftI, rightI, leftCount = 0, rightCount=0, totalCount, maxCount = 0;
char leftColor, rightColor;
for(brk = 0; brk < 2 * SIZE - 1; brk++)
{
leftCount = rightCount = 0;
rightI = brk;
rightColor = neck2[rightI];
if(rightI == 'w')
{
while(rightI == 'w')
{
rightI++;
}
rightColor = neck2[rightI];
}
rightI = brk;
while(neck2[rightI] == rightColor || neck2[rightI] == 'w')
{
rightCount++;
rightI++;
}
if(brk > 0)
{
leftI = brk - 1;
leftColor = neck2[leftI];
if(leftI == 'w')
{
while(leftI == 'w')
{
leftI--;
}
leftColor = neck2[leftI];
}
leftI = brk - 1;
while(leftI >= 0 && neck2[leftI] == leftColor || neck2[leftI] == 'w')
{
leftCount++;
leftI--;
}
}
totalCount = leftCount + rightCount;
if(totalCount > maxCount)
{
maxCount = totalCount;
}
}
return maxCount;
}
void doubleNecklace(char neck[], char doubleNeck[], int size)
{
int i;
for(i = 0; i < size; i++)
{
doubleNeck[i] = neck[i];
doubleNeck[i+size] = neck[i];
}
}
I didn't study the code in detail, but something is not symmetric: in the for loop, the "left" code has an if but the "right" code doesn't. Maybe you should remove that -1 in the for condition and add it as an if for the "right" code:
for(brk = 0; brk < 2 * SIZE; brk++)
{
leftCount = rightCount = 0;
if (brk < 2 * SIZE - 1)
{
rightI = brk;
rightColor = neck2[rightI];
//...
}
if(brk > 0)
{
leftI = brk - 1;
leftColor = neck2[leftI];
//...
}
//...
Just guessing, though... :-/
Maybe you should even change those < for <=.