Daniel Bernal
Daniel Bernal

Reputation: 11

Finding Duplicate Values and Printing Them in an Array for C++

I'm trying to find and print the duplicate values in from a list of 10 integers, and I already have this part for the C++ program figured to find it.

#include <iostream> 

using namespace std;

Program Main

int main() //Function Main

    int array[10], out[10];

cout << "The following numbers appear multiple times: ";

for (int i = 0; i < 10; i++)

    if (*(out + i) != 1)

        cout << *(out + i) << " ";

cout << "\n";

system("pause");

return 0; 

Function to find duplicates

int* getDuplicateValues(int array[], int out[], int size)//Finds values that were used more than once in the program

for (int i = 0; i < 10; i++)

    out[i] = 1;

for (int i = 0; i < 10; i++)

{

    int count = 1;

    for (int j = i + 1; j < 10; j++)

    {

        if (array[i] == array[j])

            count++;
    }

    if (count > 1)

        out[i] = array[i];

    count++; 
}

return out;

The only problem is that it won't accept 1 as a duplicate value, and that is probably because of the coding on my part. And I'm relatively new to the coding process so all I need is a step in the right direction to forming the function correctly to find the duplicate values in the array. Please get back to me as soon as you can, preferably before Friday.

Upvotes: 1

Views: 1671

Answers (1)

brc-dd
brc-dd

Reputation: 12964

Currently two approaches are coming to my mind:

1 : Using sorting: Firstly just sort the array and then iterate over the elements to check if adjacent elements are same. If they are same then check if we have already copied them. If not then push them to a vector. And return the vector at last.

Implementation:

#include <algorithm>
#include <iostream>
#include <vector>

auto findDuplicates(std::vector<int> &&v) {
    std::sort(v.begin(), v.end());
    std::vector<int> res;
    for (size_t i = 1; i < v.size(); ++i)
        if (v[i] == v[i - 1] and (res.empty() or res.back() != v[i]))
            res.push_back(v[i]);
    return res;
}

int main() {
    auto v = findDuplicates({1, 2, 1, 1, 3, 3, 3, 4, 5, 4});
    for (auto &&i : v) std::cout << i << ' ';
}

2 : Using a map to store count: We can just map all elements of input vector to create something like a frequency table. And later iterate over it and check if count of an element is greater than 1.

Implementation:

#include <iostream>
#include <map>
#include <vector>

auto findDuplicates(std::vector<int> &&v) {
    std::map<int, size_t> cntMap;
    for (auto &&i : v) cntMap[i]++;
    std::vector<int> res;
    for (auto &&i : cntMap)
        if (i.second > 1) res.push_back(i.first);
    return res;
}

int main() {
    auto v = findDuplicates({1, 2, 1, 1, 3, 3, 3, 4, 5, 4});
    for (auto &&i : v) std::cout << i << ' ';
}

Upvotes: 2

Related Questions