Unique array numbers

Apr 3, 2012 at 3:38pm
Hi all! Very new to programming and I need a little bit of help with this please? Thanks in advance for any and all replies!

I'm trying to read in an array of set values, then output only those values which are unique and I am struggling!

This is already set up in main() btw...

1
2
3
4
5
6
7
8
9
10
11
12
{
			  int input[20]={1,2,3,4,5,1,2,6,7,8,5,9,10,10,11,12,12,13,14,20}, unique[20], x=0,y=0,hold=0;
			  for(x = 0; x < 20; x++) {				  
					  if(unique[x]!=input[x])
						  unique[x]<<input[x];	  
			  }
			  cout<<unique[20]<< "\n";
			  cout<<input[20];
}
		  cout<<hold;
		  cin.ignore();
		  }


Any clues would be great! Thanks!
Apr 3, 2012 at 3:55pm
I can suggest the following algorithm. You should check each element of the array input whether it is already present in the array unique. So there are two loops in your program. The external loop for traversing array input and the internal loop for traversing array unique. For example

1
2
3
4
5
6
7
8
9
const int N = 20;
int pos = 0;

for ( int i = 0; i < N; i++ )
{
   int j = 0;
   for (  ; j < pos && input[i] != unique[j]; j++ );
   if ( j == pos ) unique[pos++] = input[i];
}     
Last edited on Apr 3, 2012 at 3:56pm
Apr 3, 2012 at 3:59pm
Alternatively, let one loop go 0->n and one loop go n->0. Exact same algorithm, but it results in slightly more readable code [in my opinion].
Apr 3, 2012 at 5:55pm
Thanks very much guys! Worked it out in the end with your advice!
Topic archived. No new replies allowed.