I was trying to solve a problem where I had to sort so I used the standard library std::sort function but I get a wrong output in the 2nd test case:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
int n,i;
cin>>n;
int arr[n-1];
for(i=1;i<=n-1;i++)
cin>>arr[i];
int size=sizeof(arr)/sizeof(arr[1]);
sort(arr,arr+size);
for(i=1;i<=n-1;i++)
cout<<arr[i]<<" ";
cout<<endl;
}
return 0;
}
I/P:
2
5
1 2 5 4
10
1 2 3 4 5 6 7 8 10
Expected O/P:
1 2 4 5
1 2 3 4 5 6 7 8 10
Actual O/P:
1 2 4 5
2 3 4 5 6 7 8 2013562 10
First of all, int arr[n-1]; is a variable length array. That's not actually part of C++, even though some compilers will tolerate it nevertheless. In most cases you can just use std::vector<int>(n-1); instead.
But look at this loop:
for(i=1;i<=n-1;i++)
cin>>arr[i];
You're starting at 1 and got all the way up to n-1, however your array goes from arr[0] to arr[n-2]. So you got undefined behavior because you're writing one past the size of the array, and you also don't write to the first position (leading to more undefined behavior when you try to sort with this uninitialized value still present).
Instead, the loop should be for(i=0;i<n-1;i++) The same applies to where you're printing it. You can then sort the vector this way:
sort(arr.begin(), arr.end());
Also note that by doing n-1 you're always reading in and handling one less value that the user inputs, I'm not sure if that's your intention. If you want that, you could also just decrease n by one after reading it in instead of writing n-1 in multiple places.
Related
I'm trying to implement insertion sort. My logic may be wrong because I was unable to complete my code due to some error.
I want help with values changing absurdly while executing. Also, there is a similar repeating element question but it is in python and it went over my head. so, please don't mark it duplicate.
As you can see I have initialized a temporary variable index, why you ask? because the value of N is changing during run time.
secondly, Value is getting repeated when sorting is taking place.
I'm using codeblocks 17.2.
#include<iostream>
#include<utility>
#include<algorithm>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
int arr[100];
int N,index;
cin>>N;
for(int i=0;i<N;i++)
{
cin>>arr[i];
}
index=N; // using temperory variable
for(int l=0;l<index;l++)
{
for(int j=l+1;j>=0;j--)
{
if(l==index-1 || j==0) //Working fine now
break;
if(arr[j]<arr[j-1])
{
swap(arr[j],arr[j-1]);
}
}
cout<<N<<endl; //value of n is changing but why
for(int k=0;k<index;k++)
{
cout<<arr[k]<<" "; //value of array is also coming wrong
}
cout<<"\n";
}
return 0;
}
N=7
and elements of the array to be
7 8 5 2 4 6 3
output is
7 //these are the values of N which is changing
7 8 5 2 4 6 3
5
7 7 8 2 4 6 3
2
5 7 7 8 4 6 3
2
4 5 7 7 8 6 3
2
4 5 6 7 7 8 3
2
3 4 5 6 7 7 8
0
2 3 4 5 6 7 7
check for boundary condition and when non-existing array index is accessed it will give undefined behavior. In this case, it appears that N was stored right before arr and it changed when you modified arr[-1].
I'm pretty new to c++, and at the moment i am trying to make a calculator that calculates a Euklid's Algorithm.
Anyways, what i need help with is how i can add the final number to some kind of array for each loop.
Lets for example say i put in the numbers 1128 and 16. my program will then give this output
1128 % 16 = 70 + 8
70 % 16 = 4 + 6
4 % 16 = 0 + 4
theese three lines is printed, one at the time, for each loop. What i want is to add the last numbers (8, 6 and 4) to an array. How would i do this?
Use Vector instead of array, Hope this Helps!
#include <iostream>
#include<vector>
using namespace std;
int main()
{
int a=1128,b=16,i;
vector<int>arr;
while(a>b)
{
cout<<a/b<<" "<<a%b<<endl;
arr.push_back(a%b);
a/=b;
}
cout<<a/b<<" "<<a%b<<endl;
arr.push_back(a%b); // Case: When a<=b in Vector
for(i=0;i<arr.size();i++)
cout<<arr[i]<<" "; // Array i.e 8 6 4
return 0;
}
Output:
70 8
4 6
0 4
8 6 4 // Array
Having difficulty finding an explanation to this.
What does this code do? I understand it creates an array of vector but that's about it.
How can I print the vector array and access elements to experiment with it?
#define MAXN 300009
vector<int>dv[MAXN];
int main()
{
for(int i=1;i<MAXN;i++)
for(int j=i;j<MAXN;j+=i)
dv[j].push_back(i);
}
The code is easy enough to instrument. The reality of what it ends up producing is a very simple (and very inefficient) Sieve of Eratosthenes. Understanding that algorithm, you'll see what this code does to produce that ilk.
Edit: It is also a factor-table generator. See Edit below.
Instrumenting the code and dumping output afterward, and reducing the number of loops for simplification we have something like the following code. We use range-based-for loops for enumerating over each vector in the array of vectors:
#include <iostream>
#include <vector>
#define MAXN 20
std::vector<int>dv[MAXN];
int main()
{
for(int i=1;i<MAXN;i++)
{
for(int j=i;j<MAXN;j+=i)
dv[j].push_back(i);
}
for (auto const& v : dv)
{
for (auto x : v)
std::cout << x << ' ';
std::cout << '\n';
}
}
The resulting output is:
1
1 2
1 3
1 2 4
1 5
1 2 3 6
1 7
1 2 4 8
1 3 9
1 2 5 10
1 11
1 2 3 4 6 12
1 13
1 2 7 14
1 3 5 15
1 2 4 8 16
1 17
1 2 3 6 9 18
1 19
Now, note each vector that only has two elements (1 and an additional number). That second number is prime. In our test case those two-element vectors are:
1 2
1 3
1 5
1 7
1 11
1 13
1 17
1 19
In short, this is a very simple, and incredibly inefficient way of finding prime numbers. A slight change to the output loops to only output the second element of all vectors of length-two-only will therefore generate all the primes lower than MAXN. Therefore, using:
for (auto const& v : dv)
{
if (v.size() == 2)
std::cout << v[1] << '\n';
}
We will get all primes from [2...MAXN)
Edit: Factor Table Generation
If it wasn't obvious, each vector has an ending element (that not-coincidentally also lines up with the subscripts of the outer array). All preceding elements make up the positive factors of that number. For example:
1 2 5 10
is the dv[10] vector, and tells you 10 has factors 1,2,5,10. Likewise,
1 2 3 6 9 18
is the dv[18] vector, and tells you 18 has factors 1,2,3,6,9,18.
In short, if someone wanted to know all the factors of some number N that is < MAXN, this would be a way of putting all that info into tabular form.
I was solving a problem on codechef:
https://www.codechef.com/NITWMA01/problems/QPALIN.It required to input m number of input cases after getting the value of m from the user. I always used to run a loop of:
while(m--)
{//input test cases}, but in this problem I don't know why the loop is running less than m times when I have to get input cases m times. I tried running the code with the sample input(with m having 6) but main() returned 0 after getting just 4 inputs(and printint respective outputs wherever necessary).
My code is as follows:
#include<iostream>
#include<cstdio>
#include<string.h>
using namespace std;
int main()
{
int n,m,op,x,l,r,i,j,xorpair=0;
char k,s[100000];
scanf("%d",&n);
scanf("%s",s);
scanf("%d",&m);
for(j=0;j<m;j++)
{
scanf("%d",&op);
if(op==1)
{
scanf("%d",&x);
scanf("%c",&k);
s[x-1]=k;
}
else
{
xorpair=0;
scanf("%d%d",&l,&r);
for(i=l-1;i<r;i++)
{
xorpair^=s[i]-'0';
}
if(xorpair==0)
{
printf("YES\n");
}
else printf("NO\n");
}
}
return 0;
}
PS: I have replaced cin with scanf. Also I believe I was not able to properly convey what problem actually I am facing. So here's the test case that explains it more clearly:
(What it should be like)
Sample input:
7
abbacca
6
2 1 4
1 1 z
2 1 4
1 4 z
2 1 4
2 5 7
Sample output:
YES
NO
YES
YES
Following is the problem that I am facing:
When I run the program for the above input, this is what appears on the output screen
7
abbacca
6
2 1 4
YES
1 1 z
2 1 4
NO
1 4 z
Process returned 0 (0x0)
I am not able to enter inputs 6 times and after 4th input it returns 0.
scanf("%c" does not do what you seem to expect. It reads just the ' ' before the char you want. Then the next tries at reading op and x fail leaving op still equal to 1, so you do two of operation 1 for every once that you intended to.
I am using scanf to take input for a graph. The input is as follows :
8
1 2
3 3 5 6
2 4 7
2 3 8
2 1 5
1 7
2 6 4
0
The first integer (8) is the number of vertices, followed by 8 line. The first integer in each is the number of outgoing edges from vertex 1 in the first line, vertex 2 in the second line and so on.
The function i have written is as follows :
void getInput() {
//init();
int numVertex; int numTest;
scanf("%d", &numVertex);
for(int i =1 ; i <= numVertex;i++) {
int ver,nC; vector<int> vList;
//fscanf(file,"%d", &ver);
scanf("%d", &nC);
for(int j=0;j<nC;j++) {
int temp ;
scanf("%d", &temp);
vList.push_back(temp);
}
props pr = {-1,-1 , vList};
graph.insert(make_pair(i, pr) );
}
}
However, the output for the last line of my input becomes weird and it basically repeats the last digit of its previous line multiple times. For the above input , the output I am getting :
1 : 2
2 : 3 5 6
3 : 4 7
4 : 3 8
5 : 1 5
6 : 7
7 : 6 4
8 : 4 4 // this is where it should give nothing
Can anyone tell me whats going wrong here? The exact same sequences of conversions, when I convert to taking input through file gives me the right output.
Can someone please point me to any error?
Do it like this:
if (scanf("%d", &nC) != EOF) {
for(int j=0;j<nC;j++) {
int temp ;
scanf("%d", &temp);
vList.push_back(temp);
}
props pr = {-1,-1 , vList};
graph.insert(make_pair(i, pr) );
}
This will check if the read was successful. The repetition of the last line of input is a well known issue and occurs because the last read attempt fails (because end of file has reached) and scanf returns the same result as its previous call.
What is props?
Whatever it is, doing C-style struct initialization on something containing an std::vector is asking for trouble - the results are undefined and almost surely not what you want.
Your input code seems OK though, despite lack of error-checking as noted in another answer.