Solving a Maze from .txt using C++ - c++

So, I am working on a code that should solve a maze to be given in a .txt file let's say "input.txt" where 1's = blocks and 0's = open paths in a form like this:
Maze1
7,6 //Number of rows and columns of the maze: row,column
1,1,1,1,1,1
1,0,1,1,0,1
1,0,0,0,0,1
1,0,1,1,0,0
1,0,1,1,0,1
1,1,0,0,1,1
1,1,1,1,1,1
1 // number of entrances
1,2 // coordinate of an entrance relative to the origin: row, column
So I have got some algorithm in my mind, but let's say the "1st" entrance is invalid...
so the output should be like this :
Maze1
Entrance: 1,2 Invalid
And this should be printed in another .txt file let's say "Output.txt".... but it actually gives me no syntax errors, yet it doesn't write anything to the Output.txt...
Anyways here's my "Incomplete-Code" ... so please help me :
#include <stdio.h>
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct Stack
{
int data[30]; //X should be constant
int top;
}; //Stack
void Push(int a,Stack &S)
{
S.top++;
if (S.top>=30) //Remember X should be constant
{
cout<<"The stack is full!"<<endl;
S.top--;
return;
}
else
{
S.data[S.top]=a;
}
} //Push
int Pop(Stack &S)
{
if (S.top==-1)
{
cout<<"The stack is empty!"<<endl;
return 0;
}
else
{
int Temp=S.data[S.top];
S.data[S.top]=NULL;
S.top--;
return Temp;
}
} //Pop
int main ()
{
#define false 1;
#define true 0;
string line;
Stack s1 = { NULL, -1 }, s2 = { NULL, -1 };
int x, y; //Dimensions of Matrix.
int z; //Element Location in Matrix.
int a; //Number of Entrance Points.
int b, c; //Coordinates of Entrance Points.
char ch; //Comma indication.
ifstream input ("Input.txt"); //Using relative addresses.
ofstream output ("Output.txt");
input>>line;
cout<<"Solution for "<<line<<" : \n \n \n";
input>>x>>ch>>y; //Reading the Dimensions of the Matrix.
cout<<line<<" coordinates are "<<x<<ch<<y<<endl<<endl<<endl;
int **Maze = new int *[x]; //Creating Dynamic Matrix.
for (int i=0; i<x; i++)
{
Maze[i]= new int [y];
}
for (int i=0; i<x; i++) //Filling the Maze from the .txt
{
for (int j=0; j<y; j++)
{
input>>z;
Maze[i][j]=z;
}
}
input>>a; //Reading the number of entrances.
for(int i=0; i<a; i++)
{
input>>b>>ch>>c; //Reading the entrance coordinates.
if (Maze[b][c]==1 || b>7 || c>6) //Checking for the validity of entrance point.
{
cout<<"Entrance: "<<b<<ch<<c<<" is Invalid! \n";
output<<"Entrance: "<<b<<ch<<c<<" is Invalid! \n";// WRITE ENTRANCE IS INVALID IN OUTPUT FILE
}
}
output.close();
input.close();
for(int i=0; i<x; i++) //Deleting Maze
{
delete[] Maze[i];
}
delete[] Maze;
return 0;
}
So where's the mistake ?

Arrays in C++ are 0-indexed - that is, Maze[1][2] is the cell in the second row, third column. Either number your entrance cell like that in the input file, or subtract 1 from each co-ord in the code.
Also, when parsing the maze itself, you don't seem to be taking account of the commas.

Related

Why am I getting a segfault trying to add element to vector<vector<int>>(matrix implementation)?

