Hey guys, new to c++. What I am trying to do is generate an array with random constituents (the number depicted by the user). While the array is filling, I want another loop to be scanning if a double has occured.
For example, if the array generated as:
10 4 5 18 5
I want to be able to detect that that 5th element was a double. I have some code I have been working on. Greatly appreciate if you could help.
You can do this a few ways. Either continue the way you are now and check after each iteration if you have already added this element, if so generate a new one. You can also generate the entire array, and then go back in and fix any repeated values. Both of these about the same efficiency wise, which is they are both bad.
A slightly better way to do this is to sort the array, and then it's just matter of checking to see if value n == value n + 1. But this has the problem of having to insert the new value into the correct spot each time something needs replaced. There's a couple ways to go about doing that, neither really being better than the other.
And a better way again is to have a bool array of size MAX - MIN, where MAX is the maximum number that can be generated, and MIN is the smallest. Each time you insert a number into the unique valued array, you first check the bool array to see if that index is true, if it is then you generate a new value and repeat. If it's not true, set that index of the bool array to true and then insert into the unique valued array.
Or, you can just use a data structure that is meant to only have unique values. Such as std::unordered_set.