Генерация 0 и 1 с вероятностью 25% и 75%
Для функции rand50 (), которая возвращает 0 или 1 с равной вероятностью, напишите функцию, которая возвращает 1 с вероятностью 75% и 0 с вероятностью 25%, используя только rand50 (). Минимизируйте количество вызовов метода rand50 (). Также запрещено использование любых других библиотечных функций и арифметических операций с плавающей запятой.
Рекомендуется: сначала попробуйте свой подход в {IDE}, прежде чем переходить к решению.
Идея состоит в том, чтобы использовать побитовое ИЛИ . Побитовое ИЛИ принимает два бита и возвращает 0, если оба бита равны 0, в противном случае результат равен 1. Таким образом, вероятность того, что оно вернет 1, составляет 75%.
Below is the implementation of above idea :
C++
// Program to print 1 with 75% probability and 0 // with 25% probability #include <iostream> using namespace std; // Random Function to that returns 0 or 1 with // equal probability int rand50() { // 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 1 with 75% // probability and 0 with 25% probability using // Bitwise OR bool rand75() { return rand50() | rand50(); } // Driver code to test above functions int main() { // Initialize random number generator srand ( time (NULL)); for ( int i = 0; i < 50; i++) cout << rand75(); return 0; } |
Java
// Java program to print 1 with 75% probability and 0 // with 25% probability class GFG { // Random Function to that returns 0 or 1 with // equal probability static int rand50() { // 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 ( int ) ( 10 * Math.random()) & 1 ; } // Random Function to that returns 1 with 75% // probability and 0 with 25% probability using // Bitwise OR static int rand75() { return rand50() | rand50(); } // Driver code public static void main(String[] args) { // Initialize random number generator //srand(time(null)); for ( int i = 0 ; i < 50 ; i++) { System.out.print(rand75()); } } } // This code is contributed by 29AjayKumar |
PHP
<?php // Program to print 1 with 75% probability // and 0 with 25% probability // Random Function to that returns 0 or // 1 with equal probability function rand50() { // 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 // 1 with 75% probability and 0 // with 25% probability using // Bitwise OR function rand75() { return rand50() | rand50(); } // Driver Code // Initialize random // number generator srand(time(NULL)); for ( $i = 0; $i < 50; $i ++) echo rand75(); // This code is contributed m_kit ?> |
Output:
11101111110010010110011111111101111110111100011000
В аналогичных строках мы также можем использовать побитовое И. Поскольку он возвращает 0 с вероятностью 75%, мы должны инвертировать результат.
// Случайная функция, возвращающая 1 с 75% // вероятность и 0 с вероятностью 25% с использованием // Побитовое И bool rand75 () { возврат! (rand50 () & rand50 ()); }
Мы также можем заменить побитовое ИЛИ и побитовое И операторы ИЛИ и И -
// Случайная функция, возвращающая 1 с 75% // вероятность и 0 с вероятностью 25% с использованием // Оператор ИЛИ или И int rand75 () { возврат! (rand50 () && rand50 ()); // возврат rand50 () || rand50 () }
We can also achieve the result using left shift operator and Bitwise XOR –
C++
// Program to print 1 with 75% probability and 0 // with 25% probability #include <iostream> using namespace std; // Random Function to that returns 0 or 1 with // equal probability int rand50() { // 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 1 with 75% // probability and 0 with 25% probability using // left shift and Bitwise XOR int rand75() { // x is one of {0, 1} int x = rand50(); x = x << 1; // x is now one of {00, 10} x = x ^ rand50(); // x is now one of {00, 01, 10, 11} return (x > 0) ? 1 : 0; } // Driver code to test above functions int main() { // Initialize random number generator srand ( time (NULL)); for ( int i = 0; i < 50; i++) cout << rand75(); return 0; } |
Java
// Java program to print 1 with 75% probability and 0 // with 25% probability class GFG { // Random Function to that returns 0 or 1 with // equal probability static int rand50() { // 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 ( int ) ( 10 * Math.random()) & 1 ; } // Random Function to that returns 1 with 75% // probability and 0 with 25% probability using // left shift and Bitwise XOR static int rand75() { // x is one of {0, 1} int x = rand50(); x = x << 1 ; // x is now one of {00, 10} x = x ^ rand50(); // x is now one of {00, 01, 10, 11} return (x > 0 ) ? 1 : 0 ; } // Driver code public static void main(String[] args) { for ( int i = 0 ; i < 50 ; i++) System.out.print(rand75()); } } // This code is contributed by 29AjayKumar |
PHP
<?php // Program to print 1 with // 75% probability and 0 // with 25% probability // Random Function to that // returns 0 or 1 with // equal probability function rand50() { // 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 1 with 75% // probability and 0 with // 25% probability using // left shift and Bitwise XOR function rand75() { // x is one of {0, 1} $x = rand50(); $x = $x << 1; // x is now one // of {00, 10} $x = $x ^ rand50(); // x is now one of // {00, 01, 10, 11} return ( $x > 0) ? 1 : 0; } // Driver code // Initialize random // number generator srand(time(NULL)); for ( $i = 0; $i < 50; $i ++) echo rand75(); // This code is contributed // by ajit ?> |
Output:
01101110111011000111111111110001111011101110110110
Обратите внимание, что приведенные выше решения будут давать разные результаты каждый раз, когда мы их запускаем.
Эта статья предоставлена Адитьей Гоэлем . Если вам нравится GeeksforGeeks, и вы хотели бы внести свой вклад, вы также можете написать статью на сайте deposit.geeksforgeeks.org или отправить свою статью по электронной почте: grant@geeksforgeeks.org. Посмотрите, как ваша статья появляется на главной странице GeeksforGeeks, и помогите другим гикам.
Пожалуйста, напишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по теме, обсужденной выше.