-5

For example I have two array (first array contains first names and second array last names). I want to generate n number of unique, non-repeating combinations from this two arrays with such ordering >>> first_name + ' ' + last_name.

I don't wish to generate every possible combination beforehand, because it's too much memory-consuming.

So what I think that algorithm should do, is to iterate until combinations are not generated, during iteration, it should give some random indexes for both arrays and if those indexes are already used together try to pick another random numbers until unique indexes are not generated. But this approach might trigger deep recursion during runtime, since as many outputs are already given, a chance that new random indexes will be matched with existing ones is going higher at each step.

So what is your suggestion guys, how can I select random, unique n items from non-existing/virtual 2 array element combinations with very optimized way

wol
  • 142
  • 1
  • 14
  • 1
    Please visit the [help], take the [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output. – mplungjan May 25 '18 at 14:25

1 Answers1

0

If you have F unique first names and L unique last names, then overall number of combinations is N = F * L

So you can generate needed number of non-repeating random integer values in range 0..N-1 (for example, with Fisher-Yates sampling), sort them, and get corresponding name combinations:

for i = 0..M-1
    Generate K[i] = Random(N)
Sort K[]
for i = 0..M-1
   FirstNameIndex = K[i] / L    //integer division
   LastNameIndex = K[i] % L     //integer modulo
   Combination[i] = First[FirstNameIndex] + Last[LastNameIndex]
MBo
  • 77,366
  • 5
  • 53
  • 86
  • Thanks, I ended up with an exact same solution. Of course, it has downside, that we generate whole length array and then shuffle it, but this is most optimal solution anyway. – wol May 28 '18 at 10:35