Inconsistent randomization in array - c++

Basically, I have a 6x6 board. I created a function that's supposed to place three X's on random coordinates on the board.
const int size = 6;
char board[6][6] = {0}; //this is actually somewhere else, but I included it here for clarity
char enemies[3] = {'X','X','X'};
void setup(char board[6][6]){
bool valid = false; //sets initial bool value to false
for (int x = 0; x <= 2; ++x){
do{
int a = rand() % size;
int b = rand() % size;
if (board[a][b] == 0){
board[a][b] = enemies[x];
valid = true;
}
}while(!valid); //if the value is false, redo until an empty board space is found
}
(I included srand(time(NULL)) in the main function as well)
It works, but only sometimes. Sometimes it generates 3 randomly placed X's, and sometimes only 2. I want it to generate 3 every single time. I have been over it a million times, trying minor variations and corrections, but I can't seem to figure out what's wrong. I included a condition for it to only place enemies[x] if the board is blank (board[a][b] == 0), and yet it sometimes only places 2 X's for some reason.

After the first X is placed, valid remains true for all subsequent iterations of the for loop, even if a valid square hasn't been found.
I changed the iteration variable to i (using x to mean something other than an ordinal when you're using 2d coordinates is just confusing), and fixed your inner retry loop:
for (int i = 0; i <= 2; ++i) {
// loop until we find a valid coordinate
while(true) {
int a = rand() % size;
int b = rand() % size;
if (board[a][b] == 0){
board[a][b] = enemies[i];
break; // we found one!
}
}
}

You are not resetting the valid flag inside the outer loop. So, once you've placed the first piece, you do not correctly handle duplicates.
for (int x = 0; x <= 2; ++x)
{
valid = false; // <-- you forgot to do this.
do
{
int a = rand() % size;
int b = rand() % size;
if (board[a][b] == 0)
{
board[a][b] = enemies[x];
valid = true;
}
} while(!valid);
}

After each run through the do/while loop you need to reset valid. After the first iteration (when x is 0), valid will be set to true. You never reset it back to false, and so on the next iterations (starting with x being 1), valid will be set to true already. This means that you might select a random coordinate that you've already marked and then proceed to the next x anyway.
That means it's entirely possible that only one square will have been marked, but the odds of this are low (1 in 1,225, if my math is correct).

Related

Wrong array variable getting changed

In the following function I clearly change the variable rightArray through the statement: rightArray[i] = dataValues[i];
However the behaviour I'm getting from the function is that the variable leftArray is changing in place of rightArray
//Returns the interquartile range
float StatisticalAnalyser::getInterquartileRange()
{
float interquartileRange = 0;
int numberOfDatums = dataFile.findNumberOfDatums();
float numberOfDatumsFloat = dataFile.findNumberOfDatums();
float dataValues[dataFile.findNumberOfDatums()];
dataFile.initialiseArrayToFileData(dataValues);
//If even number of datums
if (numberOfDatums % 2 == 0)
{
//Arrays for for each side of the median
int arraySize = numberOfDatumsFloat/2;
float leftArray[numberOfDatums/2];
float rightArray[numberOfDatums/2];
//Initialise arrays for each side of the median
for (int i = 0; i < numberOfDatums; i++)
{
if (i < numberOfDatums/2)
{
leftArray[i] = dataValues[i];
}
if (i >= numberOfDatums/2)
{
//leftArray SOMEHOW GETS CHANGED INSTEAD OF RIGHT ARRAY
rightArray[i] = dataValues[i];
leftArray gets changed instead of rightArray here: rightArray[i] = dataValues[i];
}
}
}
if (numberOfDatums % 2 == 0.5)
{
//Not relevant, isn't triggered when problem occurs
}
return interquartileRange;
}
I am running Xcode 10.1, and want to know how to fix this error so that rightArray is changed by the function instead of leftArray.
Having
float leftArray[numberOfDatums/2];
float rightArray[numberOfDatums/2];
in
if (i >= numberOfDatums/2)
{
//leftArray SOMEHOW GETS CHANGED INSTEAD OF RIGHT ARRAY
rightArray[i] = dataValues[i];
you go out of rightArray and randomly write in leftArray (of course this is an undefined behavior)
must be
if (i >= numberOfDatums/2)
{
rightArray[i - numberOfDatums/2] = dataValues[i];
Furthermore, to have
if (i < numberOfDatums/2)
{
...
}
if (i >= numberOfDatums/2)
with i unchanged is useless, the second if can be an else, but it is also better to do two for to not have to do numberOfDatums/2 all the times just to decide which array to use.

C++ Function Gives "Not all Control Paths Return A Value" Error

I am working on a function called add(BigDecimals c) which keeps getting an error that not all control paths are returning a value:
BigDecimal BigDecimal::add(BigDecimal c)
{
string fFirst = to_string(this->fraction()); //fraction part of the first number
string fSecond = to_string(c.fraction()); //fraction part of the second number
if (fFirst.length() < fSecond.length()) //fraction part of first/second number
{
string str(this->toString()); //convert fraction to string
for (unsigned int i = 0; i < fFirst.length() - fSecond.length(); i++) //difference between first and second
{
str += "0"; //pad in the 0's
}
this->equals(str); //call the equals function
}
if (fSecond.length() < fFirst.length()) //flip numbers around, second < first
{
string str(this->toString()); //convert fraction to string
for (unsigned int i = 0; i < fSecond.length() - fFirst.length(); i++) //difference between second and first
{
str += "0"; //pad in the 0's
}
this->equals(str); //call the equals function
}
for (unsigned int i = fSecond.length(); i > 0; i++)
{
int carryFlag = 0; //carry flag set to 0
int sum = carryFlag + stoi(this->at(i).toString()) + stoi(c.at(i).toString());
if (sum >= 10) //greater than 10
{
carryFlag = 1;
sum = sum % 10;
}
else //less than 10
{
carryFlag = 0; //set carry flag to 0
}
return BigDecimal(to_string(sum)); //this is the only thing I want to
//return
}
//It wants to return something here, but I am not sure what.
}
I have tried to fix this by replacing if statements with else statements, but nothing really works. I have no idea how to fix this error, so any help is appreciated!
Your logic is flawed (and the error message and the fact you don't know what to do about it is a good indication of that).
Your code will always return on the first iteration of the loop. Clearly what you want to do is accumulate a digit string one digit at a time, but that's not what the code you've written does.
This is something more like what you want. However I think you have other errors to do with the padding of numbers, so this code isn't going to work, but hopefully will give you some idea.
string result = "";
int carryFlag = 0; //carry flag set to 0
for (unsigned int i = fSecond.length(); i > 0; i--)
{
int sum = carryFlag + stoi(this->at(i).toString()) + stoi(c.at(i).toString());
if (sum >= 10) //greater than 10
{
carryFlag = 1;
sum = sum % 10;
}
else //less than 10
{
carryFlag = 0; //set carry flag to 0
}
result = to_string(sum) + result;
}
if (carryflag)
result = "1" + result;
return BigDecimal(result);
Notice the return is only after the loop has finished, and a new variable called result accumulates the digit generated each time round the loop.
Also notice the carryflag variable has been moved outside of the loop. The whole point of the carry is to hold the carry from one iteration of the loop to the next, so it can't be inside the loop. Also if there is a carry left over after all the digits have been added, you need to add a one digit to the beginning of the result.
Also I've changed i++ to i-- in the loop. You are iterating backwards through the strings you are adding so you need i--. It's an improvment but as I said before I still think this loop is wrong.
Clearly you understand how to do long addition, but what you haven't mastered yet is how to translate that into code. You have to think very carefully and precisely about what you are asking the computer to do.

Sudoku Blanks - c++

I have to write a program that takes in a Sudoku square(with all slots filled) and randomly assigns 25 blanks to be filled in. This is what I have so far but because this code has the chance to generate the same position in the array more than once I'm getting a varying number of blanks(17-21). I'm wondering if there is a simple way to get it to output 25 blanks no matter what. My print function inserts a blank if the value is zero at any spot in the array.
void insertBlanks(int square[9][9])
{
srand(time(NULL));
int i = 0;
while(i < 25)
{
int tempOne = rand() % 9;
int tempTwo = rand() % 9;
square[tempOne][tempTwo] = 0;
i = i + 1;
}
}
You should check if a 0 is already there.
if(square[tempOne][tempTwo] != 0)
{
square[tempOne][tempTwo] = 0;
i = i + 1;
}

BFS maze help c++

I am attempting to make a maze-solver using a Breadth-first search, and mark the shortest path using a character '*'
The maze is actually just a bunch of text. The maze consists of an n x n grid, consisting of "#" symbols that are walls, and periods "." representing the walkable area/paths. An 'S' denotes start, 'F' is finish. Right now, this function does not seem to be finding the solution (it thinks it has the solution even when one is impossible). I am checking the four neighbors, and if they are 'unfound' (-1) they are added to the queue to be processed.
The maze works on several mazes, but not on this one:
...###.#....
##.#...####.
...#.#.#....
#.####.####.
#F..#..#.##.
###.#....#S.
#.#.####.##.
....#.#...#.
.####.#.#.#.
........#...
What could be missing in my logic?
int mazeSolver(char *maze, int rows, int cols)
{
int start = 0;
int finish = 0;
for (int i=0;i<rows*cols;i++) {
if (maze[i] == 'S') { start=i; }
if (maze[i] == 'F') { finish=i; }
}
if (finish==0 || start==0) { return -1; }
char* bfsq;
bfsq = new char[rows*cols]; //initialize queue array
int head = 0;
int tail = 0;
bool solved = false;
char* prd;
prd = new char[rows*cols]; //initialize predecessor array
for (int i=0;i<rows*cols;i++) {
prd[i] = -1;
}
prd[start] = -2; //set the start location
bfsq[tail] = start;
tail++;
int delta[] = {-cols,-1,cols,+1}; // North, West, South, East neighbors
while(tail>head) {
int front = bfsq[head];
head++;
for (int i=0; i<4; i++) {
int neighbor = front+delta[i];
if (neighbor/cols < 0 || neighbor/cols >= rows || neighbor%cols < 0 || neighbor%cols >= cols) {
continue;
}
if (prd[neighbor] == -1 && maze[neighbor]!='#') {
prd[neighbor] = front;
bfsq[tail] = neighbor;
tail++;
if (maze[neighbor] == 'F') { solved = true; }
}
}
}
if (solved == true) {
int previous = finish;
while (previous != start) {
maze[previous] = '*';
previous = prd[previous];
}
maze[finish] = 'F';
return 1;
}
else { return 0; }
delete [] prd;
delete [] bfsq;
}
Iterating through neighbours can be significantly simplified(I know this is somewhat similar to what kobra suggests but it can be improved further). I use a moves array defining the x and y delta of the given move like so:
int moves[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
Please note that not only tis lists all the possible moves from a given cell but it also lists them in clockwise direction which is useful for some problems.
Now to traverse the array I use a std::queue<pair<int,int> > This way the current position is defined by the pair of coordinates corresponding to it. Here is how I cycle through the neighbours of a gien cell c:
pair<int,int> c;
for (int l = 0;l < 4/*size of moves*/;++l){
int ti = c.first + moves[l][0];
int tj = c.second + moves[l][1];
if (ti < 0 || ti >= n || tj < 0 || tj >= m) {
// This move goes out of the field
continue;
}
// Do something.
}
I know this code is not really related to your code, but as I am teaching this kind of problems trust me a lot of students were really thankful when I showed them this approach.
Now back to your question - you need to start from the end position and use prd array to find its parent, then find its parent's parent and so on until you reach a cell with negative parent. What you do instead considers all the visited cells and some of them are not on the shortest path from S to F.
You can break once you set solved = true this will optimize the algorithm a bit.
I personally think you always find a solution because you have no checks for falling off the field. (the if (ti < 0 || ti >= n || tj < 0 || tj >= m) bit in my code).
Hope this helps you and gives you some tips how to improve your coding.
A few comments:
You can use queue container in c++, its much more easier in use
In this task you can write something like that:
int delta[] = {-1, cols, 1 -cols};
And then you simple can iterate through all four sides, you shouldn't copy-paste the same code.
You will have problems with boundaries of your array. Because you are not checking it.
When you have founded finish you should break from cycle
And in last cycle you have an error. It will print * in all cells in which you have been (not only in the optimal way). It should look:
while (finish != start)
{
maze[finish] = '*';
finish = prd[finish];
}
maze[start] = '*';
And of course this cycle should in the last if, because you don't know at that moment have you reach end or not
PS And its better to clear memory which you have allocate in function

weighted RNG speed problem in C++

Edit: to clarify, the problem is with the second algorithm.
I have a bit of C++ code that samples cards from a 52 card deck, which works just fine:
void sample_allcards(int table[5], int holes[], int players) {
int temp[5 + 2 * players];
bool try_again;
int c, n, i;
for (i = 0; i < 5 + 2 * players; i++) {
try_again = true;
while (try_again == true) {
try_again = false;
c = fast_rand52();
// reject collisions
for (n = 0; n < i + 1; n++) {
try_again = (temp[n] == c) || try_again;
}
temp[i] = c;
}
}
copy_cards(table, temp, 5);
copy_cards(holes, temp + 5, 2 * players);
}
I am implementing code to sample the hole cards according to a known distribution (stored as a 2d table). My code for this looks like:
void sample_allcards_weighted(double weights[][HOLE_CARDS], int table[5], int holes[], int players) {
// weights are distribution over hole cards
int temp[5 + 2 * players];
int n, i;
// table cards
for (i = 0; i < 5; i++) {
bool try_again = true;
while (try_again == true) {
try_again = false;
int c = fast_rand52();
// reject collisions
for (n = 0; n < i + 1; n++) {
try_again = (temp[n] == c) || try_again;
}
temp[i] = c;
}
}
for (int player = 0; player < players; player++) {
// hole cards according to distribution
i = 5 + 2 * player;
bool try_again = true;
while (try_again == true) {
try_again = false;
// weighted-sample c1 and c2 at once
// h is a number < 1325
int h = weighted_randi(&weights[player][0], HOLE_CARDS);
// i2h uses h and sets temp[i] to the 2 cards implied by h
i2h(&temp[i], h);
// reject collisions
for (n = 0; n < i; n++) {
try_again = (temp[n] == temp[i]) || (temp[n] == temp[i+1]) || try_again;
}
}
}
copy_cards(table, temp, 5);
copy_cards(holes, temp + 5, 2 * players);
}
My problem? The weighted sampling algorithm is a factor of 10 slower. Speed is very important for my application.
Is there a way to improve the speed of my algorithm to something more reasonable? Am I doing something wrong in my implementation?
Thanks.
edit: I was asked about this function, which I should have posted, since it is key
inline int weighted_randi(double *w, int num_choices) {
double r = fast_randd();
double threshold = 0;
int n;
for (n = 0; n < num_choices; n++) {
threshold += *w;
if (r <= threshold) return n;
w++;
}
// shouldn't get this far
cerr << n << "\t" << threshold << "\t" << r << endl;
assert(n < num_choices);
return -1;
}
...and i2h() is basically just an array lookup.
Your reject collisions are turning an O(n) algorithm into (I think) an O(n^2) operation.
There are two ways to select cards from a deck: shuffle and pop, or pick sets until the elements of the set are unique; you are doing the latter which requires a considerable amount of backtracking.
I didn't look at the details of the code, just a quick scan.
you could gain some speed by replacing the all the loops that check if a card is taken with a bit mask, eg for a pool of 52 cards, we prevent collisions like so:
DWORD dwMask[2] = {0}; //64 bits
//...
int nCard;
while(true)
{
nCard = rand_52();
if(!(dwMask[nCard >> 5] & 1 << (nCard & 31)))
{
dwMask[nCard >> 5] |= 1 << (nCard & 31);
break;
}
}
//...
My guess would be the memcpy(1326*sizeof(double)) within the retry-loop. It doesn't seem to change, so should it be copied each time?
Rather than tell you what the problem is, let me suggest how you can find it. Either 1) single-step it in the IDE, or 2) randomly halt it to see what it's doing.
That said, sampling by rejection, as you are doing, can take an unreasonably long time if you are rejecting most samples.
Your inner "try_again" for loop should stop as soon as it sets try_again to true - there's no point in doing more work after you know you need to try again.
for (n = 0; n < i && !try_again; n++) {
try_again = (temp[n] == temp[i]) || (temp[n] == temp[i+1]);
}
Answering the second question about picking from a weighted set also has an algorithmic replacement that should be less time complex. This is based on the principle of that which is pre-computed does not need to be re-computed.
In an ordinary selection, you have an integral number of bins which makes picking a bin an O(1) operation. Your weighted_randi function has bins of real length, thus selection in your current version operates in O(n) time. Since you don't say (but do imply) that the vector of weights w is constant, I'll assume that it is.
You aren't interested in the width of the bins, per se, you are interested in the locations of their edges that you re-compute on every call to weighted_randi using the variable threshold. If the constancy of w is true, pre-computing a list of edges (that is, the value of threshold for all *w) is your O(n) step which need only be done once. If you put the results in a (naturally) ordered list, a binary search on all future calls yields an O(log n) time complexity with an increase in space needed of only sizeof w / sizeof w[0].