I know my code is extremely close I have all of my functions working except the moveKnight() function if you do not know what knights Tour is, it's a program we are writing to help learn recursion in class. The knight is suppose to touch every space on the 8*8 chessboard only once and then prints out the move number that it took to get there. It currently only prints out the first position board[0][0]=1
but does not give "No solution".
I can not figure out where I should start looking for the problem any help is greatly appreciated.
#include <iostream>
using namespace std;
//Global Variables
//Defining the 8 possible Moves in the order from class
int yMove[8] = { 1,2, 2, 1,-1,-2,-2,-1 };
int xMove[8] = { 2,1,-1,-2,-2,-1, 1, 2 };
int board[8][8];
int startx, starty = 0;
int movecount = 1;
//checks if move is safe
bool checkSafe(int x, int y)
{
return (x >= 0 && x < 8 && y >= 0 && y < 8 && board[x][y] == 0);
}
//Prints Current board
void printBoard(int board[8][8])
{
for (int x = 0; x < 8; x++)
{
for (int y = 0; y < 8; y++)
cout << " " << board[x][y] << " ";
cout << endl;
}
}
bool moveKnight(int x, int y, int movecount)
{
if (!checkSafe(x, y))
{
board[x][y] = movecount;
return true;
}
//end condition
if (movecount == 64)
return true;
if (moveKnight(x + xMove[1], y + yMove[1], movecount + 1))
return true;
else if (moveKnight(x + xMove[0], y + yMove[0], movecount + 1))
return true;
else if (moveKnight(x + xMove[2], y + yMove[2], movecount + 1))
return true;
else if (moveKnight(x + xMove[3], y + yMove[3], movecount + 1))
return true;
else if (moveKnight(x + xMove[4], y + yMove[4], movecount + 1))
return true;
else if (moveKnight(x + xMove[5], y + yMove[5], movecount + 1))
return true;
else if (moveKnight(x + xMove[6], y + yMove[6], movecount + 1))
return true;
else if (moveKnight(x + xMove[7], y + yMove[7], movecount + 1))
return true;
else
{
board[x][y] = 0;
return false;
}
}
int KnightTour()
{
//creating board
for (int x = 0; x < 8; x++)
{
for (int y = 0; y < 8; y++)
board[x][y] = 0;
}
board[startx][starty] = 1;
movecount + 1;
//No possible moves
if (!moveKnight(startx, starty, movecount))
cout << "Not possible";
else
{
//yes possible now print
printBoard(board);
}
//exits
return 0;
}
int main()
{
//calls knights tour
KnightTour();
cout << endl;
system("pause");
return 0;
}
Your moveKnight function returns immediately because it determines the very first position is not a valid move. The reason is you initialized the board with a non-zero value at the start position.
Remove these two lines from main:
board[startx][starty] = 1;
movecount + 1;
The first one breaks your recursion, and the second one does nothing at all.
Additionally, the logic after calling checkSafe() is screwy, because at the moment when you determine a move is either out-of-bounds or already-played, you are writing a value to the board. That's going to result in undefined behavior.
Correcting these things, and also simplifying the recursive calls:
bool moveKnight(int x, int y, int movecount)
{
if (checkSafe(x, y))
{
board[x][y] = movecount;
if (movecount == 64)
return true;
for (int i = 0; i < 8; i++)
{
if (moveKnight(x + xMove[i], y + yMove[i], movecount + 1))
return true;
}
board[x][y] = 0;
}
return false;
}
Related
Given two int I want to get all the common digits and print out them separated by spaces.
So for example, if int x=1234; int y=41567; then I want to print out: 1 4.
This is my code. It does not work properly. When I run it, it prints 0 1 2 3 4 5 then stops.
I don't want to use vector nor arrays.
void problema3() {
int x, y, kX=0, kY=0;
cout << "x="; cin >> x;
cout << "y="; cin >> y;
int cx = x;
int cy = y;
for (int i = 0; i < 10; i++) {
kX = 0;
kY = 0;
x = cx;
y = cx;
while (x != 0 || kX==0) {
if (x % 10 == i) kX=1;
x /= 10;
}
while (y != 0 || kY == 0) {
if (y % 10 == i) kY=1;
y /= 10;
}
if (kX == 1 && kY == 1) cout << i << ' ';
}
}
int main()
{
problema3();
return 0;
}
If you're allowed to use std::set then you can do what you want as follows:
#include <iostream>
#include <set>
void print(int x, int y)
{
int individual_number1 = 0, individual_number2 = 0;
std::set<int> myset;
int savey = y;//this will be used to reset y when the 2nd do while loop finishes
do
{
individual_number1 = x % 10;
do
{
individual_number2 = y % 10;
if(individual_number1 == individual_number2)
{
myset.insert(individual_number1);
break;
}
y = y / 10;
}while( y > 0);
y = savey;
x = x / 10;
} while (x > 0);
//print out the element of the set
for(int i: myset)
{
std::cout<<i<<" ";
}
}
int main()
{
int x = 1234, y = 41567;
print(x, y);
return 0;
}
The output of the above program is as follows:
1 4
which can be seen here.
Your main bug is when assigning copies of cy.
//...
for (int i = 0; i < 10; i++) {
//...
x = cx;
y = cx; // <-- BUG! should read y = cy;
But that's not the only bug in your program.
Your digit detection logic is wrong. In particular, zero is not handled correctly, and since you did not put that reusable code in a function, your program is way more complex than it needs.
Here's the corrected logic for digit detection.
// checks if base 10 representation of a positive integer contains a certain digit (0-9)
bool hasDigit(int x, int d)
{
do
{
if (x % 10 == d)
return true;
x /= 10;
} while (x != 0);
return false;
}
Your main loop then becomes:
// assuming int x, y as inputs.
// ...
for (int i = 0; i < 10; ++i)
{
if (hasDigit(x, i) && hasDigit(y, i))
std::cout << i << ' ';
}
Which leaves very little room for bugs.
You can play with the code here: https://godbolt.org/z/5c5brEcEq
I've been trying to make my vector calculator subtract. It was doing it fine with vectors that store the same amount of numbers, for example: (+) 503 - (-) 305. It would give me a good result on this kind of cases.
But when I tried subtracting different size vectors the problems appeared. I tried to solve the problem by making different filters to make the program act how I want it. But now, instead of subtracting all it does is add.
This is my setup:
const int MAX = 102;
typedef int vector[MAX];
A(0): Puts all the values of a vector at 0. For example:
Before using it:
[0][3][5][0][5]
Where the first 0 means it is a positive number, if it was [1] it would mean its negative, that [3] means that there are 3 numbers stored in the vector.
After using A0:
[0][1][0][0][0][0][0]...[0]
ES_MAJOR_VECTOR checks if vector Z > X. On that case returns true, else it's going to return false.
SUMA_VEC basically adds Z to X and then assings the value to W.
void RESTA_VEC(vector Z, vector X, vector W) {
int ZigualX(0), Xmes1(0), Xactual(0), ZmajorX(0), XmajorZ(0), contador(0);
vector copia_Z, copia_X;
A0(copia_Z);
A0(copia_X);
for (int k = 0; k < MAX; k++)
{
copia_Z[k] = Z[k];
copia_X[k] = X[k];
}
if (Z[0] == X[0])
{
if (Z[0] == 0)
{
for (int y = MAX; y >= 2; y--)
{
if (Z[y] < X[y])
{//RESTA
Z[y] = Z[y] + 10;
W[y] = Z[y] - X[y];
X[y + 1] = X[y + 1] + 1;
}
if (Z[y] > X[y])
{
W[y] = Z[y] - X[y];
}
if (Z[y] == X[y])
{
W[y] = 0;
}
}
}
if (Z[0] == 1)
{
SUMA_VEC(Z, X, W);
}
}
if (Z[0] != X[0])
{
if (ES_MAJOR_VECTOR(Z, X) == true)
{
for (int y = MAX; y >= 2; y--)
{
if (Z[y] < X[y])
{
Z[y] = Z[y] + 10;
W[y] = Z[y] - X[y];
X[y + 1] = X[y + 1] + 1;
}
if (Z[y] > X[y])
{
W[y] = Z[y] - X[y];
}
if (Z[y] == X[y])
{
W[y] = 0;
}
}
}
else
{
for (int y = MAX; y >= 2; y--)
{
if (X[y] < Z[y])
{
X[y] = X[y] + 10;
W[y] = X[y] - Z[y];
Z[y + 1] = Z[y + 1] + 1;
}
if (X[y] > Z[y])
{
W[y] = X[y] - Z[y];
}
if (X[y] == Z[y])
{
W[y] = 0;
}
}
}
}
for (int h = 0; h < MAX; h++)
{
Z[h] = copia_Z[h];
X[h] = copia_X[h];
}
}
How can I solve this? I've thought that I need to check: If they are positive or negative, if they're both positive I have to execute a subtraction, if they're negative I have to add Z to X and assign it to W.
If the vectors are different (Meaning one is positive and the another one is negative) I have to check which one is bigger, do the subtraction and then assign either 0 or 1 depending on the bigger vector of the two used earlier.
For example:
+5050
-305
W[0] = +
-5050
+305
W[0] = -
After getting helped by a very kind user I could get to this conclusion:
void RESTA_ABS(vector Z, vector X, vector W) {
int error(0);
A0(W);
if (ES_MAJOR_VECTOR(Z,X))
{
for (int i = MAX-1; i >= 2; i--)
{
if (Z[i] < X[i]) {
Z[i] = Z[i] + 10;
W[i] = Z[i] - X[i];
X[i - 1] = X[i - 1] + 1;
}
else
{
W[i] = Z[i] - X[i];
}
}
}
else
{
cout << "ERROR - VECTOR 2 > VECTOR 1" << endl;
}
}
This module doesn't mind about the vector being positive or negative. It just does the subtraction.
So, to solve this, I used another module:
void RESTA_VEC(vector Z, vector X, vector W) {
if (X[0] == 0)
{
X[0] = 1;
}
else
{
X[0] = 0;
}
RESTA_ABS(Z, X, W);
if (ES_MAJOR_VECTOR(Z, X) == true)
{
W[0] = Z[0];
}
else
{
W[0] = X[0];
}
}
This one changes the number's sign of the second vector, making it negative if its positive, and positive if its negative. (This is determined by having a 0 or a 1 on the first vector position).
And then finally, what it does is to check the sign of the greater vector and assign it to the output vector W.
The only part left is checking which of the two vectors is greaters, because as I was testing it, on some cases, it would give me a wrong answer.
For example:
[+][9][1][2][3][4][5][6][7][8][9]
[+][9][1][1][2][3][4][5][6][7][8]
Would give:
[+][8][1][1][1][1][1][1][1][1]
But it doesn't make the opperation cause it thinks that the second vector is greater.
Translation: Is Z greater than X?
bool ES_MAJOR_VECTOR_SIGNE(vector Z, vector X) {
int END(0), UP(2);
return false;
if (Z[1] > X[1])
{
return true;
}
else
{
while (END != 1)
{
if (Z[UP] > X[UP])
{
return true;
END = 1;
}
UP++;
}
}
}
I working on my project this project have a frame to [100] x [25] matrix and i try to add animation but my character is going left but it's not going right.
i tried with "counter" variable but its not work.
int counter = 1;
int counter2 = 1;
int left_border = 1;
int matris1 = sizeof(map)/100;
int matris2 = sizeof(map[0])/4;
int startx = 19;
int starty = 8;
while (true)
...
int right = 0, left = 0;
...
for (int a = 0; a < matris2; a++)
cout << "\n#"; //i have this because i make it square map.
for (int k = 0; k < matris1 - 2; k++)
{
if (left == 1)
{
if (((startx+2)-counter) == left_border)
{
counter = 0;
//cout << "SINIR!!"<< endl ;
}
if (k == (startx-counter) and a == starty)
{
counter += 1;
cout << "O";
}
else {
cout << " ";
}
}
else if (right == 1)
{
if (k == (startx+counter2) and a == starty)
{
counter2 += 1;
cout << "O";
}
its need to be going right but its not.
if you need full code.
https://codeshare.io/UbKVU
[![This is the map and "O" is the character]
https://i.stack.imgur.com/uyGQo.png
The code is very difficult to follow - you should have a coordinate system. I've made a simple example below. Update the player coordinate when a key is pressed and redraw the map x by y position, if the player is there then draw the 'O', otherwise if its a wall draw an 'X' (in this case), otherwise draw a space ' '.
using namespace std;
#include <iostream>
#include <conio.h>
#include <stdlib.h>
#define MAPW 15 // map width
#define MAPH 15 // map height
int map[MAPW][MAPH];
#define WALL 1
#define EMPTY 0
void initmap()
{
// just set the map to have walls around the border
for (int x = 0; x < MAPW; x++)
{
for (int y = 0; y < MAPH; y++)
{
if (x == 0 || y == 0 || x == (MAPW - 1) || y == (MAPH - 1))
map[x][y] = WALL;
else
map[x][y] = EMPTY;
}
}
}
int px = MAPW / 2; // player x
int py = MAPH / 2; // player y
void main()
{
initmap(); // initialize map
cout << "Press A/W/S/D to begin and move";
while (1)
{
if (kbhit()) // key pressed?
{
switch (getch()) // which key?
{
case 'a':
if (px > 0 && map[px - 1][py] != WALL) // can go left?
px--; // update x coordinate
break;
case 'd':
if (px < (MAPW-1) && map[px + 1][py] != WALL) // can go right?
px++; // update x coordinate
break;
case 'w':
if (py > 0 && map[px][py - 1] != WALL) // can go up?
py--; // update y coordinate
break;
case 's':
if (py < MAPH && map[px][py + 1] != WALL) // can go down?
py++; // update y coordinate
break;
}
// update map - clear screen and redraw
system("CLS");
// draw map each line
for (int y = 0; y < MAPH; y++)
{
for (int x = 0; x < MAPW; x++)
{
// its a wall?
if (map[x][y] == WALL)
cout << "X";
else
{
// is the player there?
if (x == px && y == py)
{
// draw the player
cout << "O";
}
else // empty space
cout << " ";
}
}
// next line
cout << "\n";
}
}
}
}
I am trying to create a maze generator using recursive backtracking and have come across a problem that I just can't get my head around. For some reason my move function is returning the value "18446744073709551615". This is (of course) leading to a segmentation fault. Why is my move function returning such a large value when my move function can only increase or decrease the value by 2?
bool maze::generate(size_t x, size_t y) {
//mark the position as visited
labyrinth.s[y][x] = true;
//print to see progress
//this->print();
//if the position is not out of bounds
if (x < 0 || x > labyrinth.MAXWIDTH - 1 || y < 0 || y > labyrinth.MAXHIGHT - 1) {
//if the position is the endpoint return true
if (labyrinth.v[y][x - 1] == 'W' || labyrinth.v[y][x + 1] == 'W' || labyrinth.v[y - 1][x] == 'W' || labyrinth.v[y + 1][x] == 'W') {
return true;
}
}
//pick a random direction
do {
d = size_t(rand() % 4);
} while(!this->pos_test(x, y, d));
std::cout << x << ' ' << y << std::endl;
if (d == UP) {
y = move(x, y, UP);
}
else if (d == DOWN) {
y = move(x, y, DOWN);
}
else if (d == RIGHT) {
x = move(x, y, RIGHT);
}
else if (d == LEFT) {
x = move(x, y, LEFT);
}
else{
}
std::cout << x << ' ' << y << std::endl;
//recursively generate the maze
if (this->generate(x, y)) {
return true;
}
}
void maze::initialize(size_t x, size_t y) {
//set the maxhight and the maxwidth to y and x
labyrinth.MAXHIGHT = y;
labyrinth.MAXWIDTH = x;
//set all elements in the vector to #
for (size_t i = 0; i < labyrinth.MAXHIGHT; i++) {
std::vector<char> temp;
for (size_t j = 0; j < labyrinth.MAXWIDTH; j++) {
temp.push_back(labyrinth.wall);
}
labyrinth.v.push_back(temp);
}
for (size_t i = 0; i < labyrinth.MAXHIGHT; i++) {
for (size_t j = 0; j < labyrinth.MAXWIDTH; j++) {
if (j % 2 == 1 && i % 2 == 1 && j != labyrinth.MAXWIDTH - 1 && j != 0 && i != labyrinth.MAXHIGHT - 1 && i != 0) {
labyrinth.v[j][i] = labyrinth.path;
}
}
}
//set all posistions to unvisited
for (size_t i = 0; i < labyrinth.MAXHIGHT; i++) {
std::vector<bool> temp2;
for (size_t j = 0; j < labyrinth.MAXWIDTH; j++) {
temp2.push_back(false);
}
labyrinth.s.push_back(temp2);
}
//setup the start point
labyrinth.v[0][1] = 'S';
//setup the endpoint
labyrinth.v[labyrinth.MAXHIGHT - 2][labyrinth.MAXWIDTH - 1] = 'W';
}
//if a position has been visited or if not possible to go to return true
bool maze::pos_test(size_t x, size_t y, size_t d) const {
//if the position is out of bounds return false
if (x < 0 || y < 0 || x > labyrinth.MAXWIDTH - 1 || y > labyrinth.MAXHIGHT - 1) {
return true;
}
else if (x == 1 && d == LEFT) {
return true;
}
else if (y == 1 && d == UP) {
return true;
}
else if (x == labyrinth.MAXWIDTH - 1 && d == RIGHT) {
return true;
}
else if (y == labyrinth.MAXHIGHT - 1 && d == DOWN) {
return true;
}
else if (d == UP) {
return labyrinth.s[y - 2][x];
}
else if (d == DOWN) {
return labyrinth.s[y + 2][x];
}
else if (d == RIGHT) {
return labyrinth.s[y][x + 2];
}
else if (d == LEFT) {
return labyrinth.s[y][x - 2];
}
else {
return true;
}
}
size_t maze::move(size_t x, size_t y, size_t d) {
//if the position is out of bounds return without modifying
if (x < 0 || x > labyrinth.MAXWIDTH - 1) {
return x;
}
else if (y < 0 || y > labyrinth.MAXHIGHT - 1) {
return y;
}
else if (d == UP) {
labyrinth.v[y - 1][x] = labyrinth.path;
return y = y - 2;
}
else if (d == DOWN) {
labyrinth.v[y + 1][x] = labyrinth.path;
return y = y + 2;
}
else if (d == RIGHT) {
labyrinth.v[y][x + 1] = labyrinth.path;
return x = x + 2;
}
else if (d == LEFT) {
labyrinth.v[y][x - 1] = labyrinth.path;
return x = x - 2;
}
else {
}
}
You are underflowing your unsigned 64-bit return type size_t.
You are checking whether x and y are below zero, but that's not enough, because 0 and 1 will still be too low because you are subtracting 2!
The number you get is 0xFFFFFFFFFFFFFFFF in hexadecimal. This is the highest possible value for an unsigned 64-bit integer.
It comes from calculating 1 - 2. Yes, this is supposed to be -1, but because your move function doesn't return a signed number but an unsigned one (check the docs on size_t), it can't be negative! Instead, it wraps around to the highest possible number.
You can imagine this in the same way you would get ...99999999999 when you try to calculate 1 - 2 on paper ignoring the "you can't subtract a higher number from a smaller one on paper" rule.
As a side note: I guess the negative result is undesired anyway, because actually your huge number, once added to a pointer, will in turn overflow back into positive, so basically it will work the same is a real -1 in your case and the segmentation fault comes from accessing something right before the beginning of your buffer, not far beyond it, but it comes down to the same thing.
Apart from that, there is no need to do return y = y - 2 and such. Just return y - 2.
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...