The array a[1..n] contains arbitrary integers. Write C++ function reduce(a,n) that reduces the array a[1..n] by eliminating from it all values that are equal to three largest different odd integers. For example, if a[ ]={9,1,1,6,7,1,2,3,3,5,6,6,6,6,7,9} then three largest different odd integers are 5,7,9 and after reduction the reduced array will be a[ ]={1,1,6,1,2,3,3,6,6,6,6}, and n=11. If you have less than 3 largest different odd integers, eliminate only those that you found.
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
void reduce(int a[], int n)
{
int b[n], c[3], k = 0;
for(int i = 0; i < n; i++)
{
b[i] = a[i]; // replicate the array
}
sort(b, b + n); // sort the array b
for(int i = n - 1; i >= 0; i--)
{
if(k <= 2 && b[i] != b[i - 1])
{
if(b[i] % 2 != 0) // store the largest three odd numbers
{
c[k] = b[i];
k++;
}
}
}
int count = 0;
int d[n];
for(int i = 0; i < n; i++)
{
d[i] = 0; // initialize array d with the 0's
}
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < n; j++)
{
if(c[i] == a[j]) // noting the positions that not to print
{
count++;
d[j] = 1;
}
}
}
for(int i = 0; i < n; i++) // print the modified array
{
if(d[i] == 0)
{
cout << a[i] << " ";
}
}
}
int main()
{
cout << "Enter the size of the array : ";
int n;
cin >> n; // read the size of the array
int a[n];
cout << "Enter the elements : ";
for(int i = 0; i < n; i++)
{
cin >> a[i]; // read the array
}
reduce(a, n);
return 0;
}
OUTPUT :
Get Answers For Free
Most questions answered within 1 hours.