So for this function, it is supposed to remove any duplicate elements in an array and replace them with an empty string. It will also output the number of duplicates that appear in an array. The code will compile and run, and will output the number of duplicates, but it wont replace the duplicates with empty strings. Any suggestions?
int removeDuplicatedValues (string array[], int n)
{
if (n <= 0)
{
return -1;
}
else
{
int dupes_values = 0;
for (int i = 0; i < n; i++)
{
string potential = array[i];
for (int k = 0; k < n, k != i; k++)
{
if (potential == array[k])
{
dupes_values++;
array[k] == "";
}
}
}
}
}
for (int k = 0; k < n, k != i; k++)
is the same as for (int k = 0; k != i; k++)
The comma operator evaluates the left had expression, throws the result away, and then evaluates the right hand expression. So the result is the value of the right hand expression.
If you want to skip the case where k==i, you could do:
1 2 3
for (int k = 0; k < n; k++) {
if (k==i) continue;
...
But as lastchance said, your k loop should start at i+1. Beyond efficiency, it will give you the correct answer. Otherwise if items 3 and 5 are the same then you'll find the dupe when i=3 and k==5, and then again when i==5 and k==3.
#include <iostream>
usingnamespace std;
int checkArrayForRepeats(int array[],int size);
int main() {
int array[20] = {};
int size, i = 0, repeats = 0;
cout << "How many numbers you want to be added? \n";
while (!(cin >> size))
{
cout << "Invalid input! Please enter number only " << endl;
cin.clear();
cin.ignore(10000, '\n');
cout << "How many numbers you want to be added? \n";
}
cout << "Enter " << size << " numbers: \n" << endl;
while (i<size)
{
while (!(cin >> array[i]))
{
cout << "Invalid input! Please enter number only " << endl;
cin.clear();
cin.ignore(10000, '\n');
}
i++;
}
//now we have our array
cout << "The numbers are: ";
for (int i = 0; i < size; i++) {
cout << array[i] << " ";
}
cout << endl << endl;
repeats = checkArrayForRepeats(array, size);
cout << repeats << " duplicate(s) removed." << endl;
cout << "Now the numbers are: ";
for (int i = 0; i < size; i++) {
if (array[i] != 0) { cout << array[i] << " "; }
}
cin.ignore();
cin.get();
return 0;
}
int checkArrayForRepeats(int array[], int size) {
int countRepeats = 0;
for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
if (array[i] == array[j]) { //compares values
array[i] = 0; //removes duplicates
countRepeats++; //counts number of duplicates
}
}
}
return countRepeats;
}
Sorry to keep everyone waiting but they were serving food in the office and I really like cheese cake. Anyways this is not exactly what you are trying to do but the concept is there. It is a starting point for you to play with and model.