Programs that generate a probability of 0 and 1 can be adjusted according to the settings:
#include <stdio.h>#include <stdlib.h>int EqualProbability() { if (rand() % 2 == 0) { return 0; } else { return 1; }}int BiasProbability(int parameter) { int size = parameter + 1; if (rand() % size == 0) { return 0; } else { return 1; }}int main(int argc, char** argv) { int zero_counter = 0; int one_counter = 0; const int kGenerateTime = 1000000; for (int i = 0; i < kGenerateTime; ++i) { if (EqualProbability() == 0) { zero_counter++; } else { one_counter++; } } printf("zero:%d one:%d\n", zero_counter, one_counter); zero_counter = 0; one_counter = 0; for (int i = 0; i < kGenerateTime; ++i) { if (BiasProbability(10) == 0) { zero_counter++; } else { one_counter++; } } printf("zero:%d one:%d\n", zero_counter, one_counter);}
Related questions:
Known as a random generator, the probability of generating 0 is P, and the probability of generating 1 is 1-P. Now you need to construct a generator,
So that the probability of constructing 0 and 1 is 1/2. Construct a generator so that the probability of constructing 1, 2, and 3 is 1/3 ;...,
Construct a generator so that the probability of constructing 1, 2, 3,... n is 1/N, requiring the lowest complexity.
For n = 2, 01 indicates 0, 10 indicates 1, and other probabilities. In other cases, discard
For n = 3, 001 indicates 1, 010 indicates 2,100 indicates 3, and other probabilities.
For N = 4, think 0001 represents 1, 0010 represents 2, 0100 represents 3, represents 4, and other probability, other circumstances give up