Prime numbers in an dynamic array - c++

I've a program which inserts all prime numbers up to a specific number in an array.
The calculation is correct. My problems are the function parameters and the transfer of my dynamic array to the function. My function doesn't modify my array.
Please take a look at the code:
#include <iostream>
using namespace std;
int primeinlesen(int *i);
int primarrayspeicherung (int *primarray,int *bis);
int main()
{
int reload=1;
while(reload==1)
{
int bis=0,*primarray,valcounter;
primeinlesen(&bis);
valcounter=primarrayspeicherung(primarray,&bis);
for(int i=0;i<valcounter;i++)
{
cout<<i<<". Primzahl: "<<primarray[i]<<"\n";
}
delete [] primarray;
cout<<"Anzahl Primzahlen: "<<valcounter<<endl;
cout<<"Erneute Berechnung?(Ja(1) oder Nein(0))";
cin>>reload;
}
return 0;
}
int primeinlesen(int *i)
{
cout<<"Bis zu welchem Wert moechten SiePrimzahlen ausgegeben,haben(max.500)";
cin>>*i;
if(*i>500)
{
cout<<"Wert zu hoch...";
}
return 0;
}
int primarrayspeicherung (int *primarray,int *bis)
{
int x,y,counter,e,valcounter=0,xcounter=0,xvalcounter=0,xx,xy,xe;
for(x=2;x<*bis;x++)
{
counter=0;
for(y=2;y<x;y++)
{
e=x%y;
if(e==0)
{
counter++;
}
}
if(counter==0)
{
valcounter++;
}
}
//ZWEITER DURCHGANG
primarray=new int[valcounter];
for(xx=2;xx<*bis;xx++)
{
xcounter=0;
for(xy=2;xy<xx;xy++)
{
xe=xx%xy;
if(xe==0)
{
xcounter++;
}
}
if(xcounter==0)
{
primarray[xvalcounter]=xx;
xvalcounter++;
}
}
return valcounter;
}
Best regards

In this function:
int primarrayspeicherung (int *primarray,int *bis)
primarray is a local variable. Everything you're doing to it (e.g. allocating, assigning) only affects the local primarray, not the one you pass in. If you want to modify both, you need to pass in a reference:
int primarrayspeicherung (int*& primarray,int *bis)

Related

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;
}

C++ - one function makes others malfunction

