<?php

require_once dirname(__DIR__) . '/tools.php';

/**
 * Triangular
 */
class triangular
{
    public $left;

    public $mode;

    public $right;

    public $ratio;

    public $leftprod;

    public $rightprod;

    public function __construct($left, $mode, $right)
    {
        $left  = formatDigit($left);
        $mode  = formatDigit($mode);
        $right = formatDigit($right);

        $this->left  = $left; // 0
        $this->mode  = $mode; // 10
        $this->right = $right; // 30

        $base = $right - $left; // 30
        $leftbase = $mode - $left; // 10
        $ratio = $leftbase / $base; // 0.333

        $this->ratio = $ratio;
        $this->leftprod = $leftbase * $base; // 300
        $this->rightprod = ($right - $mode) * $base; // 600
    }

    /**
     * Generate random digit of triangular distribution.
     *
     * @access public
     * @return float
     */
    public function rand()
    {
        $rand  = mt_rand(0, \PHP_INT_MAX) / \PHP_INT_MAX;
        $left  = $this->left;
        $right = $this->right;
        $ratio = $this->ratio;
        if($rand >= $ratio)
        {
            $rand  = 1 - $rand;
            $ratio = 1 - $ratio;
            $right = $this->left;
            $left  = $this->right;
        }
        return $left + ($right - $left) * sqrt($rand * $ratio);
    }
}
