I want to generate 2n-1 random integers in the range [1,n] with each element appearing twice except for random value, which only appears once.
for example:
n = 3
seq = [1, 2, 3, 1, 3]
in this example 2 appears only once.
My algorithm is to use dictionary, like this:
------------- | num |times| | 1 | 2 | | 2 | 1 | | 3 | 2 |
where the keys are from 1 to n and the value represents the number of occurrences of the key. I fill the dictionary with values of two and reduce the value to 1 for one random key.
- Is there any other algorithm?
- how to do it if n is very large lead to can not be stored in memory?
I am not sure that I am 100 sure what you are after, but here is a try:
Result:
EDIT:
Here is a try to do this for very large n (an n that a list of that size cannot be stored in your ram). I cannot see how to shuffle the integers. However, I can remove one at random. Let’s say you want to write the list to txt file.
In the end we were wrote n-1 element to txt file two times, and 1 element once, that element was chosen at random.
For n = 5 the txt file looks like this:
In the above case 1 is only showing up once, every other number is showing up twice.