Реализуйте rand3 () с помощью rand2 ()
Учитывая функцию rand2 (), которая возвращает 0 или 1 с равной вероятностью, реализуйте rand3 () с помощью rand2 (), которая возвращает 0, 1 или 2 с равной вероятностью. Минимизируйте количество вызовов метода rand2 (). Также запрещено использование любых других библиотечных функций и арифметических операций с плавающей запятой.
The idea is to use expression 2 * rand2() + rand2(). It returns 0, 1, 2, 3 with equal probability. To make it return 0, 1, 2 with equal probability, we eliminate the undesired event 3.
Below is the implementation of above idea –
C++
// C++ Program to print 0, 1 or 2 with equal// probability#include <iostream>using namespace std;// Random Function to that returns 0 or 1 with// equal probabilityint 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 functionsint 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 // probabilityimport 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# Probabilityimport random# Random Function to that returns 0 or 1 with# equal probabilitydef rand2(): # randint(0,100) function will generate odd or even # number [1,100] 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 functionsif __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 // probabilityusing 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// PHP Program to print 0, 1 or// 2 with equal probability// Random Function to that// returns 0 or 1 with// equal probabilityfunction 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 generatorsrand(time(NULL));for($i = 0; $i < 100; $i++) echo rand3();// This code is contributed by aj_36?> |
Выход :
2111011101112002111002020210112022022022211100100121202021102100010200121121210122011022111020
Другое решение -
Если x = rand2 () и y = rand2 (), x + y вернет 0 и 2 с вероятностью 25% и 1 с вероятностью 50%. Чтобы сделать вероятность 1 равной вероятности 0 и 2, то есть 25%, мы устраняем одно нежелательное событие, которое приводит к x + y = 1, т.е. либо (x = 1, y = 0), либо (x = 0, y = 1) .
int rand3 ()
{
int x, y;
делать {
х = ранд2 ();
у = rand2 ();
} while (x == 0 && y == 1);
вернуть x + y;
}Обратите внимание, что приведенные выше решения будут давать разные результаты каждый раз, когда мы их запускаем.
Эта статья предоставлена Адитьей Гоэлем . Если вам нравится GeeksforGeeks, и вы хотели бы внести свой вклад, вы также можете написать статью на сайте deposit.geeksforgeeks.org или отправить свою статью по электронной почте: grant@geeksforgeeks.org. Посмотрите, как ваша статья появляется на главной странице GeeksforGeeks, и помогите другим гикам.
Пожалуйста, напишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по теме, обсужденной выше.
Вниманию читателя! Не прекращайте учиться сейчас. Освойте все важные концепции DSA с помощью самостоятельного курса DSA по приемлемой для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .
Если вы хотите посещать живые занятия с отраслевыми экспертами, пожалуйста, обращайтесь к Geeks Classes Live и Geeks Classes Live USA.