![]() |
duplicate numbers in arrays
Hi, I've been lurking here for a while now and decided to make an account to get help. The program I'm trying to write is supposed to:
Read in 20 numbers, each of which is between 10 and 100, inclusive. As each number is read in, validate it and store it in the array only if it is not a duplicate of a number already read. After reading all the values, display only the unique values that the user has entered. I have the program functionally working except I don't know what to do for the duplicate cases. Is there an easy way to skip the value entered if duplicate? :
#include <iostream> |
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:
:
:
:
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: :
|
Re: duplicate numbers in arrays
There's a neat trick you can use to do this.
Use an array of zeroes. For each number they enter, set the n'th element to 1. After you're done, print out all elements that are 1. This automatically stops itself from printing out duplicates, because setting an element to 1 twice still keeps it at 1. Also, your validation of each number did not stop it from being added to the array. The assignment specifies to include duplicates as one of the 20 numbers, but do not count invalid numbers as one of the 20. :
int main() {Note that this does not mantain the order the numbers were inputted. If you need to mantain the order, you could keep your original code, and then use this method to output the array. As you're outputting it, set the element to 1. Then make sure you don't output a number if the list is set to 1 for that value. |
Re: duplicate numbers in arrays
This sounds like a homework assignment to me, so I'm not sure if you'd be allowed to do this, but it would be really easy with sets. Sets are a type of data structure which are always ordered and can only store unique values, which sounds like what you're looking for. There's a set class in the STL.
To initialise a set: :
set<int> list;:
list.insert(n);And to get stuff out: :
for (set<int>::iterator i = list.begin(); i != list.end(); i++) { |
Re: duplicate numbers in arrays
I made a boo-boo:
Quote:
:
if(!isValueInArray(n, list, idx)) |
Re: duplicate numbers in arrays
Double post, oops.
|
| All times are GMT -5. The time now is 12:46 PM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC