Select an element from the stream with a uniform distributed probability

Give:

  • Stream (end of stream - EOF)
  • Function next()to get the next element in the stream and move the pointer in the stream
  • Random generator generating floats between 0 and 1 (inclusive) evenly

Conclusion:

  • An element that is considered random (evenly distributed) selected

You can select one or two variables.

You are not allowed to use an array / list, but cannot specify a method trying to get all elements out and store them all and then pick.


This is an interview question.

My thinking:

  • I use var curto store the last saved item
  • So, if I get a new element, I generate a random generator 0 or 1, if it is 0, then cur = new element; otherwise continue;
  • EOF, cur

, ? ?


?

+4
3

i.

"" 1/i. EOF , , .

i :

enter image description here

, , .

+10

1/2, , = 2, .

float, [0..1], ( ) . O (1), .

+4

. .

private static final SecureRandom s_random = new SecureRandom();  // Use SecureRandom for truly random selection without a pattern

public static <V> V randomValue(Iterator<V> values)
{
   V result, item;
   int count;

   result = null;

   for (count = 1, values.hasNext(); count++)
   {
      item = values.next();

      if (count == 1)  // Always select the first element
         result = item;
      else if (s_random.nextnextInt(count) == 0)  // Replace the previous random item with a new item with 1/count probability
         result = item;
   }

   if (result == null)
      throw new IllegalArgumentException("No value found");

   return(result);
}

0

Source: https://habr.com/ru/post/1538485/


All Articles