Reputation: 47
I want to find the duplicate numbers in this array, I'm using vectors and want to print the answer, what am I doing wrong here?
#include <iostream>
#include <vector>
using namespace std;
int findDuplicate(vector<int> &arr)
{
int ans = 0;
// XOR all elements
for (int i = 0; i < arr.size(); i++)
{
ans = ans ^ arr[i];
}
// XOR [1, n-1]
for (int i = 1; i < arr.size(); i++)
{
ans = ans ^ i;
}
cout << ans;
return ans;
}
int main()
{
vector<int> arr = {5, 2, 5, 2, 7, 6, 6};
findDuplicate(arr);
}
Upvotes: 0
Views: 343
Reputation: 9058
There are a number of things that are wrong. Let's start with the two easy ones.
You have a cout statement that prints (it turns out) 0. But you don't do an endl, so you don't get a newline.
cout << ans << endl;
That will actually print a newline, which makes it easier to read.
Second, your method returns a value, which is ignored in main(). You probably want to do this in main:
int answer = findDuplicate(arr);
cout << "And the answer is " << answer << endl;
Or something like that.
That's all fine and good. That's the easy stuff. But why do you think this XOR code is going to tell you what duplicates their are, especially when there might be multiples of the same value or more than one value with duplicates. Maybe there is some algorithm you know about that none of us do.
But it's printing out 0 when the data clearly has duplicates.
Every duplicate finder I know about that's remotely efficient sorts the data then does a loop through it, keeping track of the last value, and if the next value equals the previous value, you have a duplicate.
#include <algorithm>
std::sort(vec.begin(), vec.end());
int prevValue = vec[0];
for (int index = 1; index < vec.size(); ++index) {
int thisValue = vec[index];
if (thisValue == prevValue) {
... Print it
}
prevValue = thisValue;
}
You can make this smarter if you want to know how many are duplicated, and want to be smart about not printing 6 is duplicated 17 times in a row.
Upvotes: 1