I have a project to write a code that performs mathematical operations on matrices. The user inputs a matrix in the form of a string and then inputs an operator, if it's + or - or * or / then the user must enter another matrix...
So I wanted to make a function that performs each operation and I started with ADD function, but I get an error when I call it in the main.
Example of input matrix: [3 4 9;2 5 8;1 2 50]
Note: No extra spaces or semicolons should be printed out.
#include <iostream>
#include <string>
#include <cstring>
#include <sstream>
#include <cstdlib>
#include <algorithm>
using namespace std;
string ADD (float matrix1,float matrix2,int arraySize);
int main()
{
string s1; //first matrix
char op; //operator
string s2;//second matrix
int y; //for power operation
int n = 0; //number of rows of first matrix
int m = 0; //number of columns of first matrix
int o = 0; //number of rows of second matrix
int p = 0;//number of columns of second matrix
getline(cin, s1);
for (int i = 0; i < s1.size(); i++)
{
if (s1[i] == ';') n++;
}
for (int j = 0; j < s1.size(); j++)
{
if (s1[j] == ' ') m++;
}
n = n+1;
m = (m/n)+1;
s1.erase(0, 1); //to remove first bracket
for (int z = 0; z < s1.size(); z++) //to replace characters with a space
{
if (s1[z] == ';' || s1[z] == ']') s1[z] = ' ';
}
string token1;
float matrix1 [n*m];
for (int x = 0; x < n*m; x++)
{
token1 = s1.substr(0, s1.find(" "));
float v = atof(token1.c_str());
matrix1 [x] = v;
s1.erase(0, s1.find(" ")+1);
}
cout <<"Please Enter An Operator From The Following List: '+ - * ^ T D I /'" <<endl;
cin >> op;
if (op == '+' || op == '-' || op == '*' || op == '/')
{
cin.ignore(); getline (cin,s2);
}
else if (op == '^') cin >> y;
for (int f = 0; f < s2.size(); f++)
{
if (s2[f] == ';') o++;
}
for (int q = 0; q < s2.size(); q++)
{
if (s2[q] == ' ') p++;
}
o = o+1;
p = (p/o)+1;
s2.erase(0, 1); //to remove first bracket
for (int e = 0; e < s2.size(); e++) //to replace characters with a space
{
if (s2[e] == ';' || s2[e] == ']') s2[e] = ' ';
}
string token2;
float matrix2 [o*p];
float h;
for (int c = 0; c <o*p; c++)
{
token2 = s2.substr(0, s2.find(" "));
h = atof(token2.c_str());
matrix2 [c] = h;
s2.erase(0, s2.find(" ")+1);
}
if ( n == o && m == p && op == '+')
{
ADD(matrix1,matrix2,m*n) //Where I got the error Cannot convert 'float*' to 'float' for argument '1'
}
return 0;
}
string ADD (float matrix1[],float matrix2[],int arraySize)
{
string str;
for (int u = 0; u < arraySize; u++)
{
float matrix3[arraySize];
matrix3[u] = matrix1[u] + matrix2[u];
ostringstream ss;
ss << matrix3;
str = ss.str();
return str;
}
cout <<str;
}
Your forward declaration doesn't match your function definition:
string ADD (float matrix1,float matrix2,int arraySize);
and
string ADD (float matrix1[],float matrix2[],int arraySize)
{
...
}
Simply change your forward declaration to match the definition.
Related
I created code to convert graph representation (A list of edges -> the adjacency list)
How can i fix error?
I have Segmentation fault in line res[cur.first - 1].insert(cur.second);for input
4 3
3 2
2 1
4 2
My code
#include <bits/stdc++.h>
using namespace std;
pair<int, int> strToSotredPair(const string& s) {
int a = 0, b = 0;
int pos = 0;
while (s[pos] != ' ') {
a = a * 10 + s[pos] - '0';
++pos;
}
while (pos < s.size()) {
b = b * 10 + s[pos] - '0';
++pos;
}
return {min(a, b), max(a, b)};
}
int main() {
int n, m;
string input;
cin >> n;
cin >> m;
vector<set<int>> res(n, set<int>());
for (int i = 0; i < m; ++i) {
cin >> input;
auto cur = strToSotredPair(input);
res[cur.first - 1].insert(cur.second); // error in this line
}
for (int i = 0; i < res.size(); ++i) {
cout << res[i].size() << ' ';
for (auto item : res[i]) {
cout << item << ' ';
}
cout << endl;
}
}
There are a couple of error's in your code because of which you were getting that error.
You wanted the graph edges as strings. So you need to take edge inputs as strings. For that, you would be required to use getline(cin,input) and cin.ignore().
(My suggestion: Do not take inputs as strings because as it is you are converting them to integers afterwards. By default if you just write cin<<node1<<node2; the two nodes of an edge would have come as integers and function strToSotredPair would not be needed).
In function strToSotredPair after you get the integer a, pos variable is pointing to the space. So you need to increase it by 1 to point to the starting position to 2nd number. Hence a pos++ was needed.
#include <bits/stdc++.h>
using namespace std;
pair<int, int> strToSotredPair(const string& s) {
int a = 0, b = 0;
int pos = 0;
while (s[pos] != ' ') {
a = a * 10 + s[pos] - '0';
++pos;
}
pos++;
while (pos < s.size()) {
b = b * 10 + s[pos] - '0';
++pos;
}
return {min(a, b), max(a, b)};
}
int main() {
int n, m;
string input;
cin >> n;
cin >> m;
vector<set<int>> res(n, set<int>());
cin.ignore(); // To clear the input buffer
for (int i = 0; i < m; ++i) {
getline(cin, input); // to get line by line string inputs
auto cur = strToSotredPair(input);
res[cur.first - 1].insert(cur.second);
}
for (int i = 0; i < res.size(); ++i) {
cout << res[i].size() << ' ';
for (auto item : res[i]) {
cout << item << ' ';
}
cout << endl;
}
}
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
char* typein(char* text)
{
int count=0;
ifstream srcFile("in.txt", ios::in);
if (!srcFile)
{
cout << "error opening source file." << endl;
return 0;
}
char x;
while (srcFile >> x)
{
if (x >= 'a' && x <= 'z')
text[count] = x;
else if (x >= 'A' && x <= 'Z')
text[count] = x + 32;
else
text[count] = ' ';
count++;
}
srcFile.close();
return text;
}
double cal1(double* all1,char* text)
{
int t,count=0;
while(all1[count])
{
t = all1[count] - 'a' ;
count++;
if (t >= 0 && t <= 25)
all1[t]++;
else
all1[26]++;
}
all1[27] =count ;
double p, cal1 = 0;
for (t = 0; t <= 26; t++)
{
p = (all1[t] / all1[27]);
all1[t] = p * log(p);
}
for (t = 0; t <= 26; t++)
{
cal1 -= all1[t];
}
return cal1;
}
int main()
{
char *text = new char[30000]();
double *all = new double[28]();
double t2,result1=0,result2=0;
text = typein(text);
result1 = cal1(all,text);
cout <<result1 << endl;
delete[] all;
delete[] text;
return 0;
}
from a period of code that calculate a double number ,instead of receiving a number from the result, I still got a “-nan.(ind)” which is not a number. Besides, I have used the function of double *all = new double28,but there is still no error or bugs showing up.
Loop while(all1[count]) never would be executed because all elements of array are zero.
Therefore count is zero, all1[27] is zero.
Therefore p = all1[t] / all1[27] is 0.0/0.0, which is NaN, so only value you able to write into array is NaN.
There is the problem:
The first man 'g' (who starts first) has to reach the final box 'e', so that the second man 'l' (whenever he do) could't catch the first man. The men can go left, right, up, down or can stay.
For example:
Input:
6 7
RRRRRRR
R_e___R
R_____R
R_RRR_R
R_gRl_R
RRRRRRR
The answer is "YES" because there is the way (Left, Up, Up, Up, Right).
How this problem can be implemented?
I'm using BFS and DFS.
Here is my code
#include <iostream>
#include <algorithm>
#include <stack>
#include <math.h>
#include <cstring>
#include <map>
#include <queue>
using namespace std;
const int MAX = 32;
char a[MAX][MAX];
int used[MAX][MAX], m1[MAX][MAX], m2[MAX][MAX];;
int movesx[8] = {-1, 1, 0, 0};
int movesy[8] = { 0, 0, -1, 1};
int n, m, c = 0, flag = 0;
struct pc {
int x, y;
};
pc li, ga, fi;
queue <pc> q;
void BFS1(pc v) {
pc from, to;
memset(m1,0,sizeof(m1)); m1[v.y][v.x] = 0;
memset(used, 0, sizeof(used));
q.push(v); used[v.y][v.x] = 1;
while(!q.empty())
{
from = q.front(); q.pop();
for(int i = 0; i < 4; ++i) {
int x = from.x + movesy[i], y = from.y + movesx[i];
if( (a[y][x] == ' ' || a[y][x] == 'g' ) && !used[y][x]) {
used[y][x] = 1;
m1[y][x] = m1[from.y][from.x] + 1;
pc temp;
temp.x = x;
temp.y = y;
q.push(temp);
}
}
}
}
void BFS2(pc v) {
pc from, to;
memset(m2,0,sizeof(m2)); m2[v.y][v.x] = 0;
memset(used, 0, sizeof(used));
q.push(v); used[v.y][v.x] = 1;
while(!q.empty())
{
from = q.front(); q.pop();
for(int i = 0; i < 4; ++i) {
int y = from.y + movesy[i], x = from.x + movesx[i];
if( (a[y][x] == ' ' || a[y][x] == 'l' ) && !used[y][x]) {
used[y][x] = 1;
m2[y][x] = m2[from.y][from.x] + 1;
pc temp;
temp.x = x;
temp.y = y;
q.push(temp);
}
}
}
}
void DFS(pc v) {
used[v.y][v.x] = 1;
for(int i = 0; i < 4; ++i) {
int x = v.x + movesx[i], y = v.y + movesy[i];
if(a[y][x] == 'e') {
c = 1;
flag = 1;
return;
}
if( (a[y][x] == ' ' ) && !used[y][x] && m2[y][x] < m1[y][x] && flag == 0 ) {
pc temp;
temp.x = x;
temp.y = y;
DFS(temp);
}
}
}
int main() {
c = 0, flag = 0;
memset(used, 0, sizeof(used));
memset(a, 'R', sizeof(a));
cin >> n >> m;
string s;
getline(cin, s);
for(int i = 0; i < n; ++i) {
getline(cin, s);
for(int j = 0; j < m; ++j) {
a[i][j] = s[j];
if(a[i][j] == 'g') {
ga.x = j;
ga.y = i;
}
else if(a[i][j] == 'l') {
li.x = j;
li.y = i;
}
else continue;
}
}
BFS1(li);
BFS2(ga);
memset(used, 0, sizeof(used));
DFS(ga);
if(c == 1) {
cout << "YES" << endl;
}
else {
cout << "NO" << endl;
}
}
Here is the second code:
#include <iostream>
#include <algorithm>
#include <stack>
#include <math.h>
#include <cstring>
#include <map>
#include <queue>
using namespace std;
const int MAX = 32;
char a[MAX][MAX];
int used[MAX][MAX], m1[MAX][MAX], m2[MAX][MAX];;
int an[1002][MAX][MAX];
int movesx[8] = {-1, 1, 0, 0, 0};
int movesy[8] = { 0, 0, -1, 1, 0};
int n, m, c = 0, flag = 0;
struct pc {
int x, y;
};
pc li, ga;
void functionD() {
for(int z = 1; z <= 1000; ++z) {
for(int i = 0; i < n; ++i) {
for(int j = 0; j < n; ++j) {
if(an[z - 1][i][j] == 1) {
int x, y;
for(int k = 0; k < 5; ++k) {
x = j + movesx[k];
y = i + movesy[k];
if(x < m && y < n && x >= 0 && y >= 0) {
if(a[y][x] != 'R' && a[y][x] != 'e') {
an[z][y][x] = 1;
}
}
}
}
}
}
}
}
void DFS(pc v, int k) {
used[v.y][v.x] = 1;
for(int i = 0; i < 5; ++i) {
int x = v.x + movesx[i], y = v.y + movesy[i];
if(a[y][x] == 'e') {
c = 1;
flag = 1;
return;
}
if(an[k][y][x] == 0 && a[y][x] != 'R' && !used[y][x] && flag == 0 && k <= 1000) {
pc temp;
temp.x = x;
temp.y = y;
DFS(temp, k + 1);
}
}
}
int main() {
int nn; cin >> nn;
for(int z = 0; z < nn; ++z) {
c = 0, flag = 0;
memset(used, 0, sizeof(used));
memset(a, 'R', sizeof(a));
cin >> n >> m;
string s;
getline(cin, s);
for(int i = 0; i < n; ++i) {
getline(cin, s);
for(int j = 0; j < m; ++j) {
a[i][j] = s[j];
if(a[i][j] == 'g') {
ga.x = j;
ga.y = i;
}
else if(a[i][j] == 'l') {
li.x = j;
li.y = i;
}
}
}
an[0][li.y][li.x] = 1;
functionD();
DFS(ga, 1);
if(c == 1) {
cout << "YES" << endl;
}
else {
cout << "NO" << endl;
}
}
}
EDIT (By Jarod42):
I found a tricky map which failed:
9 9
RRRRRRRRR
R...Rg..R
R.RlRRR.R
R.R...R.R
R.RRR.R.R
R.Re....R
R.R.RRR.R
R.......R
RRRRRRRRR
l cannot protect both accesses to e.
or even simpler
RRRRRRRRRR
R...RRRRRR
R.R...RRRR
RlReR...gR
R.R...RRRR
R...RRRRRR
RRRRRRRRRR
You have first to create a map distance from each accesses to e.
Then it is a minmax (or alpha-beta):
if g current position in one map-distance is less than l current position is same map-distance, g wins.
if l has less or equal distance in all maps distance, g loses.
else g has to use one of its valid map to reach the goal, l counters with its maps (or stands).
(Note: g has no reasons to stand as l may do the same and we are at the same point).
(Edit: Note: in provided link, it seems that the secure path has to be chosen statically, so the dynamic part (3rd bullet) is a loose for g)
There is no need for the DFS. Just test whether l can reach e before g can. If he can, then he can catch g, otherwise g wins.
(And beware of redundancy in your code; BFS1 and BFS 2 are almost identical, and could be combined into a single function.)
EDIT: The OP has added (a link to) new information: l cannot enter e.
The correction to this algorithm is obvious, if inelegant. Consider the rooms surrounding e; if there is one that g can reach before l, then g wins.
There may be other catches in the linked problem statement; the OP can state the problem he wants answered in the question itself. We don't like "link only" questions here.
hello i am new to programming but every time i run this code i get the error "c++ Expression: string subscript out of range" i am pretty sure that the error is in the second for loop
#include<iostream>
#include<string>
#include <algorithm>
using namespace std;
int main()
{
string x;
string n;
cin >> x;
for (int i = 0; i <= x.length(); i++){
if (x[i] == 'a' || x[i] == 'e' || x[i] == 'i' || x[i] == 'o' || x[i] == 'u' || x[i] == 'y')
{
x[i] = ' ';
}
}
x.erase(remove_if(x.begin(), x.end(), isspace), x.end());
int f = x.length() * 2;
for (int i = 0; i <f-1; i+=2){
n[i] = '.';
}
cout << n << endl;
}
for (int i = 0; i <= x.length(); i++)
should be:
for (int i = 0; i < x.length(); i++)
because index starts from 0
x[x.length()] out of range
can not use n[index] when the size of n is 0,use n.push_back()
for (int i = 0; i < x.length(); i++){ //error
if (x[i] == 'a' || x[i] == 'e' || x[i] == 'i' || x[i] == 'o' || x[i] == 'u' || x[i] == 'y')
{
x[i] = ' ';
}
}
x.erase(remove_if(x.begin(), x.end(), isspace), x.end());
int f = x.length() * 2;
for (int i = 0; i <f-1; i+=2){
n[i] = '.'; // n.push_back('.');
}
cout << n <
< endl;
If you are trying to remove all the vowels from your input string, you do not need to run two separate loops. You are already using std::remove_if, just add lambda shown in following code and you will have your desired output.
#include <iostream>
#include <algorithm>
#include <string>
#include <cctype>
using namespace std;
int main() {
std::string str = "This is test of vowels aeiou to be removed. Also the upper case AEIOU.";
std::cout << "Original String: " << str << std::endl;
str.erase(std::remove_if(str.begin(), str.end(), [](char x) {
return (x == 'a'|| x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'y'
|| x == 'A'|| x == 'E' || x == 'I' || x == 'O' || x == 'U' || x == 'Y')
}), str.end());
std::cout << "String with vowels removed: " << str << std::endl;
// Not sure what you are trying to achieve with this code.
int f = x.length() * 2;
for (int i = 0; i <f-1; i+=2)
{
n[i] = '.';
}
return 0;
}
Here is the LiveDemo
You have 3 bits of code causing errors:
1) Your first error occurs because you should be checking that i < x.length() in the first loop condition, not that i <= x.length() . Even better, calculate the length once and then use that value in the loop condition to avoid calling x.length() repeatedly. Your first loop should look like this:
int length = x.length();
for (int i = 0; i < x.length(); ++i)
note: ++i is quicker than i++ and in this case using ++i would not make a difference to the logic.
2) Your second error is due to the line int f = x.length() * 2 because you are doubling the length of the array and then using that number to iterate through the array. For example, if your array has a length() of 5 then int f = x.length() * 2 would mean that f = 10 but if the length of the array is 5 than accessing the array with any number greater than 4 (array index starts at zero) would produce an error. In your second loop condition you do this
for (int i = 0; i < f-1; i+=2 ) {
n[i] = '.' // i could easily be more than 4 at this point
}
To fix you second problem, take out the * 2 from int f = x.length() * 2
3) Your third is because you haven't given the n string object a value yet you are accessing it using array indexing []
For example, how do you count the occurrence of "TJ" in OAEKOTJEOTJ?
if (s[i] == 'TJ') and (s[i] == 'T'+'J')
x += 1;
First one gives me an error, second one doesn't count. I need a beginner solution to this, I haven't learned very much about c++ commands yet. Thanks
int x = 0
string s;
cin >> s;
for (int i = 0; i < 100; i++)
if (s[i] == T || s[i] == t) && (s[i+1] == J || s[i+1] == j)
x += 1
cout << x << endl;
That's the excerpt from my code, it doesn't count any tj, tJ, Tj or TJ
Try using:
if(s[i] == 'T' && s[i+1] == 'J') // and make sure you do not run out of bounds of string with index i.
x += 1;
EDIT:
Based on your code:
int x = 0
string s;
cin >> s;
for (int i = 0; i < 100; i++)
if (s[i] == T || s[i] == t) && (s[i+1] == J || s[i+1] == j)
x += 1
cout << x << endl;
You should do it like following:
int x = 0
string s;
cin >> s;
for (int i = 0; i < s.length()-1; i++) // use size of string s.length()-1 to iterate the string instead of 100
if (s[i] == 'T' || s[i] == 't') && (s[i+1] == 'J' || s[i+1] == 'j') // compare the ascii values of characters like - 'T' 'J' etc.
x += 1
cout << x << endl;
std::string provides a function find which searches the string for substrings, including multi-character substrings (below, I am using C++11 syntax):
#include <iostream>
#include <string>
int main()
{
using namespace std;
string text { "OAEKOTJEOTJ" };
unsigned int occ { 0 };
size_t pos { 0 };
for (;;) {
pos = text.find("TJ",pos); // Search for the substring, start at pos
if (pos == string::npos) // Quit if nothing found
break;
++pos; // Continue from next position
++occ; // Count the occurrence
}
std::cout << "Found " << occ << " occurrences." << std::endl;
}
The way it's done above we advance by one character only after each match. Depending on whether/how we want to deal with overlapping matches, we might want to advance pos by the length of the search pattern. (See chris's comment as well.)
Try this:
#include <locale> // for tolower() function
string tolower(string s) {
tolower(s[0]);
tolower(s[1]);
return s;
}
...
int main() {
string s;
cin >> s;
int n = s.size(),cont = 0;
for(int i = 0; i < n ; ++i) {
if(tolower(s.substr(i,2)) == "tj") {
++cont;
}
}
cout << cont << endl;
return 0;
}