한 줄에 rand6()을 사용하여 rand12() 구현

1부터 6까지의 난수를 동일한 확률로 반환하는 함수 rand6()가 주어지면 1부터 12까지의 난수를 동일한 확률로 반환하는 rand6()을 사용하여 단일 라이너 함수 rand12()를 구현합니다. 솔루션은 rand6() 메서드에 대한 호출 수를 최소화해야 합니다. 다른 라이브러리 함수 및 부동 소수점 연산을 사용할 수 없습니다.

아이디어는 표현을 사용하는 것입니다 rand6() + (rand6() % 2) * 6 . 1부터 12까지 동일한 확률로 난수를 반환합니다. 표현은 다음과 같습니다 -

 // if rand6() is even if (rand6() % 2) return 6 + rand6(); else // if rand6() is odd return rand6();  

비슷한 방식으로 작동하는 아래 표현식 중 하나를 사용할 수도 있습니다.

  • rand6() + !(rand6() % 2) * 6 또는
  • rand6() + (rand6() & 1) * 6 또는
  • rand6() + !(rand6() & 1) * 6

다음은 위의 접근 방식을 구현한 것입니다.

C++
   #include         // for rand and srand   #include         // for time   #include          using     namespace     std  ;   // Function that returns random numbers from 1 to 6 with   // equal probability   int     rand6  ()   {      // rand() will generate random numbers between 0 and      // RAND_MAX with equal probability rand() % 6 returns      // number from 0 to 5 with equal probability (rand() %      // 6) + 1 returns number from 1 to 6 with equal      // probability      return     (  rand  ()     %     6  )     +     1  ;   }   // The function uses rand6() to return random numbers from 1   // to 12 with equal probability   int     rand12  ()     {     return     rand6  ()     +     (  rand6  ()     %     2  )     *     6  ;     }   // Driver code to test above functions   int     main  ()   {      // Initialize random number generator      srand  (  time  (  NULL  ));      int     N     =     12  ;      int     freq  [  N     +     1  ]     =     {     0     };      // call rand12() multiple times and store its results      for     (  int     i     =     0  ;     i      <     N     *     100000  ;     i  ++  )      freq  [  rand12  ()]  ++  ;      // print frequency of numbers 1-12      for     (  int     i     =     1  ;     i      <=     N  ;     i  ++  )      cout      < <     freq  [  i  ]      < <     ' '  ;      return     0  ;   }   
