Implementar rand3() usando rand2()

Dada una función rand2() que devuelve 0 o 1 con igual probabilidad, implemente rand3() usando rand2() que devuelve 0 1 o 2 con igual probabilidad. Minimiza el número de llamadas al método rand2(). Tampoco se permite el uso de ninguna otra función de biblioteca ni la aritmética de punto flotante.
 


La idea es utilizar la expresión. 2 * rand2() + rand2() . Devuelve 0 1 2 3 con igual probabilidad. Para que devuelva 0 1 2 con igual probabilidad eliminamos el evento no deseado 3.
A continuación se muestra la implementación de la idea anterior: 
 

C++
   // C++ Program to print 0 1 or 2 with equal    // probability   #include          using     namespace     std  ;   // Random Function to that returns 0 or 1 with   // equal probability   int     rand2  ()   {      // rand() function will generate odd or even      // number with equal probability. If rand()      // generates odd number the function will      // return 1 else it will return 0.      return     rand  ()     &     1  ;   }       // Random Function to that returns 0 1 or 2 with    // equal probability 1 with 75%   int     rand3  ()   {      // returns 0 1 2 or 3 with 25% probability      int     r     =     2     *     rand2  ()     +     rand2  ();          if     (  r      <     3  )      return     r  ;          return     rand3  ();   }   // Driver code to test above functions   int     main  ()   {      // Initialize random number generator      srand  (  time  (  NULL  ));          for  (  int     i     =     0  ;     i      <     100  ;     i  ++  )      cout      < <     rand3  ();          return     0  ;   }   
Java
   // Java Program to print 0 1 or 2 with equal    // probability   import     java.util.Random  ;      class   GFG   {      // Random Function to that returns 0 or 1 with       // equal probability       static     int     rand2  ()         {         // rand() function will generate odd or even       // number with equal probability. If rand()       // generates odd number the function will       // return 1 else it will return 0.       Random     rand     =     new     Random  ();         return     (  rand  .  nextInt  ()     &     1  );         }         // Random Function to that returns 0 1 or 2 with       // equal probability 1 with 75%       static     int     rand3  ()         {         // returns 0 1 2 or 3 with 25% probability       int     r     =     2     *     rand2  ()     +     rand2  ();         if     (  r      <     3  )         return     r  ;         return     rand3  ();         }         // Driver code      public     static     void     main  (  String  []     args  )     {      for  (  int     i     =     0  ;     i      <     100  ;     i  ++  )         System  .  out  .  print  (  rand3  ());      }   }   // This code is contributed by divyesh072019.   
Python3
   # Python3 Program to print 0 1 or 2 with equal    # Probability   import   random   # Random Function to that returns 0 or 1 with    # equal probability    def   rand2  ():   # randint(0100) function will generate odd or even   # number [1100] with equal probability. If rand()   # generates odd number the function will    # return 1 else it will return 0   tmp  =  random  .  randint  (  1    100  )   return   tmp  %  2   # Random Function to that returns 0 1 or 2 with    # equal probability 1 with 75%    def   rand3  ():   # returns 0 1 2 or 3 with 25% probability    r   =   2   *   rand2  ()   +   rand2  ()   if   r   <  3  :   return   r   return   rand3  ()   # Driver code to test above functions   if   __name__  ==  '__main__'  :   for   i   in   range  (  100  ):   print  (  rand3  ()  end  =  ''  )   #This code is contributed by sahilshelangia   
C#
   // C# Program to print 0 1 or 2 with equal    // probability    using     System  ;   class     GFG      {      // Random Function to that returns 0 or 1 with       // equal probability       static     int     rand2  ()         {         // rand() function will generate odd or even       // number with equal probability. If rand()       // generates odd number the function will       // return 1 else it will return 0.       Random     rand     =     new     Random  ();         return     (  rand  .  Next  ()     &     1  );         }         // Random Function to that returns 0 1 or 2 with       // equal probability 1 with 75%       static     int     rand3  ()         {         // returns 0 1 2 or 3 with 25% probability       int     r     =     2     *     rand2  ()     +     rand2  ();         if     (  r      <     3  )         return     r  ;         return     rand3  ();         }         // Driver code      static     void     Main  ()         {      for  (  int     i     =     0  ;     i      <     100  ;     i  ++  )         Console  .  Write  (  rand3  ());      }   }   // This code is contributed by divyeshrabadiya07.   
PHP
      // PHP Program to print 0 1 or    // 2 with equal probability   // Random Function to that    // returns 0 or 1 with   // equal probability   function   rand2  ()   {   // rand() function will generate    // odd or even number with equal    // probability. If rand() generates    // odd number the function will   // return 1 else it will return 0.   return   rand  ()   &   1  ;   }   // Random Function to that    // returns 0 1 or 2 with    // equal probability 1 with 75%   function   rand3  ()   {   // returns 0 1 2 or 3    // with 25% probability   $r   =   2   *   rand2  ()   +   rand2  ();   if   (  $r    <   3  )   return   $r  ;   return   rand3  ();   }   // Driver Code   // Initialize random    // number generator   srand  (  time  (  NULL  ));   for  (  $i   =   0  ;   $i    <   100  ;   $i  ++  )   echo   rand3  ();   // This code is contributed by aj_36   ?>   
JavaScript
    <  script  >      // Javascript program to print 0 1 or 2 with equal       // probability          // Random Function to that returns 0 or 1 with      // equal probability      function     rand2  ()      {          // Math.random()*2 function generates       // 0 and 1 with equal probability      return     Math  .  floor  (  Math  .  random  ()  *  2  );      }          // Random Function to that returns 0 1 or 2 with       // equal probability 1 with 75%      function     rand3  ()      {          // returns 0 1 2 or 3 with 25% probability      var     r     =     2     *     rand2  ()     +     rand2  ();          if     (  r      <     3  )      return     r  ;      return     rand3  ();      }          var     ans     =     ''  ;     //to store the output      for  (  var     i     =     0  ;     i      <     100  ;     i  ++  )      ans     +=     rand3  ();          document  .  write  (  ans  );          // This code is contributed by shruti456rawal    <  /script>   

Producción :  
 

2111011101112002111002020210112022022022211100100121202021102100010200121121210122011022111020 


Otra solución - 
Si x = rand2() e y = rand2() x + y devolverá 0 y 2 con un 25% de probabilidad y 1 con un 50% de probabilidad. Para hacer que la probabilidad de 1 sea igual a la de 0 y 2, es decir, 25%, eliminamos un evento no deseado que resulta en x + y = 1, es decir, (x = 1 y = 0) o (x = 0 y = 1). 
 

int rand3() { int x y; do { x = rand2(); y = rand2(); } while (x == 0 && y == 1); return x + y; } 


Tenga en cuenta que las soluciones anteriores producirán resultados diferentes cada vez que las ejecutemos.