Hey guys, I am stuck on an array our prof. told us to do:
â€¢Given one array, remove all repetitions so that the array has unique numbers.
I am really stuck on this. Are there suppose to be any nested loops? Or 2-3 for loops used in this function? I am passing two parameters: myArray and numOfElements. Can anyone help me out? Thank you for any input.
#include <algorithm>
#include <cstdlib>
#include <iostream>
constint SIZE = 10;
int main()
{
int arr[SIZE ]; // Create the array;
for (int i = 0; i < SIZE ; ++i)
arr[i] = rand()%10; // Fill the array with numbers 0-9
bool done = false;
while (!done) // Go until all numbers are sorted and duplicates are removed
{
done = true;
std::sort(arr, arr+SIZE); // sort the array
for (int i = 0; i < SIZE-1; ++i)
{
if (arr[i] == 999)
break;
if (arr[i] == arr[i+1])
{
arr[i] = 999; // Invalid number
done = false;
}
}
}
for (int i = 0; i < SIZE; ++i) // Print the array
if (arr[i] != 999) // Let's not print the invalid number
std::cout << arr[i] << ' ';
}
What problems are you having? It looks like it works just fine to me. I even increased the max value of the possible random values it inserts to the array and it still works. Course, it's odd that it uses the same numbers each time... hmm....
In my opinion the solution represented by you is wrong because in the original assignment there is said nothing that the order of array elements may be changed.
Besides such approach as using the comparision
if (arr[i] == 999)
is invalid in whole because an arbitrary array can have any acceptable value.
@vlad
The problem is basic, that means that dynamic memory allocation is probably not within the scope yet. I'm not stopping you from providing another solution but I wasn't going to start inserting and deleting elements without STL containers. How else would you "remove" a number.
I wouldn't say that if (arr[i] == 999) is invalid because I defined the contents of arr as having a random value from 0 to 9. If I wanted another range that included 999, I would have chosen a differen invalid number. Perhaps 0xffffffff would work better, or 0xdeadbeef or something obvious.
As there is no possibility to remove an element from an array I think that "removed" elements have to be replaced by some value that is not present among element values. This gives a hint how the assignment can be done if such a replacement value is known.
Another approach is to have the position in the result array where removed elements start that is to have the length of the subarray with unique elements. For example
1 2 3 4 5 6 7 8 9 10 11 12 13 14
constint N = 10;
int a[N] = { 1, 4, 1, 1, 3, 4, 2, 7, 7, 3 };
for ( int *p = a; p != a + N; ++p ) std::cout << *p << ' ';
std::cout << std::endl;
int *q = a;
for ( int *p = a; p != a + N; ++p )
{
if ( std::find( a, q, *p ) == q ) *q++ = *p; // here the standard algorithm can be replaced by a loop
}
for ( int *p = a; p != q; ++p ) std::cout << *p << ' ';
std::cout << std::endl;