garbage value in while printing array - c++

I am declaring the array dynamically using new. The array is formed of string length, which I am giving from the user. When I am providing a string of length between 7-11 the array is printing garbage value. Why is it happening?
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<climits>
#include<vector>
#include<ctime>
#include<map>
using namespace std;
int main(){
string str;
cin>>str;
int i,j;
int** arr = new int*[str.length()];
for(i = 0; i < str.length(); ++i)
arr[i] = new int[str.length()];
for(i=0;i<str.length();i++){
for(j=0;j<str.length();j++){
cout<<arr[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
The output for string "BBABCBCAB" is:
36397056 0 8 0 -1 0 1111573058 1094926915 0
0 0 4 0 -1 0 1111573058 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
Why is it happening ? And not for other any string with more than length 12?

You're default-initializing all your ints, which doesn't actually assign them a value. Reading from an indeterminate value is undefined behavior - sometimes you get 0s, sometimes you get some weird values. Undefined behavior is undefined.
If you want all 0s, you need to value-initialize the array:
arr[i] = new int[str.length()]();
// ^^
Or use something like memset or std::fill or std::fill_n.

Related

OpenCV's connectedComponentsWithStats() returns NaN position for first centroid

I am using the OpenCV C++ API (version 4.7.0). I have an application where I need to determine the centroid of a laser spot through a camera feed, and to do that I am attempting to use the connectedComponentsWithStats() function.
In my current setup, the image data is defined in a text file as a 2D array. This data is of a binary image, which is expected by connectedCoponentsWithStats(). The size of the image is 625X889. Here is what the binary image looks like:
This is the result of a binary thresholding operation.
Here is my C++ code for computing the centroids of the connected components:
/* Grouping and centroiding implementation using OpenCV's
* ConnectedComponentsWithStats().
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <iostream>
#include <fstream>
#include <opencv2/opencv.hpp>
using namespace std;
int main()
{
uint32_t ROWS=625;
uint32_t COLS=889;
uint8_t image_array[ROWS][COLS];
uint8_t *image_data = new uint8_t[ROWS * COLS];
int i;
int j;
//Read data from file and save into image_array[][].
ifstream fp("./data/binary_image/binary_image1.txt");
if (! fp)
{
cout << "Error opening file" << endl;
return 1;
}
for (i=0; i<ROWS; i++)
{
for (j=0; j<COLS; j++)
{
fp >> image_array[i][j];
if (! fp)
{
cout << "Error reading file for element " << i << "," << j << endl;
return 1;
}
}
}
//Copy data into a 1D array called image_data.
for (i=0; i<ROWS; i++)
{
for (j=0; j<COLS; j++)
{
if (image_array[i][j] == 1)
{
image_array[i][j] = 255;
}
image_data[i * COLS + j] = image_array[i][j];
}
}
//Create image object.
cv::Mat image(ROWS, COLS, CV_8U, image_data);
//Create output objects.
cv::Mat labels, stats, centroids;
//Pass image to connectedComponentsWithStats() function.
int num_components = cv::connectedComponentsWithStats(image, labels, stats, centroids);
//Print out the centroids
for (i=0; i<num_components; i++)
{
cout << "Centroid "<< i << ": (" << centroids.at<double>(i, 0) << ", " << centroids.at<double>(i,1) << ")" << endl;
}
return 0;
}
Not that is it important, but this is how I compiled the code:
g++ `pkg-config --cflags opencv4` -c opencv_grouping.cpp
g++ opencv_grouping.o `pkg-config --libs opencv4` -o opencv_test
This is the output after running ./opencv_test:
Centroid 0: (nan, nan)
Centroid 1: (444, 312)
I am not really sure why I am getting the nan result, but I suppose this means that the area of that connected component is 0? As for the (444, 312) result, that just corresponds (roughly) to the center of a 625X889 grid, which is the size of the inputted image. So it essentially just computed the center of that grid. I tried with several other input images of the same size that were generated using different thresholds (so the spot size varried), and it yielded exactly the same result.
Does anyone have any insight/suggestions as to what might be going on here? Does OpenCV provide other functions that can be used to compute the centroid of the spot?
--Update--
I think that I found out where the problem is coming from. Something very strange is happening when I am reading in the data from the text file. It's not reading the data correctly at all. It gets to row 440 and then the rest of the data is either 0 or some garbage value (like a really large negative number for example). I am not sure why this is happening. In addition to declaring image_array as uint8_t image_array[ROWS][COLS], I have also tried allocating memory for it with new:
uint8_t **image_array = new uint8_t*[ROWS];
for (i=0; i<ROWS; i++)
{
image_array[i] = new uint8_t[COLS];
}
Both of these run into the same problem. As a sanity check, I created a smaller (19X20) array to test with. It looks like this in a text file:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 255 255 255 0 0 0 0 0 0 255 255 255 255 255 0 0 0
0 0 0 255 255 255 0 0 0 0 0 0 0 255 255 255 0 0 0 0
0 0 255 255 255 255 0 0 0 0 0 0 0 0 255 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 255 255 0 0 0 0 0 0 0 0 255 0 0 0 0 0
0 0 0 255 255 255 255 255 0 0 0 0 255 255 255 255 0 0 0 0
0 0 0 0 255 255 255 255 255 0 0 255 255 255 0 0 0 0 0 0
0 0 0 0 0 0 255 255 255 255 255 255 255 0 0 0 0 0 0 0
0 0 0 0 0 0 0 255 255 255 255 255 255 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 255 255 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
I run this through the code my code (with ROWS=19 and COLS=20) and it actually gives a reasonable output for the centroids:
Centroid 0: (9.63497, 9.22086)
Centroid 1: (3.8, 3.1)
Centroid 2: (14, 2.55556)
Centroid 3: (8.71429, 10.2857)
So the issue is that the larger array is not getting read from the text file correctly. Any suggestions?

How to make a group of integers randomly "roll around" a 2d grid, decrementing every time, until each equals 0?

sorry for the weird question, but I can explain.
Imagine you have 50 marbles that are wet with paint, and you are standing over a large canvas. You will drop each marble in the middle of the canvas, wait until it stops rolling around (assume when the marble stops, it disppears), and then drop your next one until you run out of marbles.
You will notice that when you are finished dropping all the marbles, the canvas is painted all over, with some streaks being darker than others.
That is what I am trying to represent with a 2d grid. So if I were to have 5 marbles, each with a "life" of 2, it would look something like this (given a 10x10 2d array)
/*
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
*/
Note, we dropped in the middle, then the marble went up and right
We moved twice, so our initial maxLife == 2 is now maxLife == 0, so we move onto the next marble
/*
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 0 0 2 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
*/
Note, we dropped in the middle again, then the marble went right
We moved twice, so our initial maxLife == 2 is now maxLife == 0, so we move onto the next marble
/*
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 0 0 3 1 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
*/
so on, and so on until we have dropped 5 marbles.
This seems basic enough with a simple nested for loop and recursive method to travel across and increment the array until the base case (when maxLife == 0), is hit. However, I am not getting expected results.
Here is my code :
#include <iostream>
#include <ctime>
using namespace std;
int width, height, xMax, xMin, yMax, yMin, numParticles, maxLife, waterLine;
int main()
{
/* Take in width, height, numParticles, maxLife, removed for code clarity */
int **land = makeParticleMap(width, height, numParticles, maxLife);
printIsland(land, width, height);
return 0;
}
void printIsland(int **land, int width, int height) { ... }
int **makeParticleMap(int width, int height, int numParticles, int maxLife)
{
int **land;
land = new int *[height];
for (int i = 0; i < height; ++i)
{
land[i] = new int[width]; //we have the 2d array
}
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
land[i][j] = 0;
}
}
int x, y = (width + height) / 2;
while (numParticles != 0) //while we have particles to drop
{
particleRoll(land, width, height, x, y, maxLife);
numParticles--;
}
return land;
}
void particleRoll(int **map, int width, int height, int x, int y, int maxLife)
{
if (maxLife <= 0)
{
return;
}
map[x][y]++;
maxLife--;
int xDir = (randomBool()) ? 1 : -1;
int yDir = (randomBool()) ? 1 : -1;
//i + xDir means: i-- or i++, either roll up or down rows, and j--, j++ same thing across columns
particleRoll(map, width, height, x + xDir, y + yDir, maxLife);
}
bool randomBool() { //returns -1 or 1 }
height and width never change, they are just the sizes of the array, since I am working with an int** instead of a vector.
I am just getting a width x height array of all 0's. I assume that the whole logic problem is within the recursion of particleRoll. I tried approaching it in a DFS style search, like the famous Number of Islands algorithm problem. However, I cannot figure out why my code is working like this.

storing integers in an array stores a random value

I'm coding my own minesweeper game for fun in C++ (The language I'm most familiar with) and when I'm storing a constant in a 2d array, it sometimes ends up storing a random value.
Here's my code:
using namespace std;
Table::Table() {
tiles[16][16] = {0};
covers[16][16] ={1};
}//stores position of mines, covers, and values
//places mines on the board
void Table::placemines() {
int minecount=0;
int i = rand()%15;
int j = rand()%15;
while(minecount<40){
if (tiles[i][j] == 0) {
tiles[i][j] = -10;
minecount++;
} else {}
i = rand()%15;
j = rand()%15;
}
}
and my main.cpp to display the values
using namespace std;
int main() {
Table newtable = Table();
newtable.placemines(6, 7);
for (int j = 0; j < 16; j++) {
for (int i = 0; i < 16; i++) {
cout << newtable.tiles[i][j] << ' ';
}
cout << '\n';
}
}
and the output
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 -10 -10 -10 0 0 1 -10 0 0
0 0 0 0 0 0 0 -10 0 -10 -10 0 -10 0 0 0
0 0 0 0 0 -10 0 0 0 -10 -10 0 -10 0 0 0
-10 0 0 -10 -10 0 0 -10 -10 0 0 0 0 -10 0 0
-10 0 -10 0 0 -10 0 0 0 0 0 0 0 -10 0 0
0 0 0 0 0 0 0 0 -10 -10 0 1920169263 0 -10 0 0
0 0 -10 0 0 0 0 0 0 -10 -10 1651076143 0 0 0 0
0 0 0 0 0 0 0 0 -10 -10 0 1819894831 -10 0 0 0
0 0 0 0 0 0 0 0 0 0 0 100 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 -10 0 0 0 0
0 0 0 0 0 0 0 -10 0 -10 0 32 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
-10 0 0 -10 0 0 0 0 0 0 -10 2 0 0 0 0
-10 0 0 0 0 -10 0 0 0 -10 0 4 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 4 0 0 0 0
Can anyone tell what's going on? Thank you!
Too much code missing, no declaration, no placemines() code
You have bug here:
tiles[16][16] = {0};
This statement sets some element of array, with indices 16 and 16, to 0. If your array defined as type tiles[16][16] that means you write into the Abyss and cause UB (because last element of array is tiles[15][15]).
If you have to initialize an array, use std::fill http://en.cppreference.com/w/cpp/algorithm/fill . For zero-intialization this works:
Table::Table() : tiles{0} {
Another bug possible:
int i = rand()%15;
You have to use array's size to cover the range properly.
PS. Avoid using namespace std; in global scope, pleeeese.

Loading Data from File to Data Structure in C++ and Interpreting It

Okay so this code is killing me.
My goal is to read data from a file where the data is separated by commas, then load that data into an array of structures that is supposed to be a list of "theater seats". The theater seats have certain characteristics, such as "location", "price", and "status". Price is self-explanatory. Location deals with the row and seat number of the "Seat". And status pertains to whether or not it's sold. After that, I have to interpret the data that I pulled from the data file to make a display THAT CAN be easily manipulated by the user if they input a certain choice. But that's not what I'm getting at in this question.
My question is, what would be the best method to load my data structures from the data file?
Let me show you a bit of the data file that I'm reading from.
1, 1, 50, 0
1, 2, 50, 0
1, 3, 50, 0
1, 4, 50, 0
To explain the data file, the first number is the "row", second number is the seat number in that row, the third number is the price, and the final number ("0") stands for the seat being unsold. Had the seat been purchased, the final number would be 1.
Now, here's my code.
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <cstdlib>
#include <cstdio>
#include <conio.h>
using namespace std;
enum seatDimensions{ROWS = 10, SEATS_PER = 16};
//Structures
struct Location
{
int row;
int seatNumber;
};
struct Seat
{
Location seat_location[160];
double ticketPrice;
int status;
int patronID;
};
//GLOBALS
const int MAX = 16;
int main()
{
//arrays for our data
Seat seatList[160];
//INDEX
int index = 1;
//filestream
fstream dataIn;
dataIn.open("huntington_data.dat",ios::in);
if(dataIn.fail()) //same as if(dataIn.fail())
{
cout << "Unable to access the data file." << endl;
return 999;
}
string temp;
getline(dataIn,temp,',');
seatList[index].seat_location[index].row = atoi(temp.c_str());
getline(dataIn,temp,',');
seatList[index].seat_location[index].seatNumber = atoi(temp.c_str());
getline(dataIn,temp,',');
seatList[index].ticketPrice = atof(temp.c_str());
getline(dataIn,temp,'\n');
seatList[index].status = atoi(temp.c_str());
while(!dataIn.eof() && index < MAX)
{
index++;
getline(dataIn,temp,',');
seatList[index].seat_location[index].row = atoi(temp.c_str());
getline(dataIn,temp,',');
seatList[index].seat_location[index].seatNumber = atoi(temp.c_str());
getline(dataIn,temp,',');
seatList[index].ticketPrice = atof(temp.c_str());
getline(dataIn,temp,'\n');
seatList[index].status = atoi(temp.c_str());
}
getch ();
return 0;
}
Now from here, I have to display whether or not the seats are TAKEN or not.
The display should look like this, since none of the seats are taken yet.
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 // 16 across
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
// 10 deep
I know I'm not inputting my data in correctly, because I cannot seem to get this display no matter how I try to cout it. If you can tell where I'm going wrong, please tell me. Any suggestions would be amazing.
Also, if you have any questions for me, just ask. I tried to be as specific as possible considering the question, but I know that it's still pretty vague.
Please help.
EDIT: Thanks to those who answered my question. I ended up going a very different route with my data structure, but pulled a lot from the answers.
You have the problem that each seat has a position in an array and then has an array of positions:
You need:
Location seat_location[160];
changed to:
int seat_row;
int seal_num;
then:
seatList[index].seat_location[index].row = atoi(temp.c_str());
becomes:
seatList[index].seat_row = index / COLS ;
seatList[index].seat_num = index % COLS ;
You may also like to consider actually arranging your data into a 2D array of the same dimensions as your seating.
BTW From my C background I would suggest reading the whole line and using sscanf, e.g.:
char temp[255]; // Use an appropriate maximum line length +3 for \r\n\0
fgets(dataIn, &temp);
sscanf(temp, "%d, %d, %d, %d", &.....
You could also consider implementing this with a regular expression.
Write a function that gets string of input and splits it into items:
std::vector<std::string> splitLine( const std::string &str );
Implement and debug it with string like "1, 1, 50, 0", make sure it returns vector of string with each number as separate element. Then read input line by line, split and convert each string to number separately. You will simplify the code and it will be much easier to make it work.
is it an assignment?
i guess the way you are organizing your data in structure needs to be changed.
Take a structure maybe like this
struct Seat{
double ticketPrice;
int status;
int patronId;
}
and have a two dimensional array like this
Seat seatList[10][16];
first dimension is (row number-1), second dimension is (seat number-1)
and read your data from file like this
string temp;
getline(dataIn,temp,',');
int row = atoi(temp.c_str());
getline(dataIn,temp,',');
int seatNumber = atoi(temp.c_str());
getline(dataIn,temp,',');
//check row and seatnumber > 0
seatList[row-1][seatNumber-1].ticketPrice = atof(temp.c_str());
getline(dataIn,temp,'\n');
seatList[row-1][seatNumber-1].status = atoi(temp.c_str());
Use two simple for loops to print your output from these structures.

How do I add a number to an array if it is less than a corresponding number in a "Max" array?

So here is my issue. In the program I have below, towards the bottom of the function "SetBoardStartingConfig" I attempt to fill in the first 4 rows of an array by randomly generating numbers, checking if the square I'm attempting to place them onto is empty (0), and if the addition of the piece would make it go over the specified max values in array "MaxPieces". If it wouldn't, it should theoretically be added - but its not working as I intended, and throwing me interesting values. In main, I go on to repeat this function 10 times, but it always seems to produce a different error - below I've also pasted some of my results.
Note: I've commented out both algorithms to try this, they're separated by a bit of white space.
Sidenote: I seem to always get FlagSide = 1 (right side) the first time I run the program - any ideas on how to fix this?
Thank you all very much for your help :).
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
int board[10][10];
int AIPieces[11];
int PlayerPieces[11];
int MaxPieces[11];
string PieceNames[11];
//insert stuff for maximum number of things
#define NullSpace -1 // Spaces that pieces can not move to
#define Flag -5
#define Bomb 1
#define EmptySpace 0 //Empty board spaces
void SetMaxPieces()
{
MaxPieces[0] = 1;
MaxPieces[Bomb] = 6;
MaxPieces[2] = 8;
MaxPieces[3] = 5;
MaxPieces[4] = 4;
MaxPieces[5] = 4;
MaxPieces[6] = 4;
MaxPieces[7] = 3;
MaxPieces[8] = 2;
MaxPieces[9] = 1;
MaxPieces[10] = 1;
MaxPieces[11] = 1; //Spy
}
void ResetAIPieces()
{
for (int i = 0; i < 11; i++)
AIPieces[i] = 0;
}
void SetPieceNames()
{
PieceNames[0] = "Flags:";
PieceNames[1] = "Bombs:";
PieceNames[2] = "Twos:";
PieceNames[3] = "Threes:";
PieceNames[4] = "Fours:";
PieceNames[5] = "Fives:";
PieceNames[6] = "Sixes:";
PieceNames[7] = "Sevens:";
PieceNames[8] = "Eights:";
PieceNames[9] = "Nines:";
PieceNames[10] = "Tens:";
PieceNames[11] = "Spies:";
}
void PrintBoard()
{
for (int i=0; i<10; i++)
{
for (int j=0; j<10; j++)
{
cout << board[i][j] << " ";
if (board[i][j] >= 0)
{
cout << " ";
}
}
cout << endl;
}
}
void SetBoardStartingConfig()
{
for (int i=0; i<10; i++)
{
for (int j=0; j<10; j++)
{
board[i][j] = EmptySpace;
}
}
//arrays work in [row] and [column].
//below defines areas that the pieces can not move to.
board[4][2] = NullSpace;
board[4][3] = NullSpace;
board[5][2] = NullSpace;
board[5][3] = NullSpace;
board[4][6] = NullSpace;
board[4][7] = NullSpace;
board[5][6] = NullSpace;
board[5][7] = NullSpace;
int FlagSide = rand() % 2;
if (FlagSide == 0)
{
board[0][0] = Flag;
AIPieces[0]++;
AIPieces[board[2][0] = Bomb]++;
AIPieces[board[1][1] = Bomb]++;
AIPieces[board[0][2] = Bomb]++;
AIPieces[board[1][0] = rand() % 3 + 4]++;
AIPieces[board[0][1] = rand() % 3 + 4]++;
}
else if (FlagSide == 1)
{
board[0][9-0] = Flag;
AIPieces[0]++;
AIPieces[board[2][9-0] = Bomb]++;
AIPieces[board[1][9-1] = Bomb]++;
AIPieces[board[0][9-2] = Bomb]++;
AIPieces[board[1][9-0] = rand() % 3 + 4]++;
AIPieces[board[0][9-1] = rand() % 3 + 4]++;
}
//for (int i =0; i < 4; i++)
// for (int j = 0; j < 10; j++)
// {
// if (board[i][j] == 0)
// {
// int Chosen = rand() % 10+1;
// if (AIPieces[Chosen] < MaxPieces[Chosen])
// {
// board[i][j] = Chosen;
// AIPieces[Chosen]++;
// }
// else
// break;
// }
// else
// break;
// // if (AIPieces[0] < MaxPieces[0] || AIPieces[1] < MaxPieces[1] || AIPieces[2] < MaxPieces[2] || AIPieces[3] < MaxPieces[3] || AIPieces[4] < MaxPieces[4] || AIPieces[5] < MaxPieces[5] || AIPieces[5] < MaxPieces[5] || AIPieces[6] < MaxPieces[6] || AIPieces[7] < MaxPieces[7] || AIPieces[8] < MaxPieces[8] || AIPieces[9] < MaxPieces[9] || AIPieces[10] < MaxPieces[10] || AIPieces[11] < MaxPieces[11])
// //{
// // AIPieces[board[i][j] = rand() % 10+1]++;
// //}
// }
}
int main()
{
SetMaxPieces();
SetPieceNames();
int loop = 0;
do
{
SetBoardStartingConfig();
PrintBoard();
cout << endl;
for (int i = 0; i < 11; i++)
{
cout << PieceNames[i] << AIPieces[i] << endl;
}
cout << endl;
ResetAIPieces();
loop++;
} while (loop <= 10);
system("PAUSE");
}
My Results (They seem to be the same every time I run it using the first algorithm)
1 10 5 9 0 0 0 1 5 -5
3 5 6 6 2 8 2 2 1 6
6 3 8 7 2 5 3 4 3 1
3 2 7 0 0 0 0 0 0 0
0 0 -1 -1 0 0 -1 -1 0 0
0 0 -1 -1 0 0 -1 -1 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
Flags:1
Bombs:4
Twos:5
Threes:5
Fours:1
Fives:4
Sixes:4
Sevens:2
Eights:2
Nines:1
Tens:1
2 9 10 3 8 0 0 1 4 -5
6 5 4 2 3 4 4 5 1 6
2 2 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0 0 0
0 0 -1 -1 0 0 -1 -1 0 0
0 0 -1 -1 0 0 -1 -1 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
Flags:1
Bombs:3
Twos:4
Threes:2
Fours:4
Fives:2
Sixes:2
Sevens:0
Eights:1
Nines:1
Tens:1
8 8 10 4 2 0 0 1 5 -5
9 7 6 1 3 0 0 0 1 6
7 1 3 5 0 0 0 0 0 1
7 6 1 0 0 0 0 0 0 0
0 0 -1 -1 0 0 -1 -1 0 0
0 0 -1 -1 0 0 -1 -1 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
Flags:1
Bombs:6
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 0 0 0 0 0 0 0
4 10 9 0 0 0 0 0 0 0
0 0 -1 -1 0 0 -1 -1 0 0
0 0 -1 -1 0 0 -1 -1 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
Flags:1
Bombs:3
Twos:0
Threes:0
Fours:2
Fives:1
Sixes:0
Sevens:0
Eights:0
Nines:1
Tens:1
Press any key to continue . . .
I'm not really clear what you expect to happen or what is happening, you should try explaining why what you get is wrong, so people don't have to spend ages analysing the code and results. Is the first algorithm working and the second not? Or are both wrong? The changes below will make the program easier to reason about anyway.
Your variable and function naming is a bit unconventional. It's more usual to see variables and functions start with a lowercase letter, and classes start with an uppercase letter. Your program looks as though Everything Is Very Important.
Why are you using macros here?
#define NullSpace -1 // Spaces that pieces can not move to
#define Flag -5
#define Bomb 1
#define EmptySpace 0 //Empty board spaces
In general, macros suck, especially if you don't name them to avoid clashing with other names. The inventor of C++ recommends using ALL_CAPS for macros. Better still, don't use them:
const int NullSpace = -1; // Spaces that pieces can not move to
const int Flag -5;
const int Bomb 1;
const int EmptySpace 0; //Empty board spaces
This is a very tedious way to set arrays:
void SetMaxPieces()
{
MaxPieces[0] = 1;
MaxPieces[Bomb] = 6;
MaxPieces[2] = 8;
...
MaxPieces[10] = 1;
MaxPieces[11] = 1; //Spy
}
Just initialize the array when you define it:
int MaxPieces[11] = {
1, 6, 8, 5, 4, 4, 4, 3, 2, 1, 1, 1
};
string PieceNames[11] = {
"Flags:", "Bombs:", "Twos:", "Threes:", "Fours:", "Fives:", "Sixes:",
"Sevens:", "Eights:", "Nines:", "Tens:", "Spies:"
};
But wait! Now the compiler refuses to compile the program:
game.cc:13:1: error: too many initializers for ‘int [11]’
game.cc:17:1: error: too many initializers for ‘std::string [11] {aka std::basic_string [11]}’
You are setting twelve values in an array of eleven! The compiler didn't complain when you did MaxPieces[11] (but maybe should have done) but it definitely won't let you initialize an array with too many values. Are your arrays supposed have twelve elements? Or are you just filling them wrong?
As a commenter pointed out, you must seed rand() or the pseudo-random number generator always starts in the same initial state and produces the exact same sequence of "random" numbers.
Why are you using do-while in main? do-while is only useful in a few situations, when the condition can't be tested initially (or for some clever hacks to make its block scope act as a single statement in evil macros). In your case the condition is initially true (loop is less than 10) so just use a for or while loop. I would prefer a for because your loop variable doesn't need to exist after the for so you can initialize it there:
for (int loop = 0; loop <= 10; ++loop)
{
SetBoardStartingConfig();
PrintBoard();
cout << '\n';
for (int i = 0; i < 11; i++)
{
cout << PieceNames[i] << AIPieces[i] << '\n';
}
cout << '\n';
ResetAIPieces();
}
cout << flush;
Using endl every time you want a newline is unnecessary, endl adds a newline and flushes the stream, which doesn't need to be done on every line. The code above does it just once after the loop.
Now for the first algorithm:
for (int i =0; i < 4; i++)
for (int j = 0; j < 10; j++)
{
if (board[i][j] == 0)
{
int Chosen = rand() % 10+1;
if (AIPieces[Chosen] < MaxPieces[Chosen])
{
board[i][j] = Chosen;
AIPieces[Chosen]++;
}
else
break;
}
else
break;
Surrounding the first for in braces could help readability too. It would also help to write rand()%10 + 1 rather than the spacing you have above, so that the operator precedence is more obvious, currently it looks like you mean it to be rand() % 11 because you've grouped the addition operands.
Shouldn't the check board[i][j] == 0 be board[i][j] == EmptySpace ? Otherwise what's the point of having that constant?
Do you really want to break there? Doesn't that mean you stop filling a row as soon as you find a non-empty square or run out of a particular kind of piece? If the break should be there, where do they go for the second algo? Your code is impossible to reason about, partly because all the important logic is commented out (that's not a helpful way to read code!) and because of the inconsistent indentation.
Your second algorithm is completely unreadable, do you have a screen wide enough to see that line without wrapping? Even if you do it would be easier to read broken up.
Does the second algo check board[i][j] == EmptySpace? It doesn't seem to, but maybe that's just your formatting.
Also, all those comments make it awkward to switch between implementations to compare the results. If you do this:
for (int i =0; i < 4; i++)
{
for (int j = 0; j < 10; j++)
{
if (board[i][j] == EmptySpace)
{
#if 0
int Chosen = rand()%10 +1;
if (AIPieces[Chosen] < MaxPieces[Chosen])
{
board[i][j] = Chosen;
AIPieces[Chosen]++;
}
else
break;
#else
if (AIPieces[0] < MaxPieces[0]
|| AIPieces[1] < MaxPieces[1]
|| AIPieces[2] < MaxPieces[2]
|| AIPieces[3] < MaxPieces[3]
|| AIPieces[4] < MaxPieces[4]
|| AIPieces[5] < MaxPieces[5]
|| AIPieces[5] < MaxPieces[5]
|| AIPieces[6] < MaxPieces[6]
|| AIPieces[7] < MaxPieces[7]
|| AIPieces[8] < MaxPieces[8]
|| AIPieces[9] < MaxPieces[9]
|| AIPieces[10] < MaxPieces[10]
|| AIPieces[11] < MaxPieces[11])
{
AIPieces[board[i][j] = rand() % 10+1]++;
}
#endif
}
else
break;
}
}
Then you only need to change one character (change #if 0 to #if 1) to switch between them.
Now I can see the second algorithm properly it's obvious that if any pieces remain you will place a piece, but that could place a piece which you've run out of. e.g. if AIPieces[1] < MaxPieces[1] but AIPieces[2] == MaxPieces[2] the condition is true, but then if rand()%10 + 1 returns 2 you put a piece you aren't allowed to place. That means you place too many of some types of piece.
I think Scott has a much better idea, separate the placing of pieces into a function, which will make that loop much easier to read:
for (int i =0; i < 4; i++)
for (int j = 0; j < 10; j++)
AddPiece(rand() % 3 + 4, 1, 0);
Now you could write AddPiece2 and change the call to that to experiment with different implementations. Comparing the two algorithms could help find where it goes wrong.
I'm not sure I'm understanding the question well. But, trying to answer it. Something like this seems to be what you're asking for:
Instead of incrementing AIPieces, you need to first check that the board doesn't already have something on it and that MaxPieces haven't already been used.
AIPieces[board[1][0] = rand() % 3 + 4]++;
So try a function to do this:
void AddPiece(int pieceType, int locationX, int locationY)
{
if( board[locationX][locationY] != 0 )
return; // board already has something here, so don't add.
if( AIPieces[pieceType] >= MaxPieces[pieceType] )
return; // Can't add as all of these pieces have already been used.
board[locationX][locationY] = pieceType;
AIPieces[pieceType]++;
}
And in place of the original line, call the function like this:
AddPiece(rand() % 3 + 4, 1, 0);
Your second algorithm won't work because when you try and add a piece, the if statement checks if any type of piece has been used, instead of just checking the type of piece you're trying to add.