user
Given a weighted one-bit generator of random numbers where the probability of a one occurring,

P

1
{\displaystyle {\displaystyle P\_{1}}}

, is not the same as

P

0
{\displaystyle {\displaystyle P\_{0}}}

, the probability of a zero occurring, the probability of the occurrence of a one followed by a zero is

P

1
{\displaystyle {\displaystyle P\_{1}}}

×

P

0
{\displaystyle {\displaystyle P\_{0}}}

, assuming independence. This is the same as the probability of a zero followed by a one:

P

0
{\displaystyle {\displaystyle P\_{0}}}

×

P

1
{\displaystyle {\displaystyle P\_{1}}}

.

Task details

* Use your language's random number generator to create a function/method/subroutine/... **randN** that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive.
* Create a function **unbiased** that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes.
* For N over its range, generate and show counts of the outputs of randN and unbiased(randN).

The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN.

This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
assistant
(formerly Perl 6)

**Translation of**: Perl

**Works with**: Rakudo version 2020.08.1

```
sub randN ( $n where 3..6 ) {
    return ( $n.rand / ($n - 1) ).Int;
}

sub unbiased ( $n where 3..6 ) {
    my $n1;
    repeat { $n1 = randN($n) } until $n1 != randN($n);
    return $n1;
}

my $iterations = 1000;
for 3 .. 6 -> $n {
    my ( @raw, @fixed );
    for ^$iterations {
        @raw[      randN($n) ]++;
        @fixed[ unbiased($n) ]++;
    }
    printf "N=%d   randN: %s, %4.1f%%   unbiased: %s, %4.1f%%\n",
        $n, map { .raku, .[1] * 100 / $iterations }, @raw, @fixed;
}

```

Output:

```
N=3   randN: [676, 324], 32.4%   unbiased: [517, 483], 48.3%
N=4   randN: [734, 266], 26.6%   unbiased: [489, 511], 51.1%
N=5   randN: [792, 208], 20.8%   unbiased: [494, 506], 50.6%
N=6   randN: [834, 166], 16.6%   unbiased: [514, 486], 48.6%
```