Skip to content

Instantly share code, notes, and snippets.

@Zegnat Zegnat/QBool.php
Created Aug 22, 2016

Embed
What would you like to do?
For when you need a quantum boolean that is true only some percent of the time.
<?php
namespace Zegnat;
class QBool
{
public $chance;
public $scale;
public function __construct($chance)
{
if (is_int($chance)) {
$chance = strval($chance);
} elseif (is_float($chance)) {
$chance = strval($chance);
str_replace(localeconv()['decimal_point'], '.', $chance);
}
if (is_string($chance) && strlen($chance) > 0 && preg_match('/^(?=.*\d.*)\d*\.?\d*$/', $chance) === 1) {
$decimalposition = strpos($chance, '.');
if ($decimalposition !== false) {
$scale = strlen(rtrim($chance, '0')) - $decimalposition - 1;
} else {
$scale = 0;
}
if (bccomp($chance, '0', $scale) === -1 || bccomp($chance, '1', $scale) === 1) {
echo 'Out of range.';
}
$this->scale = $scale;
$this->chance = $chance;
} else {
echo 'Not a valid chance string.';
}
}
public function getChance(): string
{
return bcadd($this->chance, '0', $this->scale);
}
public function asBool(): bool
{
$random = '0.';
for ($i = 0; $i < $this->scale; $i++) {
$random .= random_int(0, 9);
}
return bccomp($this->chance, $random, $this->scale) === 1;
}
public function asBoolean(): bool
{
return $this->asBool();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.