Java
   import     java.util.Random  ;   public     class   RandomNumbers     {      public     static     int     rand6  ()     {      Random     random     =     new     Random  ();      //nextInt(6) generates a random number from 0 to 5      return     random  .  nextInt  (  6  )     +     1  ;      }      public     static     int     rand12  ()     {      return     rand6  ()     +     (  rand6  ()     %     2  )     *     6  ;      }      public     static     void     main  (  String  []     args  )     {      int     N     =     12  ;      int  []     freq     =     new     int  [  N     +     1  ]  ;      // Initialize random number generator      Random     random     =     new     Random  ();      // Call rand12() multiple times and store its results      for     (  int     i     =     0  ;     i      <     N     *     100000  ;     i  ++  )     {      freq  [  rand12  ()  ]++  ;      }      // Print the frequency of numbers 1-12      for     (  int     i     =     1  ;     i      <=     N  ;     i  ++  )     {      System  .  out  .  print  (  freq  [  i  ]     +     ' '  );      }      }   }   
Python
   import   random   # Create a single instance of Random for better performance   rand   =   random  .  Random  ()   # Function that returns random numbers from 1 to 6 with equal probability   def   rand6  ():   return   rand  .  randint  (  1     6  )   # The function uses rand6() to return random numbers from 1 to 12 with equal probability   def   rand12  ():   return   rand6  ()   +   (  rand6  ()   %   2  )   *   6   # Driver code to test above functions   if   __name__   ==   '__main__'  :   N   =   12   iterations   =   100000   freq   =   [  0  ]   *   (  N   +   1  )   # call rand12() multiple times and store its results   for   _   in   range  (  iterations  ):   freq  [  rand12  ()]   +=   1   # print frequency of numbers 1-12   for   i   in   range  (  1     N   +   1  ):   print   freq  [  i  ]   # Wait for user input to keep the console window open   try  :   raw_input  (  'Press Enter to exit'  )   except   EOFError  :   pass   
C#
   using     System  ;   class     Program   {      // Create a single instance of Random for better performance      static     Random     rand     =     new     Random  ();      // Function that returns random numbers from 1 to 6 with equal probability      static     int     Rand6  ()      {      return     rand  .  Next  (  1       7  );      }      // The function uses Rand6() to return random numbers from 1 to 12 with equal probability      static     int     Rand12  ()      {      return     Rand6  ()     +     (  Rand6  ()     %     2  )     *     6  ;      }      // Driver code to test above functions      static     void     Main  ()      {      int     N     =     12  ;      int     iterations     =     100000  ;      int  []     freq     =     new     int  [  N     +     1  ];      // call Rand12() multiple times and store its results      for     (  int     i     =     0  ;     i      <     iterations  ;     i  ++  )      freq  [  Rand12  ()]  ++  ;      // print frequency of numbers 1-12      for     (  int     i     =     1  ;     i      <=     N  ;     i  ++  )      Console  .  Write  (  freq  [  i  ]     +     ' '  );      Console  .  ReadLine  ();     // Added to keep the console window open until a key is pressed      }   }   
JavaScript
   function     rand6  ()     {      // Generates a random number from 1 to 6      return     Math  .  floor  (  Math  .  random  ()     *     6  )     +     1  ;   }   function     rand12  ()     {      return     rand6  ()     +     (  rand6  ()     %     2  )     *     6  ;   }   const     N     =     12  ;   const     freq     =     new     Array  (  N     +     1  ).  fill  (  0  );   // Call rand12() multiple times and store its results   for     (  let     i     =     0  ;     i      <     N     *     100000  ;     i  ++  )     {      freq  [  rand12  ()]  ++  ;   }   // Print the frequency of numbers 1-12   for     (  let     i     =     1  ;     i      <=     N  ;     i  ++  )     {      console  .  log  (  freq  [  i  ]);   }   

산출:

 100237 100202 99678 99867 100253 99929 100287 100449 99827 99298 100019 99954   

또 다른 해결책:

 int rand12() { return (rand6() * 2) - (rand6() & 1); }  
  • 랜드6() * 2: 그러면 동일한 확률로 짝수 2 4 6 8 10과 12가 반환됩니다.
  • 랜드6() & 1 : rand6()이 각각 짝수 또는 홀수인지에 따라 0 또는 1을 반환합니다. 그래서 표현은
  • (rand6() * 2) - (rand6() & 1) : 1부터 12까지 동일한 확률로 난수를 반환합니다.

다음은 위의 접근 방식을 구현한 것입니다.

C++
   #include         #include         #include          // Assume rand6 generates a random integer between 1 and 6   int     rand6  ()     {      return     rand  ()     %     6     +     1  ;   }   int     rand12  ()     {      return     (  rand6  ()     *     2  )     -     (  rand6  ()     &     1  );   }   int     main  ()     {      // Seed the random number generator      srand  (  time  (  0  ));      // Generate a random number between 1 and 12      int     randomNum     =     rand12  ();      // Print the random number      std  ::  cout      < <     'Random number between 1 and 12: '      < <     randomNum      < <     std  ::  endl  ;      return     0  ;   }   
Java
   import     java.util.Random  ;   public     class   Main     {      private     static     final     Random     rand     =     new     Random  ();      // Assume rand6 generates a random integer between 1 and 6      public     static     int     rand6  ()     {      return     rand  .  nextInt  (  6  )     +     1  ;      }      public     static     int     rand12  ()     {      return     (  rand6  ()     *     2  )     -     (  rand6  ()     &     1  );      }      public     static     void     main  (  String  []     args  )     {      // Generate a random number between 1 and 12      int     randomNum     =     rand12  ();      // Print the random number      System  .  out  .  println  (  'Random number between 1 and 12: '     +     randomNum  );      }   }   
Python
   import   random   def   rand6  ():      '''    Generates a random integer between 1 and 6 inclusive.    Returns:    int: A random integer between 1 and 6.    '''   return   random  .  randint  (  1     6  )   def   rand12  ():      '''    Generates a random integer between 1 and 12 inclusive.    Returns:    int: A random integer between 1 and 12.    '''   # Generate two random numbers between 1 and 6   num1   =   rand6  ()   num2   =   rand6  ()   # Calculate the result using the formula: (2 * num1) - (num2 & 1)   result   =   (  2   *   num1  )   -   (  num2   &   1  )   # Ensure the result is within the range of 1 to 12   if   result   >   12  :   result   =   result   %   12   return   result   if   __name__   ==   '__main__'  :   # Seed the random number generator   random  .  seed  ()   # Generate a random number between 1 and 12   random_num   =   rand12  ()   # Print the random number   print  (  'Random number between 1 and 12:'     random_num  )   
JavaScript
   /**    * Generates a random integer between 1 and 6 inclusive.    *    * @returns {number} A random integer between 1 and 6.    */   function     rand6  ()     {      return     Math  .  floor  (  Math  .  random  ()     *     6  )     +     1  ;   }   /**    * Generates a random integer between 1 and 12 inclusive.    *    * @returns {number} A random integer between 1 and 12.    */   function     rand12  ()     {      // Generate two random numbers between 1 and 6      let     num1     =     rand6  ();      let     num2     =     rand6  ();      // Calculate the result using the formula: (2 * num1) - (num2 & 1)      let     result     =     (  2     *     num1  )     -     (  num2     %     2  );      // Ensure the result is within the range of 1 to 12      if     (  result     >     12  )     {      result     =     result     %     12  ;      if     (  result     ===     0  )     {      result     =     12  ;      }      }      return     result  ;   }   // Generate a random number between 1 and 12   let     randomNum     =     rand12  ();   // Print the random number   console  .  log  (  'Random number between 1 and 12:'       randomNum  );   

산출
Random number between 1 and 12: 7