Skip to content

Instantly share code, notes, and snippets.

@Zegnat
Created August 22, 2016 12:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zegnat/04524da84c28e9965c6c6cce87eac13d to your computer and use it in GitHub Desktop.
Save Zegnat/04524da84c28e9965c6c6cce87eac13d to your computer and use it in GitHub Desktop.
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