1

I want to create a function that outputs the distinct values in a given array. For example, in the following sequence 2 2 1 1 5 2 , the distinct digits are 2 1 5. What I've done till now is:

void Distinct(int a[], int b[], int n){

    int i;                    //n is the number of elements for a and b
    int k=0;                  //a is the original array       
    int ac;


b[0] = a[0];
    for (i = 0; i <= n; ++i){
       if (a[i] != b[k])
                   {
                  k+=1; 
                  ac = a[i]; 
                  b[k] =ac; //b is where I want to put distinct digits
                      }

    }


    for ( i = 0; i < k; ++i)
    {
        printf("%d ", b[i]);
    }
}

But this is not enough, because what I've done is for the case when the numbers repeat one after another, I mean: 111122221 , I will get 121, and 1 at the end again.Can you please help me write a function that would consider this case, with repeating numbers scattered in the array ? Thank you.

  • 2
    sort the array first. – Gort the Robot Mar 7 '15 at 18:13
  • Ok, so then I can use the same function I wrote ?, because it's done for sorted arrays. – Ivan Gandacov Mar 7 '15 at 18:16
4

There are many, many ways of doing this, and you haven't really specified whether you're after something that's simple to code or optimally performant or if you have an upper bound on the possible numbers or any other restriction that might help us tell which answer you need.

But your sample code implies you want the solution in a "low-level" language where we're dealing with arrays made up of bytes rather than some higher-level construct like a list/tuple/vector that makes it trivial to do things like remove elements from the middle. Therefore, I would suggest you run a sort algorithm on the input array (if you're in C++, that would be std::sort), then run your Distinct() function on that sorted array to create a correctly unique-ified array.

  • Note that Snowman's answer is entirely correct if you want to use one of those "higher-level constructs". – Ixrec Mar 8 '15 at 15:22
2

We have a name for a data structure that can only contain an element once: a set.

I have done this and tasks like it many times. Here is some pseudocode:

Array input = { ... };
Set output = ...;
for (int i : input) {
  output.add(i);
}
print output;

Initialize the array and a set that will contain the array's contents. Then iterate the array, adding each element to the set. If the set already contains an element with the same value, it will do nothing. Once this is done, print the set. It will contain each value stored in the array a maximum of once.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.