Rand - andreydiveev/wiki GitHub Wiki
random with special chars:
< /dev/urandom tr -dc _A-Za-z0-9\!\@\#\$\%\^\&\*\(\)-+= | head -c20; echo
pwgen special characters:
pwgen -sy 20 1
pwgen:
pwgen -s 60 1
Openssl random hex:
openssl rand -hex 32
Generate random HEX string:
# xxd -l 16 -p /dev/urandom
ASCII:
cat /dev/urandom \
| tr -dc 'a-zA-Z0-9-_!@#$%^&*()_+{}|:<>?=' \
| fold -w 32 \
| grep -i '[!@#$%^&*()_+{}|:<>?=]' \
| head -n 1
Base58:
head /dev/urandom | tr -dc 123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ | head -c 40 ; echo ''
Generate random string:
# head /dev/urandom | tr -dc A-Za-z0-9 | head -c 13 ; echo ''
PHP. Random value with probability:
<?php
function randomFactory(array $data): Closure {
$values = [];
$rand = 0;
foreach ($data as $value => $chance) {
$values[] = [
'rand' => $rand += $chance,
'value' => $value,
];
}
return function () use ($values) {
$rand = random_int(0, PHP_INT_MAX) / PHP_INT_MAX;
foreach ($values as $value) {
if ($rand < $value['rand']) {
return $value['value'];
}
}
throw new LogicException('smth get wrong');
};
}
$data = [
1 => 0.1,
2 => 0.25,
3 => 0.25,
4 => 0.4,
];
$random = randomFactory($data);
$result = array_combine(array_keys($data), array_fill(0, count($data), 0));
$attempts = 10000;
for ($i = 0; $i < $attempts; ++$i) {
$rand = $random();
++$result[$rand];
}
echo "value\tcount\texpected\treal\tdiff", PHP_EOL, PHP_EOL;
foreach ($result as $value => $count) {
$real = $count / $attempts;
$diff = abs($real - $data[$value]);
printf("%d\t%5d\t%8.2f\t%.2f\t%.2f" . PHP_EOL, $value, $count, $data[$value], $real, $diff);
}