Skip to content

Instantly share code, notes, and snippets.

@bagart
Last active October 7, 2021 16:45
Show Gist options
  • Save bagart/92f385c81468d3d792bbbc70d505bb7f to your computer and use it in GitHub Desktop.
Save bagart/92f385c81468d3d792bbbc70d505bb7f to your computer and use it in GitHub Desktop.
random3 and random4 from random2
<?php
echo "Задача: написать random3() и random4() возвращающие равновероятные значения используя только random2()\n";
echo random2() . " - random 0|1\n";
echo random3() . " - random 0|1|2\n";
echo random4() . " - random 0|1|2|3\n\n";
function random2(): int
{
return random_int(0, 1);
}
/**
* @return 0|1|2|3
*/
function random4(): int
{
return random2() + 2 * random2();
}
/**
* @return 0|1|2
*/
function random3(): int
{
$x = rr3x3();
return ("{$x[0]}{$x[1]}{$x[2]}" % 3);
}
//1,1,1
//1,1,2
//1,1,3
//всегда полная равнораспределенная комбинация 1-2-3 в каждом регистре
function rr3x3(): array
{
$x1 = 1 + random2() + random2();
$x2 = 1 + random2() + random2();
$x3 = 1 + random2() + random2();
if ($x2 === 2) {
$x2 = 1;
} elseif ($x2 === 1) {
$x2 = 2;
}
if ($x3 === 2) {
$x3 = 3;
} elseif ($x3 === 3) {
$x3 = 2;
}
return [$x1, $x2, $x3];
}
@bagart
Copy link
Author

bagart commented Oct 4, 2021

https://3v4l.org/GBXpL#v8.0.11

Задача: написать random3() и random4() возвращающие равновероятные значения используя только random2()
0 - random 0|1
1 - random 0|1|2
3 - random 0|1|2|3

@bagart
Copy link
Author

bagart commented Oct 7, 2021

2^6 не может быть. кратно трем без остатка, но это забавный математический трюк

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment