Answer to Question #323101 in C++ for User12345

Question #323101

Write a function named "eliminate_duplicates" that takes an array of integers in random order and eliminates all the duplicate integers in the array.

The function should take two arguments:

(1) an array of integers;

(2) an integer that tells the number of cells in the array.

The function should not return a value, but if any duplicate integers are eliminated, then the function should change the value of the argument that was passed to it so that the new value tells the number of distinct integers in the array. 



1
Expert's answer
2022-04-04T02:40:44-0400
#include<iostream>
#include<algorithm>

using namespace std;

int eliminate_duplicates(int arr[], int n)
{
	if (n == 0 || n == 1)
		return n;
	sort(&arr[0], &arr[n - 1]);
	int *temp = new int[n];
	int j = 0;
	for (int i = 0; i < n - 1; i++)
	{
		if (arr[i] != arr[i + 1])
			temp[j++] = arr[i];
	}
	if(arr[n - 1]>temp[j-1])
		temp[j++] = arr[n - 1];
	for (int i = 0; i < j; i++)
		arr[i] = temp[i];
	return j;
}

int main()
{
	int arr[] = {4,5,7,4,1,2,3,7,6,2};
	int n = sizeof(arr) / sizeof(arr[0]);
	cout << "Primary array: ";
	for (int i = 0; i < n; i++)
		cout << arr[i] << " ";
	cout << "\nn = " << n << endl;
	n = eliminate_duplicates(arr, n);
	for (int i = 0; i < n; i++)
		cout<<arr[i]<<" ";
	cout << "\nn = " << n;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS