Related
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.
The other day, I wrote a console game of Tic-Tac-Toe in c++ for my son. He wanted me to add a computer, and I ended us using the minimax algorithm for the first time. I did some quick testing, but really just gave my laptop to my son as soon as it was printing stuff, who played with it for a couple minuets. I looked over his sholder once or twice, and noticed that it wasn't playing optimally, iv'e been trying to debug it, but I can't see where it goes wrong. I tried getting rid of alpha beta prunning, but that did not change anything.
For context, on the board the computer is -1, blank is 0, and the player is 1.
Here is the minimax function:
int minimax(int board[9], int depth, int alpha, int beta, bool isMaxizimaizingPlayer)
{
bool found = false;
for (int i = 0; i < 9; i++)
{
if (board[i] == 0)
{
found = true;
}
}
if (!found)
{
return eval(board);
}
if (depth == 0 || eval(board) != 0)
{
return eval(board);
}
if (isMaxizimaizingPlayer)
{
int maxEval = -2;
for (int spot = 0; spot < 9; spot++)
{
if (board[spot] == 0)
{
board[spot] = 1;
int e = minimax(board, depth - 1, alpha, beta, false);
if (e > maxEval)
{
maxEval = e;
}
//if (beta < alpha)
//{
// break;
//}
board[spot] = 0;
}
}
return maxEval;
}
else {
int minEval = 2;
for (int spot = 0; spot < 9; spot++)
{
if (board[spot] == 0)
{
board[spot] = -1;
int e = minimax(board, depth - 1, alpha, beta, true);
if (e < minEval)
{
minEval = e;
}
//if (beta < alpha)
//{
// break;
//}
board[spot] = 0;
}
}
return minEval;
}
}
To be compleate, here is my eval function:
int eval(int board[9])
{
/*horizontial*/
for (int i = 0; i < 3; i++)
{
if (board[i * 3] == board[i * 3 + 1] && board[i * 3 + 2] == board[i * 3] && board[i * 3] != 0)
{
return board[i * 3];
}
}
/*vertical*/
for (int i = 0; i < 3; i++)
{
if (board[i] == board[i + 3] && board[i] == board[i + 6] && board[i] != 0)
{
return board[i];
}
}
/*Both diags*/
if (board[4] != 0) {
if (board[0] == board[4] && board[0] == board[8])
{
return board[4];
}
if (board[2] == board[4] && board[4] == board[6])
{
return board[4];
}
}
return 0;
}
And here is the inital call:
int spot = 0;
int minEval = 2;
for (int i = 0; i < 9; i++)
{
if (board[i] == 0)
{
board[i] = -1;
int score = minimax(board, 3, -2, 2, false);
if (score < minEval) {
minEval = score;
spot = i;
}
board[i] = 0;
}
}
std::cout << "The computer went in spot " << spot + 1 << std::endl;
board[spot] = -1;
printBoard(board);
It looks like you only call minimax with a depth of three, so the algorithm will only look up to three moves ahead, if you want optimal play you need to set the depth to > 9, so that the agent is always looking ahead to the end of the game.
I am trying to implement the Matlab function imquantize using opencv. Which opencv thresholding function I should use to implement Matlab function multithresh? Once thresholding has been done how do I label the pixels according to the threshold? Is this the right way to implement imquantize ? Are there any other function's I should include in the code?
There is an implementation based on OpenCV here, where you should probably get the idea:
cv::Mat
imquantize(const cv::Mat& in, const arma::fvec& thresholds) {
BOOST_ASSERT_MSG(cv::DataType<float>::type == in.type(), "input is not of type float");
cv::Mat index(in.size(), in.type(), cv::Scalar::all(1));
for (int i = 0; i < thresholds.size() ; i++) {
cv::Mat temp = (in > thresholds(i)) / 255;
temp.convertTo(temp, cv::DataType<float>::type);
index += temp;
}
return index;
}
Updated: thresholds are the vector of the float threshold values (uniform distributed to # of levels that you want to quantize within [0, 1]). Check the code snippet of how it is used:
const float step = 1./levels[i];
arma::fvec thresh = arma::linspace<arma::fvec>(step, 1.-step, levels[i]-1);
channels[i] = imquantize(channels[i], thresh);
I suppose you are looking for something like this
/*function imquantize
* 'inputImage' is the input image.
* 'levels' is an array of threholds
* 'quantizedImage' is the reurned image
* with quantized levels.
*/
Mat imquantize(Mat inputImage, vector<vector<int> > levels)
{
//initialise output label matrix
Mat quantizedImage(inputImage.size(), inputImage.type(), Scalar::all(1));
//Apply labels to the pixels according to the thresholds
for (int i = 0; i < inputImage.cols; i++)
{
for (int j = 0; j < inputImage.rows; j++)
{
// Check if image is grayscale or BGR
if(levels.size() == 1)
{
for (int k = 0; k < levels[0].size(); k++)
{
// if pixel < lowest threshold , then assign 0
if(inputImage.at<uchar>(j,i) <= levels[0][0])
{
quantizedImage.at<uchar>(j,i) = 0;
}
// if pixel > highest threshold , then assign 255
else if(inputImage.at<uchar>(j,i) >= levels[0][levels[0].size()-1])
{
quantizedImage.at<uchar>(j,i) = 255;
}
// Check the level borders for pixel and assign the corresponding
// upper bound quanta to the pixel
else
{
if(levels[0][k] < inputImage.at<uchar>(j,i) && inputImage.at<uchar>(j,i) <= levels[0][k+1])
{
quantizedImage.at<uchar>(j,i) = (k+1)*255/(levels[0].size());
}
}
}
}
else
{
Vec3b pair = inputImage.at<Vec3b>(j,i);
// Processing the Blue Channel
for (int k = 0; k < levels[0].size(); k++)
{
if( pair.val[0] <= levels[0][0])
{
quantizedImage.at<Vec3b>(j,i)[0] = 0;
}
else if( pair.val[0] >= levels[0][levels.size()-1])
{
quantizedImage.at<Vec3b>(j,i)[0] = 255;
}
else
{
if(levels[0][k] < pair.val[0] && pair.val[0] <= levels[0][k+1])
{
quantizedImage.at<Vec3b>(j,i)[0] = (k+1)*255/(levels[0].size());
}
}
}
// Processing the Green Channel
for (int k = 0; k < levels[1].size(); k++)
{
if( pair.val[1] <= levels[1][0])
{
quantizedImage.at<Vec3b>(j,i)[1] = 0;
}
else if( pair.val[1] >= levels[1][levels.size()-1])
{
quantizedImage.at<Vec3b>(j,i)[1] = 255;
}
else
{
if(levels[1][k] < pair.val[1] && pair.val[1] <= levels[1][k+1])
{
quantizedImage.at<Vec3b>(j,i)[1] = (k+1)*255/(levels[1].size());
}
}
}
// Processing the Red Channel
for (int k = 0; k < levels[2].size(); k++)
{
if( pair.val[2] <= levels[2][0])
{
quantizedImage.at<Vec3b>(j,i)[2] = 0;
}
else if( pair.val[2] >= levels[2][levels.size()-1])
{
quantizedImage.at<Vec3b>(j,i)[2] = 255;
}
else
{
if(levels[2][k] < pair.val[2] && pair.val[2] <= levels[2][k+1])
{
quantizedImage.at<Vec3b>(j,i)[2] = (k+1)*255/(levels[2].size());
}
}
}
}
}
}
return quantizedImage;
}
In this function the input had to be an Mat::Image and a 2D vector which can have different levels for different channels.
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 am trying to create a utility for generating palmdoc/mobipocket format ebook files, it is said that mobi uses LZ77 compression technique to compress their records, but I found that there is quite a deviation from standard LZ77, My main source of reference is Calibre ebook creator with C implementation for palmdoc
In this file, uncompress works well, but I have not been able to compress a mobi record identically similar either using other implementation or this (Calibre code doent decompress the same).
I found some differences like, (<-- my comments follow in code)
static Py_ssize_t <-- can replaced with size_t
cpalmdoc_do_compress(buffer *b, char *output) {
Py_ssize_t i = 0, j, chunk_len, dist;
unsigned int compound;
Byte c, n;
bool found;
char *head;
buffer temp;
head = output;
temp.data = (Byte *)PyMem_Malloc(sizeof(Byte)*8); temp.len = 0;
if (temp.data == NULL) return 0;
while (i < b->len) {
c = b->data[i];
//do repeats
if ( i > 10 && (b->len - i) > 10) { <-- ignores any match outside this range
found = false;
for (chunk_len = 10; chunk_len > 2; chunk_len--) {
j = cpalmdoc_rfind(b->data, i, chunk_len);
dist = i - j;
if (j < i && dist <= 2047) { <-- 2048 window size instead of 4096
found = true;
compound = (unsigned int)((dist << 3) + chunk_len-3);
*(output++) = CHAR(0x80 + (compound >> 8 ));
*(output++) = CHAR(compound & 0xFF);
i += chunk_len;
break;
}
}
if (found) continue;
}
//write single character
i++;
if (c == 32 && i < b->len) { <-- if space is encountered skip char & check for next sequence for match otherwise do this, due to this code had wrong result.
n = b->data[i];
if ( n >= 0x40 && n <= 0x7F) {
*(output++) = CHAR(n^0x80); i++; continue;
}
}
if (c == 0 || (c > 8 && c < 0x80))
*(output++) = CHAR(c);
else { // Write binary data <-- why binary data? LZ is for text encoding
j = i;
temp.data[0] = c; temp.len = 1;
while (j < b->len && temp.len < 8) {
c = b->data[j];
if (c == 0 || (c > 8 && c < 0x80)) break;
temp.data[temp.len++] = c; j++;
}
i += temp.len - 1;
*(output++) = (char)temp.len;
for (j=0; j < temp.len; j++) *(output++) = (char)temp.data[j];
}
}
PyMem_Free(temp.data);
return output - head;
}
is this implementation correct?
PalmDoc compression essentially is byte pair compression, i.e. a variant of LZ77