If $p$ is $\frac{n}{m}$ for some $n,m$:
find the minimum k such that $2^k \geq m$. When the coin is flipped $k$ times there are $2^k$ possible results: write all the possible results in lexicographical order and map the first $n$ results to Head and the next $m-n$ results to Tails.
Then just
Flip the coin $k$ times. If the rank of the result (in lexicographical order) is one of the first $n$, the output is Head. If the rank of the result is from $n+1$ to $m$, the output is Tails. If the rank of the result is from $m$ to $2^k$, flip the coin $2^k$ times again and repeat
Example with $p=\frac{1}{7}$:
$k$ is $3$ because $2^k = 8 \geq 7$. The possible results in lexicographical order are:
HHH
HHT
HTH
HTT
THH
THT
TTH
TTT
Flip the coin 3 times: if the resul is HHH, set the output to the biased coin to be H. If the result is one of HHT...TTH set the output to the biased coin to be T. If the result is TTT, flip the coin 3 times again and repeat.
Some optimization (thanks to @steve in the comments).
Thanks to the lexicographical order, sometimes we can stop the process before finishing all the $k$ flips. In the example above, if the first results are HT or TH we are going to output T.
Sometimes a value for $k$ greater than the minimum required will allow to discard less flips on average. For example, if $m=5$ using $k=3$
the first five outcomes will be mapped either to H or T, while the last three will result in "wasting" the three flips and repeating the process. So, every time we want a random outcome with $p=n/5$ if we use $k=3$ the expected number of coin tosses $E_3$ is equal to $3$ in $5/8$ cases, and it is equal to $3+E_3$ in the other $3/8$ cases, that is $E_3 = 3 \times 5/8 + (E_3+3) \times 3/8$. Solving for $E_3$ gives us $E_3 = 24/5 = 4.8$
However, if we use $k=4$
the first fifteen outcomes will be mapped either to H or T, and we are "wasting" the flips in just one case out of sixteen. So, every time we want a random outcome with $p=n/5$ if we use $k=4$ the expected number of coin tosses $E_4$ is equal to $4$ in $15/16$ cases, and it is equal to $4+E_4$ in the last case, that is $E_4 = 4 \times 15/16 + (E_4+4) \times 1/16$. Solving for $E_4$ gives us $E_4 = 64/15 \approx 4.267 $
double t=0.5;to the probability you want to simulate. Input a fair or biased coin as you prefer. – Steve May 20 '21 at 08:12