how to do it, but so that I can check if this value is already in the array, and if so it generates a new value
You do not do it because it is a very bad idea.
To illustrate why this is a terrible idea, consider another version of the same problem: collect a million numbers in random order by the following process:
- Choose a number from one to a million.
- Check if there is any in the list.
- If so, return to step 1
- Otherwise, add the number to the list.
- Is there one million items in the list? If yes, then everything is ready. If not, return to step 1.
Clearly this works. Is that a good idea? Suppose you are almost done. There are 999999 items in the list. The only missing element is 857313. What are you doing? You pick a random number, say 12. Now you check the elements 999999 in the list to see if any of them are 12. 12 may have been one of the first numbers you selected, so you could quickly find it . Or it may be one of the last, so it will take a long time. An average of 500,000 checks will show if there are 12 in the list. And this is so, since there is only one number in the list.
12 failed. Go back to the beginning. Choose another random number, say 53259. Is it on the list? Another half a million checks.
Keep doing this until you generate 857313, which happens once in a million attempts.
So, on average, 500,000 x 1,000,000 = five hundred billion comparisons are required to place the last item on the list. It can go even further. This may take several trillion comparisons. Or you are lucky and it will take one. But an average of half a trillion comparisons.
This is a terrible way to create a random list order.
There are two good ways to do a random list order.
(1) Create a device that can sort the list with the specified order function. Provide a stable ordering based on random seed.
Note that you should not create random order by creating a method that returns random results when asked: "Is A greater than B?" This is an erratic ordering; many sorting algorithms are based on stable sorting ordering and will go into infinite loops or have other bad behavior when specifying unstable sorting ordering.
This algorithm is O (n lg n) and has a nice property that is very easy to write from the standard parts, as other answers indicate. It is also extremely fast for small lists in typical implementations.
(2) Select an item by index from a list of sources in a random order, removing it from the source list in the process and placing it in the address list.
The latter is known as Knuth Shuffle or Fischer-Yates Shuffle, and it is a very fast algorithm. You can do this "in place" by mutating the existing array into shuffled order or by creating a new list. It also has a good property that you can "pay for the game" by shuffling the "top" of the list when you need it. If you have a million items to shuffle, but you only need the first hundred, you can simply develop a sort order for the first hundred and call it good.