Can someone please illuminate why I am getting the following error with the following code?
Execution error: Your program had this runtime error:
Exceeded memory or invalid memory reference. The program ran for
0.000 CPU seconds before the error. It used 3048 KB of memory.
------ Data ------
7 4
11 6 11 6 3 10 6
7 9 6 13 5 15 5
1 10 12 7 13 7 5
13 11 10 8 10 12 13
----------------------------
Code:
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
int castle[50][50];
int components[50][50];
bool visited[50][50];
int N, M;
void flood(int y, int x, int component) {
if(visited[y][x]) return;
visited[y][x] = true;
components[y][x] = component;
if(x>0 && !((castle[y][x] & 1) == 1)) { //West
cout<<"castle["<<y<<"]["<<x<<"] just";
cout<<"flooded west\n";
flood(y, x-1, component);
}
if(y>0 && !((castle[y][x] & 2) == 2)) { //North
cout<<"castle["<<y<<"]["<<x<<"] just";
cout<<"flooded north\n";
flood(y-1, x, component);
}
if(x<M && !((castle[y][x] & 4) == 4)) { //East
cout<<"castle["<<y<<"]["<<x<<"] just";
cout<<"flooded east\n";
flood(y, x+1, component);
}
if(y<N && !((castle[y][x] & 8) == 8)) { //South
cout<<"castle["<<y<<"]["<<x<<"] just";
cout<<"flooded south\n";
flood(y+1, x, component);
}
}
int main() {
ifstream inp("castle.in");
ofstream out("castle.out");
memset(components, -2, sizeof(components));
memset(visited, false, sizeof(visited));
inp >> M >> N;
for(int y=0; y<N; y++) {
for(int x=0; x<M; x++) {
inp >> castle[y][x];
}
}
int curComponent = 0;
for(int y=0; y<N; y++) {
for(int x=0; x<M; x++) {
if(visited[y][x]) continue;
flood(y,x,++curComponent); //first component will be 1
// cout << "curComponent = " << curComponent <<"\n";
}
}
int roomAreas[curComponent+2]; //need an extra one since curComponent actually starts at 1
memset(roomAreas, 0, sizeof(roomAreas));
int greatestArea = 0;
for(int y=0; y<N; y++) {
for(int x=0; x<M; x++) {
cout << "components[" << y <<"][" << x <<"] = " << components[y][x] << "\n";
roomAreas[components[y][x]]++;
if(roomAreas[components[y][x]] > greatestArea) greatestArea = roomAreas[components[y][x]];
}
}
int greatestCombined = 0, bestx=0, besty=0;
char bestDir='N'; //Means none -> error
for(int y=0; y<N; y++) {
for(int x=0; x<M; x++) {
/*
if(x>0 && components[y][x] != components[y][x-1] && roomAreas[components[y][x]] + roomAreas[components[y][x-1]] > greatestCombined) { //West
greatestCombined = roomAreas[components[y][x]] + roomAreas[components[y][x-1]];
bestx = x;
besty = y;
bestDir = 'W';
}
*/
if(y>0 && components[y][x] != components[y-1][x] && roomAreas[components[y][x]] + roomAreas[components[y-1][x]] > greatestCombined) { //North
greatestCombined = roomAreas[components[y][x]] + roomAreas[components[y-1][x]];
bestx = x;
besty = y;
bestDir = 'N';
}
if(x<M && components[y][x] != components[y][x+1] && roomAreas[components[y][x]] + roomAreas[components[y][x+1]] > greatestCombined) { //East
greatestCombined = roomAreas[components[y][x]] + roomAreas[components[y][x+1]];
bestx = x;
besty = y;
bestDir = 'E';
}
/*
if(y<N && components[y][x] != components[y+1][x] && roomAreas[components[y][x]] + roomAreas[components[y+1][x]] > greatestCombined) { //South
greatestCombined = roomAreas[components[y][x]] + roomAreas[components[y+1][x]];
bestx = x;
besty = y;
bestDir = 'S';
}
*/
}
}
out << curComponent << "\n" << greatestArea << "\n" << greatestCombined << "\n" << besty+1 << " " << bestx+1 << " " << bestDir << "\n";
return 0;
}
Thanks so much!
Possibly
if(x<M && ...
should be
if(x<M-1 && ...
Since in that part, it can recursively flood(x+1). That could mean passing in x equal to M, which is overflowing the bounds to the east.
Similarly for the y flooding south check.
Related
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;
}
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 want to plot where the x and y variables are in an array, and when the x or y value is greater than its respective dimension in the array, they should change direction. However, when I run the program the Y value keeps going up. I am new to C++ so any help is greatly appreciated. Here is my code:
#define PI 3.14159265
#include <iostream>
#include <tgmath.h>
int timeRun = 0;
int rect[500][1000] = {0};
int theta = 50;
int x = 0;
float y = 0;
float previousY = 0;
int yGo;
int dir = 0;//0 = right; 1 = left;
int main()
{
for(int a = 30; a<=89; a=a+1){
memset(rect,0,sizeof(rect));
x = 0;
y = 1;
theta = a;
std::cout << theta;
int sum = 0;
for(int t = 0; t<1000;t=t+1){
y = previousY + tan(theta * PI/180);
previousY = y;
yGo = floor(y);
rect[x][yGo] = 1;
if(dir==0){
x++;
}
if(dir==1){
x--;
}
if(x>499 && dir==0){
dir = 1;
if(theta%360 >= 270 && theta%360 <= 360){
theta+=(a-180);
}
}
if(x<1 && dir==1){
dir = 0;
if(theta%360 >= 0 && theta%360 <= 90){
theta+=(180-a);
}
}
if(y>998 && dir ==0){
theta+=(a-180);
}
if(y>998 && dir ==1){
theta+=(180-a);
}
if(y<1 && dir ==0){
theta+=(180-a);
}
if(y<1 && dir ==1){
theta+=(a-180);
}
}
for ( int i = 0; i < 500; i++ ){
for ( int j = 0; j < 1000; j++ ){
sum+=rect[i][j];
}
}
std::cout << sum;
}
}
Thank you for any help!
I really don't understand your program. I simplified the core to:
static const float radian_conversion = 3.14159264f / 180.0f;
int x = 0;
float y = 0.0f;
int theta = 30;
int dir_add = 1;
cout << "t | x | y | theta" << endl;
const float y_increment = tan(theta * radian_conversion);
for (int t = 0; t < 1000; ++t)
{
y = y + y_increment;
cout << t << "|" << x << "|" << y << "|" << theta << "\n";
int y_index = floor(abs(y));
rect[x][y_index] = 1;
x = x + dir_add;
if ((x > 499) || (x < 1))
{
dir_add = dir_add * -1;
}
}
I'm also showing how you can make the x variable increment and decrement.
The statements that don't change or don't cause a variable to change have been extracted out of the loop.
I recommend you take the output of the above program into a spreadsheet program and have the spreadsheet program plot it.
When I try to start my C++ program it stops with error "5.exe has stopped working". This program supposed to calculate how many tiles you need for pool, if number of tiles on one side is non-round number, add one row of tiles to it. P.S. Sorry for my bad English.
#include <iostream>
#include <math.h>
#include <cstdlib>
using namespace std;
int main()
{
int x,y,z;
int a,b;
cout << "Insert dimensions of pool in metres: " << endl;
cin >> x >> y >> z;
cout << "Insert dimensions of tile in centimeters: " << endl;
cin >> a >> b;
a=a/100;
b=b/100;
int brx = 0, brzx = 0, bry = 0, brzy = 0, bxpod = 0, bypod = 0;
if (x%a == 0) {
brx = x / a;
}
else {
brx = x / a + 1;
}
if (z%b == 0) {
brzx = z / b;
}
else {
brzx = z / b + 1;
}
if (y%a == 0) {
bry = y / a;
}
else {
bry = y / a + 1;
}
if (z%b == 0) {
brzy = z / b;
}
else {
brzy = z / b + 1;
}
if (x%a == 0) {
bxpod = x / a;
}
else {
bxpod = x / a + 1;
}
if (y%b == 0) {
bypod = y / b;
}
else {
bypod = y / b + 1;
}
int s = (brx*brzx + bry*brzy) * 2 + bxpod*bypod;
cout << "You need " << s << "tiles." << endl;
system("pause");
return 0;
}
Using a debugger, you can easily find that you have a division by 0 in the following lline:
if (x%a == 0) {
brx = x / a;
}
You are doing an integer division on "a":
a = a / 100;
So if a is lower than 100, a will be 0. 10 / 100 = 0.1 = 0 when cast as int.
You should use double instead of int
I'm now working on a Tic Tac Toe project. I'm having the problem that whenever I input into the console an ordinate,for example [6][0] (and the program will put the mark 'X' or 'O' into that position) for an array with the size of [15][15],it will automatically save the mark 'X' or 'O' into another position which is not in the array range (in my case is [5][15]).This is my program (P/S: I'm Vietnamese so just ignore the parts that are in Vietnamese):
int size = 15;
int inputAmount;
int inputX = 0;
int inputY = 0;
char board[15][15];
bool checkWin = false;
char mark = 'X';
// Interdisciplinary examination of scale loss
bool checkWinLose() {
int max;
int x,y;
x = inputX;
y = inputY;
// Looking horizontally under investigation
for (; max < 3; max++)
{
if ((board[x][y] == 'X' || board[x][y] == 'O') && (board[x][y] == board[x - 1][y] && board[x - 1][y] == board[x - 2][y]))
{
cout << "Game over ngang!" << endl;
return 1;
}
x++;
}
x = inputX;
y = inputY;
max = 0;
// Interdisciplinary examination of vertical
for (; max < 3; max++)
{
if ((board[x][y] == 'X' || board[x][y] == 'O') && (board[x][y] == board[x][y - 1] && board[x][y - 1] == board[x][y - 2]))
{
cout << "Game over doc!" << endl;
return 1;
}
y++;
}
x = inputX;
y = inputY;
max = 0;
// Interdisciplinary examination of under the cliff cave from left to right
for (; max < 3; max++)
{
if ((board[x][y] == 'X' || board[x][y] == 'O') && (board[x][y] == board[x - 1][y - 1] && board[x - 1][y - 1] == board[x - 2][y - 2]))
{
cout << "Game over trai sang phai!" << endl;
return 1;
}
x++;
y++;
}
x = inputX;
y = inputY;
max = 0;
// Interdisciplinary examination of under the cliff cave from right to left
for (; max < 3; max++)
{
if ((board[x][y] == 'X' || board[x][y] == 'O') && (board[x][y] == board[x + 1][y - 1] && board[x + 1][y - 1] == board[x + 2][y - 2]))
{
cout << "Game over phai sang trai!" << endl;
return 1;
}
x--;
y++;
}
// Flower test case
if (inputAmount == 225)
{
cout << "Game over hoa!" << endl;
return 1;
}
}
// Lay-coordinate of the muon practice player list
void takeInput() {
do {
// Lay gia tri toa do x
do {
cout << "Please choose the horizontal (rightward) number (smaller than " << size + 1 << "): ";
cin >> inputX;
} while ((inputX > size) || (inputX <= 0));
// Lay y coordinate values
do {
cout << "Please choose the vertical (downward) number (smaller than " << size + 1 << "): ";
cin >> inputY;
} while ((inputY > size) || (inputY <= 0));
inputX--;
inputY--;
if (board[inputX][inputY] != '.')
cout << "Already chosen!" << endl ;
} while (board[inputX][inputY] != '.');
board[inputX][inputY] = mark;
if (mark == 'X')
mark = 'O';
else
mark = 'X';
cout << endl << endl << endl;
}
// Hien game board on the screen
void loadGameboard () {
int x,y;
////TODO: check win or lose
while (!checkWin) {
for (; y < size ; y++)
{
for (; x < size ; x++)
{
cout << board[x][y] << " ";
}
cout << endl;
x = 0;
}
checkWin = checkWinLose();
if (checkWin == true)
return;
x,y = 0;
takeInput();
inputAmount++;
}
}
// At first preparation game board
void prepareGameboard () {
int x,y;
for (; y < size ; y++)
{
for (; x < size ; x++)
{
board[x][y] = '.' ;
}
x = 0;
}
}
int main(array<System::String ^> ^args)
{
char reset = 'y';
do {
prepareGameboard();
loadGameboard();
checkWin = 0;
inputAmount = 0;
cout << "Do you want to replay ? (y/n): ";
cin >> reset;
if ((reset == 'y') || (reset == 'Y'))
{
system("CLS");
}
} while ((reset == 'y') || (reset == 'Y'));
return 0;
}
I would change x,y = 0 to x = y = 0 at line 123 in the code you pasted. And also add return 0 to the function checkWinLose().
You are not initializing the values for x and y in ther for's.
Try to use :
void prepareGameboard () {
int x,y;
for (y = 0; y < size ; y++)
{
for (x = 0; x < size ; x++)
{
board[x][y] = '.' ;
}
}
}
And:
void loadGameboard () {
int x,y;
////TODO: check win or lose
while (!checkWin) {
for (y = 0; y < size ; y++)
{
for (x = 0; x < size ; x++)
{
cout << board[x][y] << " ";
}
cout << endl;
}
checkWin = checkWinLose();
if (checkWin == true)
return;
takeInput();
inputAmount++;
}
}
Also, like #Heinz said, and a return 0; at the end of the checkWinLose function;
Looking at your code, I believe the you are assuming the int always are initialized with 0 and that checkWinLose will return 0 by the default. Local variables have undefined initialization values and when no explicity return is called, the function just return so 'garbage' value.
Try to always add the returned value to the functons and initialize your variables (specially counters).
Update
This is how the function checkWinLose should be with the return 0;
// Interdisciplinary examination of scale loss
bool checkWinLose() {
int max;
int x,y;
x = inputX;
y = inputY;
// Looking horizontally under investigation
for (; max < 3; max++)
{
if ((board[x][y] == 'X' || board[x][y] == 'O') && (board[x][y] == board[x - 1][y] && board[x - 1][y] == board[x - 2][y]))
{
cout << "Game over ngang!" << endl;
return 1;
}
x++;
}
x = inputX;
y = inputY;
max = 0;
// Interdisciplinary examination of vertical
for (; max < 3; max++)
{
if ((board[x][y] == 'X' || board[x][y] == 'O') && (board[x][y] == board[x][y - 1] && board[x][y - 1] == board[x][y - 2]))
{
cout << "Game over doc!" << endl;
return 1;
}
y++;
}
x = inputX;
y = inputY;
max = 0;
// Interdisciplinary examination of under the cliff cave from left to right
for (; max < 3; max++)
{
if ((board[x][y] == 'X' || board[x][y] == 'O') && (board[x][y] == board[x - 1][y - 1] && board[x - 1][y - 1] == board[x - 2][y - 2]))
{
cout << "Game over trai sang phai!" << endl;
return 1;
}
x++;
y++;
}
x = inputX;
y = inputY;
max = 0;
// Interdisciplinary examination of under the cliff cave from right to left
for (; max < 3; max++)
{
if ((board[x][y] == 'X' || board[x][y] == 'O') && (board[x][y] == board[x + 1][y - 1] && board[x + 1][y - 1] == board[x + 2][y - 2]))
{
cout << "Game over phai sang trai!" << endl;
return 1;
}
x--;
y++;
}
// Flower test case
if (inputAmount == 225)
{
cout << "Game over hoa!" << endl;
return 1;
}
return 0; //<- Returning false if the all other tests failed
}