Find and replace duplicates in an array

Here's what I am trying to do.

I need to load an array with random integers, however, the numbers need to be unique.

The size of the array can vary based on user input, so using a static "if array[0] == array[1]", etc., is not going to work. I'm assuming I will need to do this with a for loop, I'm just not sure how to accomplish this.

Any help would be appreciated.

Thanks.
You can check if a value is already in the array using std::count ( http://www.cplusplus.com/reference/algorithm/count/ ) before inserting it in the array
Find a simple sort algorithm and make it do what you want
I'm not sure if this will work but it was fun to make
1
2
3
4
5
6
7
8
9
10
11
12
13
int ary[5] = {1,2,3,4,5};
int sizeofarray = 5;

for(int i = 0; i < sizeofarry; i++)
{
  for(int j = i; j < sizeofarray; j++)
  {
       if (arry[i] == arry[j])
      {
        ary[j] = 2 * ary[j];
      }
   }
}
Last edited on
Bazzy,

I'm really not sure how I would use "count". I've never used it before.


kfex,

Not working. I gets stuck in an endless loop. The problem is that this loop will see a duplicate...the number that was just entered. If the number 5 was entered into array[3], then when the loop runs, it's going to see that array[i] == array[j] if i = 3.

I need something that will either check for a duplicate before the random number is entered into the array (as Bazzy suggested, I just don't know how to use count), or to have it ignore the current entry point.


See this example:
1
2
3
4
5
6
7
8
int randomarray[ ARRAY_SIZE ];
int randomvalue;
do
{
    randomvalue = rand(); // get random value
}while ( count ( randomarray, randomarray+ARRAY_SIZE, randomvalue ) ); // randomvalue is present 

randomarray [ index ] = randomvalue;  // randomvalue wasn't in the array so you can insert it   
Last edited on
Something is not working right.

Here is the code that I have:

1
2
3
4
5
6
7
8
9
10
11
12
13
int number;
int pick[number], guessDigit[number];

int temp, n;

for (int n = 0; n < number; n++) {
  do {
    temp = rand() % 10;
  }
  while ( count ( pick, pick+number, temp ) );

  temp = pick[n];
}


Here is the output:

2043106816,
32767,
6297792,
0,
6297231,
0,
2043107016,
32767,


It's only supposed to pick a number between 0 - 9. Plus, it has 0 twice. Not sure what's going on now.


You got line 12 inverted
temp = pick[n];pick[n] = temp;
Bazzy,

That worked, you are my new best friend. :-)

Thank you for your help, this was making my head hurt.
Topic archived. No new replies allowed.