I have included a description of my C++ program a little further down, but I feel like the problem might be so basic the description is unnecessary. Essentially, I'm getting a segfault in my "parse_matrix" method. I've done some debugging and marked the line where the run ends, but I can't figure out what exactly is wrong. What I'm trying to do in the line is to use cin to grab a number from the input file and put it into a matrix (implemented as a vector< vector< int >>) at index [i][j]. I've tried different ways to set the value in the matrix (first
Here's the program description:
I am writing a program that basically will take an input file containing information on matrices and an operation to perform, and will output the resulting matrix. The first line in the input file will say either "add" or "multiply", the second line will say how many matrices there will be. Then, there will be two lines for each matrix, the first of which has two numbers separated by a space that determine the dimension (rows columns) of the following matrix, whose contents will be written in a single line and grouped into rows (so a 2x2 matrix would be A(1,1) A(1,2) A(2,1) A(2,2) (1,1 is the top left, 1,2 is the top right, 2,1 is the bottom left, 2,2 is the bottom right).
An example input file, which tells the program to add 3 matrices, all of dimensions 2x2:
add
3
2 2
1 2 3 4
2 2
1 1 1 1
2 2
1 0 1 0
Here's my code (I've marked where the problem seems to be occuring). Any help would be greatly appreciated!
#include <iostream>
#include <cstdio>
#include <cmath>
#include <vector>
using namespace std;
//define dot product
int dot(vector<int> a, vector<int> b){
int c=0;
int size = a.size();
for (int i=0; i<size; i++){
c += a[i]*b[i];
}
return c;
}
//define Matrix struct
struct Matrix {
vector<vector<int>> mtrx;
int m;
int n;
//overloading "+" for adding matrices
Matrix operator+ (const Matrix& b){
Matrix c;
for (int i=0; i<b.m; i++){
for (int j=0; j<b.n; j++){
c.mtrx[i][j] = this->mtrx[i][j] + b.mtrx[i][j];
}
}
return c;
}
//overloading "*" for multiplying matrices
Matrix operator* (const Matrix& b){
Matrix c;
for (int i=0; i<b.m; i++){
for (int j=0; j<b.n; j++){
vector<int> temp;
for (int k=0; k<b.m; k++){
temp.push_back(b.mtrx[k][j]);
}
c.mtrx[i][j] = dot(this->mtrx[i],temp);
}
}
c.n = b.n;
return c;
}
};
//will apply the designated operation to two matrices
Matrix operation(Matrix a, Matrix b, string op_type){
Matrix c;
if (op_type=="add"){
if (a.m == b.m && a.n == b.n) {
c = a+b;
}
else {
cout<<"Dimensions do not match. Addition cannot be performed.";
exit(1);
}
}
else if (op_type == "multiply"){
if (a.n == b.m){
c = a*b;
}
else {
cout<<"Inner dimensions do not match. Multiplication cannot be performed.";
exit(1);
}
}
else {
cout<<"This program does not "<<op_type<<" matrices. It only adds or multiplies.";
exit(1);
}
return c;
}
//reads line and sets matrix elements
void parse_matrix(Matrix *p){
int m,n;
cin>>m>>n;
p->m = m;
p->n = n;
for (int i=0; i<m; i++) {
for (int j=0; j<n; j++){
int x;
cin>>x;
/************THIS IS WHERE THE SEGFAULT OCCURS***************/
((p->mtrx)[i]).push_back(x);
}
}
}
//prints matrix elements in a line (row, column) lexicographical ordering using cout
void print_matrix(Matrix matrix){
int m = matrix.m;
int n = matrix.n;
for (int i=0; i<m; i++) {
for (int j=0; j<n; j++){
cout<<matrix.mtrx[i][j];
}
cout<<endl;
}
}
//main will read in type of operation, number of matrices, and individual matrices
//each matrix resides on a line, and will be parsed into rows and columns
//each matrix line will be preceded by a line of two ints that specifies the matrix dimensions
int main() {
string op_type;
cin>>op_type;
int num;
cin>>num;
Matrix matrix;
Matrix final;
parse_matrix(&final);
for (int k=1; k<num; k++) {
parse_matrix(&matrix);
operation(final, matrix, op_type);
}
print_matrix(final);
return 0;
}
This code has a problem:
Matrix c;
...
c.mtrx[i][j] =
This accesses out of bounds. c.mtrx was created as a 0x0 matrix but you try to access indices i,j. The [] operator does not automatically expand the size of the vector.
The line you marked probably has the same issue:
((temp.mtrx)[i]).push_back(x);
Your code does not show what temp is but probably it's a global variable that does not have as many as i rows yet.
Instead you need to make sure that a vector entry at index [i] already exists before you try writing to its value. You can use push_back as an alternative.

