I am new to c++ and need help making my maze look better. I want to use unicode characters but my program crashes. Here is a picture of my random maze. image of my maze
You can check my code here
#include <iostream>
#include <ctime>
#include <cstring>
using std::cout;
using std::fill;
using std::endl;
using std::cin;
using std::cout;
int main()
{
srand(time(NULL));
int arr_x[1000] = { 0 }; fill(arr_x + 0, arr_x + 1000, -1);
int arr_y[1000] = { 0 }; fill(arr_y + 0, arr_y + 1000, -1);
//coordinates used to go back when the generation runs into blocked path
char arr[100][100]; memset(arr, '#', sizeof(char) * 100 * 100);
//creating 100x100 char array of #
int rows, cols = 0;
cout << "Rows "; cin >> rows;//choose
cout << "Columns"; cin >> cols;
int random_number = 0; int x = 0; int y = 0; int index = 0;
arr[0][0] = ' ';
while (1)
{
random_number = rand() % (4) + 1;
int available_paths = 0;
if (x + 1 >= 0 && x + 1 < rows && arr[x + 1][y] != ' ' && arr[x + 2][y] != ' ' && arr[x + 1][y + 1] != ' ' && arr[x + 1][y - 1] != ' ') { available_paths++; if (random_number == 1) { x = x + 1; arr_x[index] = x; arr_y[index] = y; arr[x][y] = ' '; index++; } }
if (x - 1 >= 0 && x - 1 < rows && arr[x - 1][y] != ' ' && arr[x - 2][y] != ' ' && arr[x - 1][y + 1] != ' ' && arr[x - 1][y - 1] != ' ') { available_paths++; if (random_number == 2) { x = x - 1; arr_x[index] = x; arr_y[index] = y; arr[x][y] = ' '; index++; } }
if (y + 1 >= 0 && y + 1 < cols && arr[x][y + 1] != ' ' && arr[x][y + 2] != ' ' && arr[x + 1][y + 1] != ' ' && arr[x - 1][y + 1] != ' ') { available_paths++; if (random_number == 3) { y = y + 1; arr_x[index] = x; arr_y[index] = y; arr[x][y] = ' '; index++; } }
if (y - 1 >= 0 && y - 1 < cols && arr[x][y - 1] != ' ' && arr[x][y - 2] != ' ' && arr[x + 1][y - 1] != ' ' && arr[x - 1][y - 1] != ' ') { available_paths++; if (random_number == 4) { y = y - 1; arr_x[index] = x; arr_y[index] = y; arr[x][y] = ' '; index++; } }
if (available_paths == 0) //if available_paths are 0 I need to go
{ //back to the last visited square
index = index - 1;
if (index < 0) { break; }
x = arr_x[index]; y = arr_y[index];
}
}
for (int x = 0; x < rows; x++)
{
for (int y = 0; y < cols; y++)
{
cout << "[" << arr[x][y] << "]";
if (y == (cols - 1)) { cout << endl; }
}
}
int end;
cin >> end;
}
I am thinking about using this character - ▮. Is there any simple way to improve my algorithm?
Related
I have a 2d char array, of which I am trying to retrieve the value of an opposite side while on the edge. Instead of retrieving that value, it keeps returning with null. Can't make heads or tails of what the problem is. Here is the code I traced the problem to.
int xO = x; int yO = y;
//reassigns to opposite side of array
if ((x == 0) && (xM == - 1)) { xM = mapSize - 1; }
if ((x == mapSize - 1) && (xM == 1)) { xM = 0 - (mapSize - 1); }
if ((y == 0) && (yM == - 1)) { yM = mapSize - 1; }
if ((y == mapSize - 1) && (yM == 1)) { yM = 0 - (mapSize - 1);
}
//Checks 9 chars around and assigns any found characters
if (mapPlates[x + xM][y + yM] == 0) {
std::cout << "//" + std::to_string(x + xM) + ", " + std::to_string(yM + y) + "; " + std::to_string(mapPlates[x + xM][y + yM]) + "//";
}
if (mapPlates[x + xM][y + yM] =! "%") {
remaining--;
mapPlates[xO][yO] = mapPlates[x + xM][y + yM];
std::cout << "{assigned " + std::to_string(mapPlates[xO][yO]) + " }";
}
return remaining;
}
Snippet of output(only returns values == null)(should be returning '%'):
```//14, 49; 0////14, 0; 0////14, 1; 0////19, 49; 0////20, 49; 0////19, 0;
Given an arbitrary matrix, how do I find the co-ordinates that surrounds each city accurately?
E.g. City 1 has surrounding matrix of (0, 0), (0, 3), (1, 0), (1, 3), (2,0), (2, 1), (2, 2), (2, 3).
I have tried using a hardcoded method. Which is loop through each city's co-ordinate, however there are still inaccuracy in this method.
E.g. (0, 1) and from there check all 8 directions, up, down, left, right, upper left, upper right, bottom left, bottom right.
And if the char value is ' ', it is not a city which means it is part of a surrounding.
Is there any way which is much more efficient and more accurate in finding the surrounding?
void surroundings(int x, int y) {
// Initiate the first city struct information
citySummInfo.cityId = cityLocList[0].cityId;
citySummInfo.cityName = cityLocList[0].cityName;
citySummInfoList.push_back(citySummInfo);
// Add unique cityID & cityName into vector
for (size_t i = 0; i < cityLocList.size(); i++) {
for (size_t j = 0; j < citySummInfoList.size(); j++) {
if (cityLocList[i].cityId == citySummInfoList[j].cityId && cityLocList[i].cityName == citySummInfoList[j].cityName) {
break;
}
else if (j == citySummInfoList.size() - 1) {
citySummInfo.cityId = cityLocList[i].cityId;
citySummInfo.cityName = cityLocList[i].cityName;
citySummInfoList.push_back(citySummInfo);
}
}
}
// To populate the entire matrix with city ID
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
for (size_t k = 0; k < cityLocList.size(); k++) {
if (cityLocList[k].xGrid == i && cityLocList[k].yGrid == j)
mapPtr[j][i] = cityLocList[k].cityId + '0';
}
}
}
// Main process of getting the surrounding
for (size_t i = 0; i < citySummInfoList.size(); i++) {
for (size_t j = 0; j < cityLocList.size(); j++) {
if (citySummInfoList[i].cityId == cityLocList[j].cityId)
citySummInfoList[i].coOrdinates.push_back(to_string(cityLocList[j].xGrid) + "." + to_string(cityLocList[j].yGrid));
}
}
for (size_t i = 0; i < citySummInfoList.size(); i++) {
vector<string> temp;
for (size_t j = 0; j < citySummInfoList[i].coOrdinates.size(); j++) {
char cityId = citySummInfoList[i].cityId + '0';
char delim[] = { '.' };
vector<string> tempAxis = tokenizer(citySummInfoList[i].coOrdinates[j], delim, 1);
int xAxis = stoi(tempAxis[0]);
int yAxis = stoi(tempAxis[1]);
if (xAxis - 1 < 0 || yAxis - 1 < 0) {
continue;
}
if (mapPtr[xAxis - 1][yAxis + 1] != cityId) {
if (xAxis + 1 == x || yAxis + 1 == y || xAxis - 1 < 0 || yAxis - 1 < 0)
continue;
string coOrd = to_string(xAxis - 1) + "." + to_string(yAxis + 1);
if (find(temp.begin(), temp.end(), coOrd) == temp.end()) {
temp.push_back(coOrd);
}
}
if (mapPtr[xAxis - 1][yAxis] != cityId) {
if (xAxis + 1 == x || yAxis + 1 == y || xAxis - 1 < 0 || yAxis - 1 < 0)
continue;
string coOrd = to_string(xAxis - 1) + "." + to_string(yAxis);
if (find(temp.begin(), temp.end(), coOrd) == temp.end()) {
temp.push_back(coOrd);
}
}
if (mapPtr[xAxis - 1][yAxis - 1] != cityId) {
if (xAxis + 1 == x || yAxis + 1 == y || xAxis - 1 < 0 || yAxis - 1 < 0)
continue;
string coOrd = to_string(xAxis - 1) + "." + to_string(yAxis - 1);
if (find(temp.begin(), temp.end(), coOrd) == temp.end()) {
temp.push_back(coOrd);
}
}
if (mapPtr[xAxis][yAxis + 1] != cityId) {
if (xAxis + 1 == x || yAxis + 1 == y || xAxis - 1 < 0 || yAxis - 1 < 0)
continue;
string coOrd = to_string(xAxis) + "." + to_string(yAxis + 1);
if (find(temp.begin(), temp.end(), coOrd) == temp.end()) {
temp.push_back(coOrd);
}
}
if (mapPtr[xAxis][yAxis - 1] != cityId) {
if (xAxis + 1 == x || yAxis + 1 == y || xAxis - 1 < 0 || yAxis - 1 < 0)
continue;
string coOrd = to_string(xAxis) + "." + to_string(yAxis - 1);
if (find(temp.begin(), temp.end(), coOrd) == temp.end()) {
temp.push_back(coOrd);
}
}
if (mapPtr[xAxis + 1][yAxis + 1] != cityId) {
if (xAxis + 1 == x || yAxis + 1 == y || xAxis - 1 < 0 || yAxis - 1 < 0)
continue;
string coOrd = to_string(xAxis + 1) + "." + to_string(yAxis + 1);
if (find(temp.begin(), temp.end(), coOrd) == temp.end()) {
temp.push_back(coOrd);
}
}
if (mapPtr[xAxis + 1][yAxis] != cityId) {
if (xAxis + 1 == x || yAxis + 1 == y || xAxis - 1 < 0 || yAxis - 1 < 0)
continue;
string coOrd = to_string(xAxis + 1) + "." + to_string(yAxis);
if (find(temp.begin(), temp.end(), coOrd) == temp.end()) {
temp.push_back(coOrd);
}
}
if (mapPtr[xAxis + 1][yAxis - 1] != cityId) {
if (xAxis + 1 == x || yAxis + 1 == y || xAxis - 1 < 0 || yAxis - 1 < 0)
continue;
string coOrd = to_string(xAxis + 1) + "." + to_string(yAxis - 1);
if (find(temp.begin(), temp.end(), coOrd) == temp.end()) {
temp.push_back(coOrd);
}
}
}
citySummInfoList[i].coOrdinates.reserve(temp.size());
citySummInfoList[i].coOrdinates.insert(citySummInfoList[i].coOrdinates.end(), temp.begin(), temp.end());
}
}
Also, is there a possibility that my print function may cause such unreliability?
void print(int x, int y) {
for (int i = 0; i <= x + 2; i++) {
if (i == 0 || i >= x + 1) // Indentation for 1st and last row of non city locations
cout << setw(4) << " ";
for (int j = 0; j <= y + 2; j++) {
if ((i == 0 || i == x + 1) && j <= y + 1) { // Layout for first and last row
cout << "# ";
}
else if ((j == 0 && (i != 0 || i <= x))) { // Numbering for each row
if (x - i >= 0) {
cout << setw(3) << left << x - i << " ";
}
else {
cout << " "; // Indentation for last row of #s
}
}
else if (j == 1 && i < x + 2) { // Layout for first column
cout << "#";
}
else if (j == y + 2 && i != 0 && i < x + 1) { // Layout for last column
cout << " #";
}
else if (i == x + 2 && j < y + 1) { // Numbering for each column
cout << j - 1 << " ";
}
else if ((i != 0 && i != x + 2 && j != y + 2)) {
cout << " " << mapPtr[x - i][j - 2]; // Plot map value
}
}
cout << endl;
}
cout << endl;
}
This is an O(n) answer for your problem. The idea behind it is to find all points that are edges (a point is an edge if it is adjacent to anything which is not its own city).
After finding all edge points, loop through each of them and add all points adjacent to them which are whitespace characters.
#include <bits/stdc++.h>
#define x first
#define y second
using namespace std;
typedef pair<int, int> point;
string m[] = {
" ",
" 555 ",
" 555 ",
" 222 555 ",
" 222 ",
" 222 ",
" 222 ",
" ",
"11 33 ",
"11 44",
" 44"
};
//hash function for pairs
struct hash_pair {
template <class T1, class T2>
size_t operator()(const pair<T1, T2>& p) const {
auto hash1 = hash<T1>{}(p.first);
auto hash2 = hash<T2>{}(p.second);
return hash1 ^ hash2;
}
};
bool insideBounds(int x, int y, point &size){
if(x < 0 || x >= size.x || y < 0 || y >= size.y) return false;
return true;
}
bool isEdge(int x, int y, point &size){
for(int i = -1; i < 2; ++i){
for(int j = -1; j < 2; ++j){
if(!insideBounds(x + j, y + i, size)) return true;
if(m[y + i][x + j] == ' ') return true;
}
}
return false;
}
void FindSurrounding(int x, int y){
//size of map
point size = make_pair(11, 11);
//current city id
char city = m[y][x];
//finding a point in edge of the city
point edge = make_pair(x, y);
for(int i = x - 1; i >= 0; --i)
if(m[y][i] == city) edge = make_pair(i, y);
//find all edge points
unordered_set<point, hash_pair> visited;
stack<point> toVisit;
toVisit.push(edge);
while(toVisit.size()){
point current = toVisit.top();
visited.insert(current);
toVisit.pop();
for(int i = -1; i < 2; ++i){
for(int j = -1; j < 2; ++j){
point p = make_pair(current.x + j, current.y + i);
if(!insideBounds(p.x, p.y, size) || m[p.y][p.x] != city) continue;
if(visited.find(p) == visited.end() && isEdge(p.x, p.y, size)){
toVisit.push(p);
}
}
}
}
//find surrounding slots
unordered_set<point, hash_pair> surrounding;
for (const auto& p: visited) {
for(int i = -1; i < 2; ++i){
for(int j = -1; j < 2; ++j){
point curr = make_pair(p.x + j, p.y + i);
if(insideBounds(curr.x, curr.y, size) && m[curr.y][curr.x] == ' '){
surrounding.insert(curr);
}
}
}
}
//print answer
for (const auto& p: surrounding) {
cout<<"("<<p.x<<", "<<p.y<<"), ";
}
}
int main()
{
FindSurrounding(0, 8);
return 0;
}
OUTPUT: (2, 10), (1, 10), (2, 9), (0, 10), (2, 8), (2, 7), (1, 7), (0, 7),
Hello I have been attempting to add a scoring scheme which is 11 for internal gaps, 8 for terminal gaps on the 5 prime end, 7 for gaps on the 3' end, 4 for mismatches, 0 for matches. Currently the code only accounts for internal gap (= 11), mismatches(= 4) and matches (=0) but not for terminal gaps. Im fairly new to coding so I apologise in advance if my code is messy, any guidance is appreciated. I should be getting a score of 275.
The two sequences I used are included in the code.
#include <iostream>
#include <fstream>
#include <bits/stdc++.h>
using namespace std;
void getscore(string x, string y, int pxy, int pgap)
{
int i, j;
int m = x.length();
int n = y.length();
int dp[n+m+1][n+m+1] = {0};
for (i = 0; i <= (n+m); i++)
{
dp[i][0] = i * pgap;
dp[0][i] = i * pgap;
}
for (i = 1; i <= m; i++)
{
for (j = 1; j <= n; j++)
{
if (x[i - 1] == y[j - 1])
{
dp[i][j] = dp[i - 1][j - 1];
}
else
{
dp[i][j] = min({dp[i - 1][j - 1] + pxy ,
dp[i - 1][j] + pgap ,
dp[i][j - 1] + pgap });
}
}
}
int l = n + m;
i = m; j = n;
int xpos = l;
int ypos = l;
int xans[l+1], yans[l+1];
while ( !(i == 0 || j == 0))
{
if (x[i - 1] == y[j - 1])
{
xans[xpos--] = (int)x[i - 1];
yans[ypos--] = (int)y[j - 1];
i--; j--;
}
else if (dp[i - 1][j - 1] + pxy == dp[i][j])
{
xans[xpos--] = (int)x[i - 1];
yans[ypos--] = (int)y[j - 1];
i--; j--;
}
else if (dp[i - 1][j] + pgap == dp[i][j])
{
xans[xpos--] = (int)x[i - 1];
yans[ypos--] = (int)'_';
i--;
}
else if (dp[i][j - 1] + pgap == dp[i][j])
{
xans[xpos--] = (int)'_';
yans[ypos--] = (int)y[j - 1];
j--;
}
}
while (xpos > 0)
{
if (i > 0) xans[xpos--] = (int)x[--i];
else xans[xpos--] = (int)'_';
}
while (ypos > 0)
{
if (j > 0) yans[ypos--] = (int)y[--j];
else yans[ypos--] = (int)'_';
}
int id = 1;
for (i = l; i >= 1; i--)
{
if ((char)yans[i] == '_' && (char)xans[i] == '_')
{
id = i + 1;
break;
}
}
// Printing the final answer
cout << "Optimal score = ";
cout << dp[m][n] << "\n";
cout << "Optimal alignment :\n";
for (i = id; i <= l; i++)
{
cout<<(char)xans[i];
}
cout << "\n";
for (i = id; i <= l; i++)
{
cout << (char)yans[i];
}
return;
}
int main(){
string geneA = "TCTGGTGTCCTAGGCGTAGAGGAACCACACCAATCCATCCCGAACTCTGGTGGTTAAACTCTACTGCGGTGACGATACT ";
string geneB = "TGGTGCGGTCATACCAGCGCTAATGCACCGGATCCCATCAGAACTCCGCAGTTAAGCGCGCTTGGGCCAGAACAGTACTGGGATGGGTGTCC ";
int misMatchPenalty = 4;
int gapPenalty = 11;
int tPenalty=7;
int fPenalty=8;
getscore(geneA, geneB,
misMatchPenalty, gapPenalty);
return 0;
}
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
}
Please help me figure this out, I have tested it and tested it and re-read and re-wrote for the past 11 hours and I give up. I found a working code that someone else wrote, but it still doesn't explain to me why his works and mine doesn't because the problem that I am having works on his but not on mine
Got it people, code edited for anyone who has had a similiar problem...
The original code that I had is here http://pastebin.com/h7fXHKzf
the problem I was having was that it kept hanging up on the if(board[x][y - 1] == '.') checks.
Spoke too soon....The program will sometimes crash...it's rare but has crashed 3x in a row before...most of the time when I run it everything works.
// Chapter 8 Programming Project #9
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 10
#define PATH_SIZE ((int) (sizeof(brd_path)))
#define ROW_SIZE ((int) (sizeof(board) / sizeof(board[0])))
int main(void)
{
char board[SIZE][SIZE] = {};
char brd_path[25] = {'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O',
'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z'};
// 0 = Up, 1 = Down, 2 = Left, 3 = Right
bool path_dir_chk[4] = {false};
bool blocked = false;
unsigned short i, j, x = 0, y = 0;
// Generate a random number
srand((unsigned) time(NULL));
int dir = rand() % 4;
// Set all positions of board to '.'
for (x = 0; x < ROW_SIZE; x++) {
for (y = 0; y < ROW_SIZE; y++)
board[x][y] = '.';
}
x = 0;
y = 0;
board[0][0] = 'A';
// Generate the path
while (blocked != true && i != PATH_SIZE) {
for (i = 0; i < PATH_SIZE;) {
// Reset path_dir_chk values if empty
for (j = 0; j < 4; j++) {
if (board[x][y - 1] == '.')
path_dir_chk[0] = false;
if (board[x][y + 1] == '.')
path_dir_chk[1] = false;
if (board[x - 1][y] == '.')
path_dir_chk[2] = false;
if (board[x + 1][y] == '.')
path_dir_chk[3] = false;
}
// Check the direction and replace that char
switch (dir) {
case 0: if ((y - 1) >= 0 && board[x][y - 1] == '.') {
board[x][--y] = brd_path[i];
path_dir_chk[0] = true;
printf("I is now: %d\n", ++i);
} break;
case 1: if ((y + 1) >= 0 && board[x][y + 1] == '.') {
board[x][++y] = brd_path[i];
path_dir_chk[1] = true;
printf("I is now: %d\n", ++i);
} break;
case 2: if ((x - 1) >= 0 && board[x - 1][y] == '.') {
board[--x][y] = brd_path[i];
path_dir_chk[2] = true;
printf("I is now: %d\n", ++i);
} break;
case 3: if ((x + 1) >= 0 && board[x + 1][y] == '.') {
board[++x][y] = brd_path[i];
path_dir_chk[3] = true;
printf("I is now: %d\n", ++i);
} break;
}
// if all path's are true exit
if (path_dir_chk[0] == true &&
path_dir_chk[1] == true &&
path_dir_chk[2] == true &&
path_dir_chk[3] == true)
blocked = true;
// Reset the random direction
dir = rand() % 4;
}
}
// Print the board
for (x = 0; x < ROW_SIZE; x++) {
for (y = 0; y < ROW_SIZE; y++)
printf("%c ", board[x][y]);
printf("\n");
}
return 0;
}
OK I have made changes to reflect what I have so far, no it is printing 'I is now:' numbers 1 - 25 and then it starts over but it stops on 12 the second time around and freezes into some kind of loop
Below is the working code I found online, you can compare the two and see the similarity's but the lines of code on his that are exactly like mine do not work on mine.....
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 10
#define COLS 10
int main (void)
{
int i, j, k, direction;
char board[ROWS][COLS];
const char letters[] = {'A', 'B', 'C', 'D', 'E', 'F',
'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z'};
srand ((unsigned) time(NULL));
for (i = 0; i < ROWS; i++)
for (j = 0; j < COLS; j++)
board[i][j] = '.';
i = 0;
j = 0;
k = 1;
//set array[0][0] to first element
board[i][j] = letters[0];
while (k < 26) {
direction = rand() % 4;
if (board[i][j] == '.')
board[i][j] = letters[k++];
if ((board[i][j + 1] != '.' || j == ROWS - 1 )&&
(board[i + 1][j] != '.' || i == COLS -1) &&
(board[i - 1][j] != '.' || i == 0) &&
(board[i][j - 1] != '.' || j == 0))
break;
switch (direction) {
case 0: if (j < ROWS - 1 && board[i][j + 1] == '.'){ //move right
j++;
break; }
case 1: if (i < COLS -1 && board[i + 1][j] == '.') { //move down
i++;
break; }
case 2: if (i > 0 && board[i - 1][j] == '.'){ //move up
i--;
break; }
case 3: if (j > 0 && board[i][j - 1] == '.') { //move left
j--;
break; }
}
}
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++)
printf ("%4c", board[i][j]);
printf ("\n");
}
return 0;
}
You aren't setting x and y back to 0 after this code
for (x = 0; x < ROW_SIZE; x++) {
for (y = 0; y < ROW_SIZE; y++)
board[x][y] = '.';
}
Thus x and y will start at 10. Also you aren't range checking x and y, which means that x and y might wander off the board.
This code
if ((board[x][y - 1] != '.' || y - 1 < 0) &&
(board[x][y + 1] != '.' || y + 1 > ROW_SIZE) &&
(board[x - 1][y] != '.' || x - 1 < 0) &&
(board[x + 1][y] != '.' || x + 1 > ROW_SIZE))
should be this
if ((y - 1 < 0 || board[x][y - 1] != '.') &&
(y + 1 >= ROW_SIZE || board[x][y + 1] != '.') &&
(x - 1 < 0 || board[x - 1][y] != '.') &&
(x + 1 >= ROW_SIZE || board[x + 1][y] != '.'))
There are two subtle differences.
First y+1 and x+1 are not allowed to be equal to ROW_SIZE, since ROW_SIZE is 10, but the valid array indices are 0 to 9.
Second, order is important. When evaluating a logical OR, the left side is evaluated first, and if it's true, then the right side is not evaluated. This is important, since on some machines, even reading outside of the array bounds will cause a crash.
for (x = 0; x < ROW_SIZE; x++) {
for (y = 0; y < ROW_SIZE; y++)
board[x][y] = '.';
}
After the initialization you are not resetting the value of x and y. While value of X= ROW_SIZE, you are trying to access board[x + 1][y] and board[x][y + 1].
x = 0;
y = 0;
Thanks user3386109 your input was invaluable as was the rest of y'alls help I appreciate it, the working code is below :)
// Chapter 8 Programming Project #9
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 10
#define PATH_SIZE 25
#define ROW_SIZE ((int) (sizeof(board) / sizeof(board[0])))
int main(void)
{
char board[SIZE][SIZE];
// 0 = Up, 1 = Down, 2 = Left, 3 = Right
unsigned short i = 0, x, y;
// Generate a random number
srand((unsigned) time(NULL));
int dir = rand() % 4;
// Set all positions of board to '.'
for (x = 0; x < ROW_SIZE; x++) {
for (y = 0; y < ROW_SIZE; y++)
board[x][y] = '.';
}
x = 0;
y = 0;
board[0][0] = 'A';
// Generate the path
for (i = 0; i < PATH_SIZE;) {
// Check that the last character has not been cornered
if ((board[x][y - 1] != '.' || y - 1 < 0) &&
(board[x][y + 1] != '.' || y + 1 > ROW_SIZE) &&
(board[x - 1][y] != '.' || x - 1 < 0) &&
(board[x + 1][y] != '.' || x + 1 > ROW_SIZE))
break;
// Check the direction and replace that char
switch (dir) {
case 0: if ((y - 1) >= 0
&& board[x][y - 1] == '.') {
board[x][--y] = i + 'B';
++i;
} break;
case 1: if ((y + 1) < ROW_SIZE
&& board[x][y + 1] == '.') {
board[x][++y] = i + 'B';
++i;
} break;
case 2: if ((x - 1) >= 0
&& board[x - 1][y] == '.') {
board[--x][y] = i + 'B';
++i;
} break;
case 3: if ((x + 1) < ROW_SIZE
&& board[x + 1][y] == '.') {
board[++x][y] = i + 'B';
++i;
} break;
default: if (board[x][y] == '.')
board[x][y] = i + 'B';
break;
}
// Reset the random directions
dir = rand() % 4;
}
// Print the board
for (x = 0; x < ROW_SIZE; x++) {
for (y = 0; y < ROW_SIZE; y++)
printf("%4c ", board[x][y]);
printf("\n");
}
return 0;
}