-2

I need to generate an array of random numbers representing v4 ip address, and each random numbers in the array have to be unique.

What would be the most efficient approach (data structure and algorithm) to solve this problem?

I am thinking to generate an array of 255^4 element, from 0 to 255^4. and use a shuffle algorithm such as Fischer and Yattes algorithm to shuffle these number. So when I need to generate an array of n element, I simply pick the 1st n element from the above array.

Is it the most efficient approach?

WABBIT0111
  • 2,233
  • 2
  • 18
  • 30
  • 1
    Possible duplicate of [Most efficient way of randomly choosing a set of distinct integers](https://stackoverflow.com/questions/3722430/most-efficient-way-of-randomly-choosing-a-set-of-distinct-integers) and https://stackoverflow.com/questions/196017/unique-non-repeating-random-numbers-in-o1 – Oleg Nov 12 '17 at 00:06

2 Answers2

1

IP v4 numbers are just another way to present a 32-bit integer. Print each byte in decimal with dots inbetween.

Hence, pick a random 32-bit number, and discard those who represent a broadcast address in your system. Repeat as necessary.

Thorbjørn Ravn Andersen
  • 73,784
  • 33
  • 194
  • 347
0

If you want deterministic uniqueness guarantees for your IPv4 integers (32 bits), you could simply use an array of 512 MB then according to whatever probability distribution you need just loop over the array, flip a coin (maybe biased towards how many integers you are looking for), and set the bit if heads or leave it unset if tails.

However if you willing for probabilistic guarantees only, you could be much trickier in reducing the memory consumption using a construction based on approximate counting.