allocation error in c++

I have this following code to sort number which I read from text file. My text file elements must be like this:
3 6
6
5
1
The first number (3) in the first column represents the number of elements that should I sort, the first number in second column represent the max number which I have to send via array which is 6 here.
And the number must be sorted is 6 5 1.
So this is my code but there is error says "invalid allocation size" and how to send max via array.
I need help please.
Here is my code:
// Read and Sort.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
#include<fstream>
using namespace std ;
#include<time.h>
#include <string>
int Max ;
int number_of_items;
const int s= 22;
int arr[s];
int n=sizeof(arr)/sizeof(*arr);
class sort{
public:
int read_file()
{
int num = 0;
int x ;
char filename[50];
ifstream numbersfile ;
cout<<"Please enter the file name below"<<endl<<"_______________________________________________"<<endl;
cin.getline(filename,50);
cout<<"_______________________________________________"<<endl;
numbersfile.open(filename);
if(numbersfile.is_open())
{
for(int i =0;i<n;i++){
numbersfile>>arr[i];
Max=arr[0];
number_of_items=arr[1];
}
}
else{
cout<<"Failed To load requierd file"<<endl;
}
int arr2[s];
cout<<"The elements supposed to be sorted are:"<<endl<<endl;
for(int i =2;i<n;i++){
numbersfile>>arr[i];
cout<<arr[i]<<" "<<endl;
}
counting_sort(arr2,n);
return 0 ;}
int counting_sort(int arr[],int size)
{
int n=size;
int max=arr[0];
for (int i=1;i<n;i++) {
if (arr[i]>max) {
max=arr[i];
}
}
int *output_array=new int[n];
for (int i=0;i<n;i++) {
output_array[i]=0;
}
int *count=new int[max+1];
for (int i=0;i<=max+1;i++) {
count[i]=0;
}
for (int i=0;i<n;i++){
count[arr[i]]=count[arr[i]]+1;
}
for (int i=1;i<max+1;i++) {
count[i]=count[i]+count[i-1];
}
for (int i=n-1;i>=1;i--) {
output_array[count[arr[i]]-1]=arr[i];
count[arr[i]]=count[arr[i]]-1;
}
cout<<"The sorted elements are:"<<endl<<endl;
for (int i=0;i<n;i++) {
cout<<output_array[i]<<" ";
}
cout<<"\n-----------------------------------------------"<<endl;
return 0;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
clock_t t1,t2;
t1=clock();
sort s1;
s1.read_file();
t2 = clock();
float diff = ((float)t2 - (float)t1)/1000 ;
cout <<"The time taken to execute this process is:\n"<< diff<<" Milliseconds." << endl;
return 0;
}
int *count=new int[max+1];
for (int i = 0; i <= max+1;i++) {
count[i]=0;
}
Note that here you goes out of range, because you try to access the last element as count[max+1], because the <= in the conditional test, and this position is not allocated. It should be like this:
int *count=new int[max+1];
for (int i = 0; i < max+1;i++) {
count[i]=0;
}
I suggest to you to carefully check each for, looking if you aren't accessing some position not bounded/allocated. Use printf's or cout's to debug, this is really useful.

C++ I/O numbers in text file

I'm trying to read numbers from a test file and display them in a matrix. In the text file, there is one number per line. The first two lines are the dimensions of the matrix.(3 and 4) I'm having trouble assigning the actual data values of these numbers to the matrix. In this case Values 2 through 14.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <stdlib.h>
using namespace std;
#include "Matrix.h"
int main()
{
CMatrix A(10,10); //set to arbitrary size
int x;
int i = 0;
int number;
int rowsFile;
int columnsFile;
while ( myFile.good()&& myFile.is_open() )
{
myFile>>x;
if (i==0){ //for row dimension
rowsFile = x;
}
if (i==1){ //for column dimension
columnsFile = x;
}
cout<<"Value "<<i<<": "<<x<<endl; //displays the values
if (i>=2){
for (int r = 0; r < rowsFile; r++)
{
for (int c = 0; c < columnsFile; c++)
{
A.Value(r,c) = x;
myFile>>x;
}
}
myFile.close();
}
i=i+1;
}
myFile.close();
CMatrix A(rowsFile, columnsFile);
cout<<endl<< "Rows: "<<A.getNumberOfRows()<<endl;
cout<< "Columns: "<<A.getNumberOfColumns()<<endl;
cout<<endl<<A.ToString();
}
Here is a display of my output.
For some reason my commented out loop doesn't seem to be working.
Any help would be appreciated. Thank you!
While I can't offer you a complete solution due not completely understanding what you're trying to do, I recommend reading the contents of the file line wise and storing them in a vector, as in this example:
std::ifstream ifs("file.txt");
std::string line;
std::vector<std::string> lines;
if (ifs.good()) while (getline(ifs, line)) lines.push_back(line);
else throw std::runtime_error("An error occurred while trying to read from file.");
This makes it easier to work with the data.
I suggest you reorganize this code to place doubles into matrix elements immediately after reading them.
The file io code may not be perfect, but I would separate the reading of the number of rows and columns from the loop that handles the element values.
// do not declare i here
int numRows;
int numCols;
std::fstream inputFile("filename", std::in);
if ! (inputFile >> numRows >> numCols)
{
// Handle error
}
// Check that numRows and numCols are acceptable (positive)
// [not shown]
CMatrix A(numRows, numCols);
if (inputFile)
{
int elementsRead = 0;
for (int i = 0; i < numRows; i++)
{
for (int j = 0; j < numCols; j++)
{
double x;
if (inputFile >> x)
{
A.Value(i,j) = x;
++elementsRead;
} else {
// probably an error from too-short file,
// token could not be converted to double, etc.
// handle appropriately
break;
}
}
}
}
if (elementsRead != numRows * numCols)
{
// handle error
}
// Use matrix A

Reading from a data file to 2D array. No output. C++

I am new to programming and c++. I am working on an assignment which requires me to read data from a data file and store it into a 2D array. Every line in the text file is in the following format(data type is int)
XXXX XX XX XX XX ...(and so on)
The four digit number is actually student ID and is to be stored in a separate 1D array. I have done this part and I don't have any issues. Now the rest 2 digit numbers are to be stored in a 2D array with 4 columns and X rows, where X is the number of lines in the data file.
I have written the following code to try to read into the file. It gives no error and compiles correctly but when I try to print the 2D array, using cout, I don't get anything. Nothing. Please look at the following code and try to help me.
I am new to stackoverflow and programming so please forgive me if the code is not formatted correctly or is not as per the tradition.
//___CODE____
#include<iostream>
#include<iomanip>
#include<fstream>
#include<cstdlib>
#include<string>
using namespace std;
//Global
const int SIZE = 1000;
int const col = 4;
string fileName;
//Function Prototypes
int readId(int id[], int size);
int readScores(int scores[][col], int size);
//Main
int main()
{
int examScores[SIZE][col];
int id[SIZE] = {};
cout<<endl;
readId(id, SIZE);
readScores(examScores, SIZE);
}
//Declarations
int readId(int id[], int size)
{
ifstream inputFile;
int count = 0;
int total = 0; //Size of id [] OR no. of students.
int temp = 0;
//Takes the name of the data file from the user.
//NOTE: The filename should include its extension.
cout<<"Enter the name of the data file (including the extension):";
cin>>fileName;
inputFile.open(fileName.c_str());
if(inputFile.is_open())
{
while(inputFile >> temp)
{
if(count % 5 == 0)
{
id[total] = temp;
total++;
}
++count;
}
}
else
cout<<"Data file not found!"<<endl; // If this is executed make sure the data file
//is located in the same directory as this program.
//To print the content of array. Check.
for(int i=0; i < total; i++)
cout<<id[i]<<endl;
return total;
}
int readScores(int scores[][col], int size)
{
ifstream inputFile;
int count = 0;
int c = 0; //Counter for column.
int total = 0; //No. of students.
int temp = 0;
inputFile.open(fileName.c_str());
if(inputFile.is_open())
{
while(inputFile >> temp)
{
if(count % 5 != 0)
{
if (c < col)
{
scores[total][c] = temp;
}
else
total++;
c = 0;
scores[total][c] = temp;
}
++count;
c++;
}
}
else
cout<<"Data file not found!"<<endl; // If this is executed make sure the data file
//is located in the same directory as this program.
//To print the contents of 2D array. Check.
for (int r = 0; r < total; r++)
{
for (c = 0; c < col; c++)
{
cout<<setw(8)<<scores[r][col];
}
cout<<endl;
}
return total;
}
Your else-Statement is wrong, there are some brackets missing (now you always reset c to zero)

Filling 2-D arrays from user input

I have a bit of a problem, I am writing a program to ask the user to enter numbers for a Sudoku grid, and then store them in a 2-d array. I know how to print out the array to show the Sudoku grid, But I am having trouble getting the array elements set to the numbers that the user enters, can anyone help?
This is all that I have, which I know is not much but I have only ever done this with 1-d arrays before.
Code:
#include <iostream>
using namespace std;
void fillGrid1(int grid1, int sizeOfArray) {
for(int x = 0; x < sizeOfArray; x++) {
grid1[x][9] = x;
}
}
int main()
{
int grid1[9][9];
fillGrid1(grid1, 9);
for(int row = 0; row < 9; row++) {
for(int column = 0; column < 9; column++) {
cout << grid1[row][column] << " ";
}
cout << endl;
}
}
Here you have two functions, one to interactively fill the hole sudoku by getting the user input. The other for printing the sudoku. With the little information you gave it's what I think you seek:
#include <iostream>
#include <stdio.h>
#include<stdlib.h>
using namespace std;
void interactiveSudokuFill(int grid1[9][9]){
for(int y=0;y<9;y++){
for(int x=0;x<9;x++){
string theString;
cout<<"Write the value to prace in Sudoku["<<y<<"]["<<x<<"] :"<<endl;
std::getline(cin,theString);
int nr=atoi(theString.c_str());
grid1[y][x]=nr;
}
}
}
void printSudoku(int grid[9][9]){
for(int y=0;y<9;y++){
for(int x=0;x<9;x++){
cout<<"["<<grid[y][x]<<"]";
}
cout<<endl;
}
}
int main()
{
int grid1[9][9];
interactiveSudokuFill(grid1);
printSudoku(grid1);
}
There are other more safe/elegant ways of doing this(for example user input should have been checked before delievering it to atoi()), but this way is the simpler I can think of.
Firstly, you're taking in an int where you expect an array:
void fillGrid1(int grid1, int sizeOfArray)
// ^^^^^^^^^
This should be something of the form,
void fillGrid1(int grid1[9][9], int sizeOfArray)
Next is that you should use a nested loop to access the elements of the multidimensional array:
void fillGrid1(int grid1[9][9], int sizeOfArray)
{
for (int i = 0; i < sizeOfArray; ++i)
{
for (int k = 0; k < sizeOfArray; ++k)
{
grid1[i][k] = x; // shouldn't x be the number the user entered?
}
}
}
You should also zero-fill your array:
int grid1[9][9] = {0};