I'm getting a segmentation fault in my C++ program, kindly help me know where I'm going wrong. Code is as follows:
#include<iostream>
#include<fstream>
#include <stdlib.h>
using namespace std;
int hasTwoElements(int A[], int n, int x)
{
int temp;
bool hashMap[2000] = {0}; /*initialize hash map as 0*/
for (int i = 0; i < n; i++)
{
temp = x - A[i];
if (temp >= 0 && hashMap[temp] == 1)
return 1;
hashMap[A[i]] = 1;
}
return 0;
}
int main()
{
ofstream input,output;
input.open ("ip.txt");
output.open ("op.txt");
int t;
cin>>t;
input<<t<<endl;
while(t--){
int n=rand()%50+1;
int A[n];
input<<n<<endl;
for(int i=0;i<n;i++){
A[i] = rand()%1000-500;
input<<A[i]<<" ";
}
input<<endl;
int x;
x = rand()%2000-1000;
input<<x<<endl;
if(hasTwoElements(A, n, x)==1)
output<<"Pair exists"<<endl;
else
output<<"Pair doesn't exist"<<endl;
}
output.close();
input.close();
return 0;
}
I'm basically trying to check if a pair exists in the array for which the sum of the two numbers is equal to the number X passed in the function.
Aucun commentaire:
Enregistrer un commentaire