View Single Post
Old Mar 26th, 2008, 1:14 AM   #2
lectricpharaoh
Caffeinated Neural Net
 
lectricpharaoh's Avatar
 
Join Date: Jun 2005
Location: Wet west coast of Canada
Posts: 864
Rep Power: 3 lectricpharaoh is on a distinguished road
Re: duplicate numbers in arrays

The easiest (but not the most efficient) method is to iterate through the array, checking to see if the number is present. If so, don't add it. You can write a function for this:
C++ Syntax (Toggle Plain Text)
  1. bool isValueInArray(int value, int *array, int numValues)
  2. {
  3. for(int x=0; x<numValues; ++x)
  4. if(array[x] == value)
  5. return true;
  6. return false;
  7. }
Now, when you get the number from the user, just call this function first in the body of your 'get input from user' loop, and only add it if it returns false:
C++ Syntax (Toggle Plain Text)
  1. if(isValueInArray(n, list, idx)
  2. {
  3. list[idx] = n;
  4. ++idx;
  5. }
Semantically identical to the above, by using postfix increment:
C++ Syntax (Toggle Plain Text)
  1. if(isValueInArray(n, list, idx)
  2. list[idx++] = n;
Of course, you don't need to write a separate function for this; I did it only for clarity. You can merge it into the loop with a flag variable and a nested loop.

You're also not printing out all the valid values the user entered, unless this happens to be 10. Try making your printing loop like so:
C++ Syntax (Toggle Plain Text)
  1. for(int j=0; j<idx; ++j)
  2. cout << list[j] << ' ';
On another note, your code would be much clearer with consistent indentation, and (in my opinion, though I'm sure others will disagree) using the 'opening brace at line start' style, rather than the old K&R style. I had to scan your code a bit to tell where blocks began and ended, whereas if it were done the way I suggest, it'd have been much easier.
__________________
A man's knowledge is like an expanding sphere, the surface corresponding to the boundary between the known and the unknown. As the sphere grows, so does its surface; the more a man learns, the more he realizes how much he does not know. Hence, the most ignorant man thinks he knows it all. - L. Sprague de Camp
lectricpharaoh is offline   Reply With Quote