How I test this code in DevCpp? (has other 2 .h) - c++

How I teste this code in DevCpp: because show no main error
undefined reference to `WinMain'
#include "Expression.h"
using namespace std;
expression encontra seu valor
void Expression::infixToPostfix()
{
string teste=getInfix();
int n = teste.length();
char atual[n+1];
char x;
strcpy(atual, teste.c_str());
Stack<char> operadores;
Stack<char> pos_fixa;
for(int i=0;i<n+1;i++){
if(isdigit(atual[i])){
pos_fixa.push(atual[i]);
}
else{
if(atual[i] != ')'){
operadores.push(atual[i]);
}
else{
while(!operadores.empty() || x != '('){
operadores.getTop(x);
if(x!='('){
pos_fixa.push(x);
}
operadores.pop(x);
}
}
}
}
while(!pos_fixa.empty()){
pos_fixa.getTop(x);
printf("%c\n",x);
postfix=postfix+x;
pos_fixa.pop(x);
}
}
and I don't know how I run this exemple program to test
because don't have a way to create a main? or anithing like that? has other parts but stackoverflow don't allowed to declare

Related

global vairable did not initialize correctly between running multiple test cases in c++

I am still actively learning c++ with a strong background in python3, the point of this question is not seeking any help with solving the problem Decode Variations on leetcode or pramp, but to understand the compilation or syntax related issue in c++.
The following code using dfs runs well if I run it case by case, however on pramp, it failed in RUN TESTS! Very surprising! It seems like in test case #2 int n=0; was not initialized and used the output of n in test case #1 as its value rather than 0, see the console in the attached screenshot at the end.
#include <iostream>
#include <string>
using namespace std;
int n=0;
void dfs(const string& s, int i){
if (i==s.size()){
n++;
return;
}
if ( 0<s[i]-'0' && s[i]-'0'<10)
dfs(s, i+1);
if (i+1<s.size() && 10<=stoi(s.substr(i,2)) && stoi(s.substr(i,2))<=26)
dfs(s, i+2);
}
int decodeVariations(const string& s)
{
dfs(s,0);
cout<<n<<endl;
return n;
}
int main()
{
return 0;
}
Here is the code to run test case #2:
int main()
{
const string s = "26";
dfs(s,0);
cout<<n<<endl;
return 0;
}
If I added another initialization of n=0; to int decodeVariations(const string& s), then everything works fine. I try to become a programmer with a clear mind, please educate me.
Yes, non-const global variable is evil. Even though I don't know how leetcode and pramp (especially, the main function is empty) run a number of test cases, but I get a hunch it runs test case in the main function, which only compile and run the code once. Thus the global did not get reinitialized.
#include <iostream>
#include <string>
using namespace std;
int n=0;
void dfs(const string& s, int i){
if (i==s.size()){
n++;
return;
}
if ( 0<s[i]-'0' && s[i]-'0'<10)
dfs(s, i+1);
if (i+1<s.size() && 10<=stoi(s.substr(i,2)) && stoi(s.substr(i,2))<=26)
dfs(s, i+2);
}
int decodeVariations(const string& s)
{
dfs(s,0);
return n;
}
int main(int argc, char **argv){
for (int i=1;i<argc;i++)
cout<<decodeVariations(argv[i])<<endl;
}
run with ./test 26 26 26
output:
2
4
6
Quick fix is to get rid of global variable
#include <iostream>
#include <string>
using namespace std;
//int n=0;
int dfs(const string& s, int i){
int ans = 0;
if (i==s.size()){
return 1;
}
if ( 0<s[i]-'0' && s[i]-'0'<10)
ans += dfs(s, i+1);
if (i+1<s.size() && 10<=stoi(s.substr(i,2)) && stoi(s.substr(i,2))<=26)
ans += dfs(s, i+2);
return ans;
}
int decodeVariations(const string& s)
{
// your code goes here
int n;
n = dfs(s,0);
cout<<n<<endl;
return n;
}

error while passing values in push operation in stack implementation(Parenthesis matching)

#include <iostream>
#include<string>
using namespace std;
class Stack{
public:
int top;
int size;
string *s;
void isBalanced(Stack *st,string exp);
};
push function is
void push(Stack *st,string x){
if(st->top==st->size-1)
cout<<"Stack full\n";
else{
st->top++;
st->s[st->top]=x;
}
}
pop function
string pop(Stack *st){
string x;
if(st->top==-1)
cout<<"Stack is empty\n";
else{
x=st->s[st->top--];
}
return x;
}
errored function
void Stack::isBalanced(Stack *st,string exp){
for(int i=0;exp[i]!='\0';i++){
if(exp[i]=='('){
push(st,exp[i]);
}else if(exp[i]==')'){
if(top==-1)
cout<<"stack empty\n";
pop(st);
}
}
if(top==-1)
cout<<"Balanced\n";
else
cout<<"Not balanced\n";
}
in main
int main()
{
Stack st;
string expression;
cout<<"ENTER EXPRESSION TO CHECK PARENTHESIS BALANCED OR NOT : ";
cin>>expression;
st.size=expression.length();
st.top=-1;
st.s=new string[st.size];
st.isBalanced(&st,expression);
}
here i was trying to implement parenthesis matching problem using in c++ but in the line below code throws error in function isBalanced please
try
to fix
my problem
push(st,exp[i]);
this line throws error canot covert something... and i cant able to fix it.I had donr all posible ways and cant be rectified so ...
push(st, std::to_string(exp[i])); should fix your problem!

Getting wrong answer in a DP problem although implementation looks correct

I was trying to solve Reduce String on codechef which says
Give a string s of length l, and a set S of n sample string(s). We do reduce the string s using the set S by this way:
Wherever Si appears as a consecutive substring of the string s, you can delete (or not) it.
After each deletion, you will get a new string s by joining the part to the left and to the right of the deleted substring.
I wrote a recursive function as follows:-
Basically what i am doing in my code is either don't delete the character or delete it if it is part of any substring but it is giving wrong answer.
#include <bits/stdc++.h>
using namespace std;
#define mx 255
int dp[mx];
unordered_map<string,int> sol;
void init(int n)
{
for(int i=0;i<n;i++)
{
dp[i]=-1;
}
}
int solve(string str,int low,int high,vector<string> smp)
{
if(low>high)
{
return 0;
}
if(dp[low]!=-1)
{
return dp[low];
}
int ans=1+solve(str,low+1,high,smp);
for(int i=low;i<high;i++)
{
string tem=str.substr(low,i-low+1);
for(int j=0;j<smp.size();j++)
{
cout<<"low i high str"<<low<<" "<<i<<" "<<high<<" "<<smp[j]<<" "<<tem<<endl;
if(tem.compare(smp[j])==0)
{
ans=min(ans,solve(str,i+1,high,smp));
}
}
}
return dp[low]=ans;
}
signed main()
{
sol.clear();
string str;
vector<string> smp;
int n;
cin>>str;
cin>>n;
for(int i=0;i<n;i++)
{
string tem;
cin>>tem;
smp.push_back(tem);
}
int len=str.length();
init(len+1);
cout<<solve(str,0,len-1,smp)<<endl;
return 0;
}
PS:
link to the question
This question is toughest(seen so far) and most beautiful(again seen so far) question based on DP ON INTERVALS.
The initial code would definitely not work since it only considers single pass on the string and would not consider remaining string after deleting the patterns again and again.
There are 3 cases:-
Case 1 Either character is not deleted.
Case 2It is deleted as a part of contiguous substring.
Case 3It is deleted as a part of subsequence that matches any word given in the set of patterns and everything that is not part of that subsequence is deleted first as a substring(which again belongs to set of words).
The third part is the most tricky and requires enough thinking and is even tougher to implement too.
So for every substring we need to check whether this substring can be completely destroyed or not.
The function compute_full_recur() is the function that ensures that whether substring can be deleted either in Case 2 or Case 3.
The function compute_full takes care of Case 1.And finally this code will not run on codechef link since all the function are recursive with memoization but to verify the code is working i Have run it on Problem Reducto of Hackerrank which is exact similar with lower constraints.Download test cases and then run on test cases on your PC for verifying.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
#define mx 252
#define nx 40
bool full[mx][mx],vis[mx][mx],full_recur[mx][mx][nx][nx];
int ans[mx];
void init()
{
for(int i=0;i<mx;i++)
{
for(int j=0;j<mx;j++)
{
full[i][j]=false,vis[i][j]=false;
}
}
for(int i=0;i<mx;i++)
{
ans[i]=-1;
}
for(int i=0;i<mx;i++)
{
for(int j=0;j<mx;j++)
{
for(int k=0;k<nx;k++)
{
for(int l=0;l<nx;l++)
{
full_recur[i][j][k][l]=false;
}
}
}
}
}
bool compute_full_recur(string str,int low,int high,vector<string> pat,int idx,int len)
{
if(low>high&&len==pat[idx].length())
{
return true;
}
if(low>high&&len<pat[idx].length())
{
full_recur[low][high][idx][len]=false;
return false;
}
if(str[low]==pat[idx][len]&&compute_full_recur(str,low+1,high,pat,idx,len+1))
{
return full_recur[low][high][idx][len]=true;
}
for(int i=low+1;i<=high;i++)
{
if(str[low]==pat[idx][len]&&full[low+1][i]&&compute_full_recur(str,i+1,high,pat,idx,len+1))
{
return full_recur[low][high][idx][len]=true;
}
}
full_recur[low][high][idx][len]=false;
return false;
}
void compute_full(string str,int low,int high,vector<string> pats)
{
if(low>high)
{
return;
}
if(vis[low][high])
{
return;
}
vis[low][high]=true;
compute_full(str,low+1,high,pats);
compute_full(str,low,high-1,pats);
for(int i=0;i<pats.size();i++)
{
if(!full[low][high])
full[low][high]=compute_full_recur(str,low,high,pats,i,0);
}
}
int compute_ans(string str,int low,int high)
{
if(low>high)
{
return 0;
}
if(ans[low]!=-1)
{
return ans[low];
}
int sol=1+compute_ans(str,low+1,high);
for(int i=low+1;i<=high;i++)
{
if(full[low][i]==true)
{
sol=min(sol,compute_ans(str,i+1,high));
}
}
return ans[low]=sol;
}
signed main()
{
int t;
cin>>t;
while(t--)
{
string str;
int n;
vector<string> pats;
cin>>n>>str;
for(int i=0;i<n;i++)
{
string tem;
cin>>tem;
pats.push_back(tem);
}
init();
compute_full(str,0,str.length()-1,pats);
cout<<compute_ans(str,0,str.length()-1)<<endl;
}
return 0;
}

Segmentation Fault Passing Reference as Function Parameter

With this block of code, I'm getting a segmentation fault as I try to pass the stack references to the transferStacks() method. Any help on understanding why this is would be helpful!
I could just get rid of the helper method and it should work, but I'm trying to understand conceptually.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <stack>
using namespace std;
void transferStacks(stack<int> & s1, stack<int> & s2){
if (s1.empty()){
for (int i = 0; i < s2.size(); i++){
int element = s2.top();
s1.push(element);
s2.pop();
}
}
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int queries = 0;
cin>>queries;
stack <int> newestOnTop;
stack <int> oldestOnTop;
while (queries!=0){
int type = 0;
cin >> type;
int input = 0;
if (type == 1){ //enqueue
cin>>input;
newestOnTop.push(input);
}
else if (type == 2){ //dequeue
transferStacks(newestOnTop, oldestOnTop);
oldestOnTop.pop();
}
else if (type == 3){ //peek
transferStacks(newestOnTop, oldestOnTop);
cout<<oldestOnTop.top()<<endl;
}
queries--;
}
return 0;
}
Segmentation Fault
You appear to believe that this code will copy s2 to s1:
for (int i = 0; i < s2.size(); i++){
int element = s2.top();
s1.push(element);
s2.pop();
}
But it will not: if before the loop s2 contains 3 elements, only the first 2 will be copied (and generally, only the first half will be copied).
In addition, your transfer function transfers from s2 to s1, but the way you call it implies that you intended the opposite: to transfer from s1 to s2. Current code would leave oldestOnTop empty, which will then result in a crash when you use oldestOnTop.top() or oldestOnTop.pop().

(C++) Does not stop on std::cin and goes into infinity loop?

I have a wird problem. Im using Visual Studio 2012, thats my code: (something is in polish but i hope you will understand how it works).
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <queue>
using namespace std;
#pragma warning (disable: 4996);
struct strona
{
int zawartosc;
int gdzie;
};
void Wyswietl(int tab[], int dlugosc)
{
cout<<"Tablica wyglada tak"<<endl;
for(int i=0;i<dlugosc;i++)
{
cout<<tab[i]<<"\t";
}
cout<<endl;
}
int main()
{
int ileStron=3;
int *tablicaStron, *tablicaBitowOdniesienia;
tablicaStron=new int[ileStron];
tablicaBitowOdniesienia=new int[ileStron];
queue <strona> kolejka;
char opcja='a';
while(opcja!='k')
{
cout<<"(D)odawac (K)oniec (W)yswietl";
cin>>opcja;//DONT STOP THE PROGRAM!
if(opcja=='D'|opcja=='d')
{
strona tymczas;
cout<<"Podaj co dodać do kolejki";
cin>>tymczas.zawartosc;
int licznik=0;
if(kolejka.size()<ileStron)
{
tymczas.gdzie=kolejka.size();
kolejka.push(tymczas);
tablicaStron[tymczas.gdzie]=tymczas.zawartosc;
}
else if(kolejka.size()==ileStron)
{
cout<<"bang bang";
int czyJest=0;
int licznikfora=0;
for(int i=0;i<ileStron;i++)//sprawdza czy wpisywana strona nie istnieje przypadkiem w tablicy stron
{
if(tablicaStron[i]==tymczas.zawartosc)
{
czyJest=1;
}
licznikfora++;
}
cout<<"czyJest ma wartosc "<<czyJest<<" a licznik fora "<<licznikfora<<endl;
if(czyJest==0)
{
tymczas.gdzie=kolejka.front().gdzie;
kolejka.pop();//TUTAJ SIE BEDZIE ZAPISYWAC DO PAMIECI WIRTUALNEJ
kolejka.push(tymczas);
tablicaStron[tymczas.gdzie]=tymczas.zawartosc;
}
else if(czyJest==1)
{
cout<<"to co chcesz dodac juz jest w pamieci";
}
}
else
{
cout<<"rozmiar kolejki sie nie zgadza";
}
}
else if(opcja=='W'|opcja=='w')
{
Wyswietl(tablicaStron,ileStron);
cout<<endl;
cout<<"pierwszy element w kol: "<<kolejka.front().zawartosc<<"|"<<kolejka.front().gdzie<<" "
<<"ostatni element w kol: "<<kolejka.back().zawartosc<<"|"<<kolejka.back().gdzie<<endl;
}
}
system("pause");
return 0;
}
The problem is that after choosing option (d) - just type d and press enter, then type any few letters and the program should show you
(D)odawac (K)oniec (W)yswietl
but it is starting to loop to infinity...
What is the problem?
I think problem is with this statement:
cin>>tymczas.zawartosc;
At this point if you give a char or string input, program blows up.
to make your program work properly:
start the program and give only one input d, let the control hit this point : cin>>tymczas.zawartosc;
now input a number here, as it is int type. now control hits first cin.
The problem is with using cin to read int but user inputs a char or string. Behaviour is undefined in this case.
This link should resolve confusion: C++ character to int