Here is my task:
Write class Word which has:
pointer on array of characters
constructors and destructors
function to read word
function to check if character which is passed to it as argument occurs in word and return position of occurance
function to check which of two words has more occurances of number 10 and to return that number of occurances
Here is my solution. I compiled it without errors but it doesn't work as it shoud.
#include <iostream>
#include <string.h>
using namespace std;
class Word
{
private:
char *content;
int length;
public:
Word();
Word(char *);
~Word();
void print_content(void);
int check_character(char);
friend int check_number(Word,Word);
};
Word::Word()
{
}
Word::Word(char *n)
{
length=strlen(n);
content=new char [length];
for(int i=0;i<length;i++)
{
content[i]=n[i];
}
}
Word::~Word()
{
delete content;
}
void Word::print_content(void)
{
for(int i=0;i<length;i++)
{
cout<<""<<content[i];
}
}
int Word::check_character(char a)
{
int position=0;
for(int i=0;i<length;i++)
{
if(content[i]==a)
{
position=i+1;
}
}
if(position>0)
{
return position;
}
else return 0;
}
int check_number(Word n,Word m)
{
int counter_n=0;
int counter_m=0;
for(int i=1;i<n.length;i++)
{
if((n.content[i-1]=='1')&&(n.content[i]=='0'))
{
counter_n=counter_n+1;
}
}
for(int i=1;i<m.length;i++)
{
if((m.content[i-1]=='1')&&(m.content[i]=='0'))
{
counter_m=counter_m+1;
}
}
if(counter_n>counter_m)
{
return counter_n;
}
else if(counter_n<counter_m)
{
return counter_m;
}
else return 0;
}
int main()
{
char characters1[]="qwerty10",*p1,*p2;
char characters2[]="stackoverflow101010";
p1=characters1;
p2=characters2;
Word first(p1);
Word second(p2);
cout<<""<<first.check_character('q')<<endl;
cout<<""<<second.check_character('f')<<endl;
//cout<<""<<check_number(first,second)<<endl;
first.print_content();
second.print_content();
}
Function check_number(first,second) for some reason makes other functions to work incorrectly, if you call it by removing "//" you will see that first.print_content() and second.print_content() don't give us correct result. Or if function first.check_character('r') is first called, second.check_character('j') second called and then check_number(first,second), then two firsly called functions don't work.
What's reason for this strange behaviour?
Word objects are passed by copy to check_number, but you did not define the copy constructor. So default one is used by the compiler and this one copies pointer (char* content). Temporary objects passed to the function are pointing to data created first and second in the main function...upon deletion (temprary objects are deleted after the function is called), they delete the pointers, so first and second objects are pointing to deleted memory. You have undetermined behaviour here, this explains side effects you experienced.
Passing objects by reference to check_number is an easy way to fix your problem. Here is a working code (including many fixes because you did not access arrays correctly):
#include <iostream>
using namespace std;
#include <iostream>
#include <string.h>
using namespace std;
class Word
{
private:
char *content;
int length;
public:
Word();
Word(char *);
~Word();
void print_content(void);
int check_character(char);
friend int check_number(const Word&,const Word&); // changed here
};
Word::Word()
{
}
Word::Word(char *n)
{
length=strlen(n);
content=new char [length];
for(int i=0;i<length;i++)
{
content[i]=n[i]; // changed here
}
}
Word::~Word()
{
delete [] content; // changed here
}
void Word::print_content(void)
{
for(int i=0;i<length;i++)
{
cout<<""<<content[i]; // changed here
}
}
int Word::check_character(char a)
{
int position=0;
for(int i=0;i<length;i++)
{
if(content[i]==a) // changed here
{
position=i+1;
}
}
if(position>0)
{
return position;
}
else return 0;
}
int check_number( const Word& n, const Word& m)// changed here
{
int counter_n=0;
int counter_m=0;
for(int i=1;i<n.length;i++)
{
if((n.content[i-1]=='1')&&(n.content[i]=='0')) // changed here
{
counter_n=counter_n+1;
}
}
for(int i=1;i<m.length;i++)
{
if((m.content[i-1]=='1')&&(m.content[i]=='0')) // changed here
{
counter_m=counter_m+1;
}
}
if(counter_n>counter_m)
{
return counter_n;
}
else if(counter_n<counter_m)
{
return counter_m;
}
else return 0;
}
int main()
{
char characters1[]="qwerty10",*p1,*p2;
char characters2[]="stackoverflow101010";
p1=characters1;
p2=characters2;
Word first(p1);
Word second(p2);
cout<<""<<first.check_character('q')<<endl;
cout<<""<<second.check_character('f')<<endl;
cout<<""<<check_number(first,second)<<endl;
first.print_content();
second.print_content();
}
This outputs:
1
10
3
qwerty10stackoverflow101010
Declaring a copy constructor is another way to fix the problem:
Word( const Wodr& word ) :
length( word.length ),
content( new char[word.length] )
{
memcpy( content, word.content, word.length );
}
That would be less efficient than passing objects by const reference, but would make your code safer (it's good to always declare copy constructor to prevent bug you experienced here).
Finally, if you are lazy, you can also declare the copy constructor as private, to prevent compiler to copy objects, just declare it, don't impelment it:
class Word
{
....
private:
Word( const Word& word ); // this makes argument passed by copy impossible.
};
Then, compiler will not let you call check_number.

Array Initialization problems: Unexpected behavior

The following program builds perfectly. However, during execution, no matter what value of degree I provide, the program takes only 2 array elements as input. I suppose there might be a problem with the redeclaration of the arrays f[] and fDash[]. In JAVA, arrays can be easily redeclared using the new keyword. Is that possible in c++ too? If not, what is the alternative?
P.S. I am using CodeBlocks 13.12 and compiler settings are standard.
#include <iostream>
#include <cmath>
using namespace std;
class Polynomial
{
public:
void input(void);
void expression(void);
void derivative(void);
double value(double var);
double der(double var);
private:
int f[];
int fDash[];
int degree;
};
void Polynomial::input()
{
cout<<"Enter degree of polynomial:\t";
cin>>degree;
f[degree+1];
fDash[degree];
for(int i=0;i<=degree;i++)
{
cout<<"Enter coefficient of x^"<<i<<":\t";
cin>>f[i];
}
for(int i=0;i<degree;i++)
{
fDash[i]=f[i+1]*(i+1);
}
}
void Polynomial::expression()
{
cout<<f[0];
for(int i=1;i<=degree;i++)
{
cout<<" + "<<f[i]<<"*x^"<<i;
}
}
void Polynomial::derivative()
{
cout<<fDash[0];
for(int i=1;i<degree;i++)
{
cout<<" + "<<fDash[i]<<"*x^"<<i;
}
}
double Polynomial::value(double var)
{
double val=0.0;
for(int i=0;i<=degree;i++)
{
val+=f[i]*pow(var,i);
}
return val;
}
double Polynomial::der(double var)
{
double val=0.0;
for(int i=0;i<degree;i++)
{
val+=fDash[i]*pow(var,i);
}
return val;
}
int main()
{
double lb,ub,step,var,accum=0.0,rms;
int counter=0;
Polynomial p;
p.input();
cout<<"\n\n\nPolynomial is:\nf(x) = ";
p.expression();
cout<<"\n\n\nDerivative is:\nf'(x) = ";
p.derivative();
cout<<"\n\n\nEnter x0,x1,Step:\t";
cin>>lb;
cin>>ub;
cin>>step;
cout<<"\n\n\n====================================";
cout<<"\n\nx\t|\tf\t|\tf'\n\n\n";
var=lb;
while(var<=ub)
{
cout<<var<<"\t|\t"<<p.value(var)<<"\t|\t"<<p.der(var)<<"\n";
accum+=pow(p.value(var),2.0);
var+=step;
counter++;
}
cout<<"\n====================================";
accum/=counter;
rms=sqrt(accum);
cout<<"\nRMS energy of f(x) = "<<rms;
return 0;
}
This does not compile on clang, it fails with "error: field has incomplete type 'int []' int f[];" and likewise for fDash.
Let's see how you declared these fields:
int f[];
int fDash[];
In C++, you can declare arrays with statically defined sizes like so:
int f[5];
int fDash[6];
If you want dynamic arrays, which you need in this case, you'd have to declare
int* f;
int* fDash;
and allocate memory for them with
f = new int[5];
You also must release that memory somewhere like so
delete [] f;
But beware - managing your own memory like this is error prone and should be avoided. You should just use std::vector instead, which is the equivalent of java.util.ArrayList:
std::vector<int> f;
std::vector<int> fDash;
And modify your input function like so:
void Polynomial::input()
{
cout<<"Enter degree of polynomial:\t";
cin>>degree;
int input;
for(int i=0;i<=degree;i++)
{
cout<<"Enter coefficient of x^"<<i<<":\t";
cin>>input;
f.push_back(input);
}
for(int i=0;i<degree;i++)
{
fDash.push_back(f[i+1]*(i+1));
}
}
You don't use arrays correctly. You need to allocate memory if you want to use array of variable length. How use arrays in c++ see this and this, or use std::vector

Swap 2D int array elements according to user input using printf and scanf

How do i swap the elements in a 2D int array according to use input? For example i have a 2x2 matrix with elements
int c[2][2]=
{
{1,2, },
{3,4, }
};
the user inputs which area to swap like: c[0][0] and c[0][1] then display the new results. Thanks
#include <stdio.h>
#include <stdlib.h>
void swap(int c[2][2],int &x1,int &y1,int &x2,int &y2)
{
int temp = c[x1][y1];
c[x1][y1] = c[x2][y2];
c[x2][y2] = temp;
}
int main(void)
{
int c[2][2]=
{
{1,2, },
{3,4, }
};
int x,y;
int x1,x2,x3,x4,x5,y1,y2,y3,y4,y5;
for(x=0;x<2;x++)
{
for(y=0;y<2;y++)
{
printf("\t%d",c[x][y]);
}
printf("\n");
}
printf("\nEnter 1st value to be swapped:\n");
printf("Row\n");
scanf("%d",&x3);
printf("Column\n");
scanf("%d",&y3);
printf("\nEnter 2nd value to be swapped:\n");
printf("Row\n");
scanf("%d",&x4);
printf("Column\n");
scanf("%d",&y4);
if((x3==1&&y3==1)&&(x4==1&&y4==2))
{
swap(c[0][0],c[0][1]);
}
for(x=0;x<2;x++)
{
for(y=0;y<2;y++)
{
printf("\t%d",c[x][y]);
}
printf("\n");
}
system("pause");
return ;
}
It looks like you just want to do this:
swap(c[x3-1][y3-1],c[x4-1][y4-1]);
But before you do that, you'll need to sanitise the variables to ensure they are within the range of the array.

Newbie - matrix addition implementation in c++

Hello i'm trying to program the addition of 2 matrices into a new one (and it does when i run the program step by step) but for some reason VS 2010 gives me an access error after it does the addition.
Here is the code.
#include <iostream>
#include <cstdio>
#include <conio>
using namespace std;
class operatii
{
typedef double mat[5][5];
mat ms,m1,m2;
int x1,x2,y1,y2;
public:
void preg();
int cit_val();
void cit_mat(int&,int&,double[5][5]);
void suma();
void afisare(int&,int&,double[5][5]);
};
void operatii::preg()
{
cit_mat(x1,y1,m1);
cit_mat(x2,y2,m2);
suma();
afisare(x1,y1,ms);
}
int operatii::cit_val()
{
int n;
cin>>n;
return n;
}
void operatii::cit_mat(int& x,int& y,double m[5][5])
{
char r;
cout<<"Matrice patratica? Y/N ";
cin>>r;
if ((r=='y')||(r=='Y'))
{
cout<<"Numar linii si coloane: ";
x=cit_val();
y=x;
}
else
{
cout<<"Numar linii: ";
x=cit_val();
cout<<"Numar coloane: ";
y=cit_val();
}
for (int i=1;i<=x;i++)
for (int j=1;j<=y;j++)
cin>>m[i][j];
}
void operatii::suma()
{
if ((x1==x2)&&(y1==y2))
for (int i=1;i<=x1;i++)
for (int j=1;i<=y1;j++)
ms[i][j]=m1[i][j]+m2[i][j];
else cout<<"Eroare";
}
void operatii::afisare(int& x,int& y,double m[5][5])
{
cout<<endl;
for (int i=1;i<=x;i++)
{
for (int j=1;j<=y;j++)
cout<<m[i][j];
cout<<endl;
}
}
void main()
{
operatii matrice;
matrice.preg();
system("PAUSE");
}
Any kind of help would be apreciated.
Arrays are 0-based in c++.
Change your various variants of for (somevar=1; somevar<=something) to for (somevar=0; somevar<something)
You're writing past the end of your arrays, which overwrites stack return address, leading to a return to nonexecutable code, again leading to an access violation.
Also,
for (int j=1;i<=y1;j++)
I think you want to use j not i here. Such errors are much easier to see if you use longer and more distinct variable names than "i" and "j", such as e.g. "Line" and "Column"