<?php
/**
 * Created by PhpStorm.
 * User: stanley-king
 * Date: 16/6/21
 * Time: 下午4:01
 */

namespace bonus;


class allocator
{
    private function get_maxamount($total,$num)
    {
        $avg = doubleval($total / $num);
        return intval($avg * 2 + 0.5);
    }

    private function get_minamount($total,$num)
    {
        $avg = doubleval($total / $num);
        $avg = $avg / 10;
        $avg = intval($avg + 0.5);

        return $avg;
    }

    public function separate_money($min_amount,$total_amount,$total_num,&$min_val,&$max_val)
    {
        $min_amount = intval(doubleval($min_amount) * 100 + 0.5);
        $base_amount = $min_amount;
        $num = intval($total_num);

        $ret = array();
        for ($i = 0; $i < $num; $i++) {
            array_push($ret,$base_amount);
        }

        $total_amount = intval(intval(doubleval($total_amount) * 100 + 0.5) - $num * $base_amount);
        $min_amount = $this->get_minamount($total_amount,$num);

        if($min_amount > 0)
        {
            foreach($ret as &$val) {
                $val += $min_amount;
            }
            $total_amount -= $min_amount * $num;
        }

        $max_val = 0;
        $max_amount = $this->get_maxamount($total_amount,$num);
        for ($i = 0; $i < $num && $total_amount > 0;)
        {
            $amount = intval(mt_rand(0, $max_amount));
            $amount = $amount > $total_amount ? $total_amount : $amount;

            $ret[$i] += $amount;
            $total_amount -= $amount;
            $max_val = $ret[$i] > $max_val ? $ret[$i] : $max_val;

            if($i == $num -1) {
                $i = 0;
            } else {
                $i++;
            }
        }

        $max_val = doubleval($max_val) / 100;
        $min_val = $ret[0];
        foreach ($ret as &$val) {
            $min_val = $min_val > $val ? $val : $min_val;
            $val = doubleval($val) / 100;
        }
        $min_val = doubleval($min_val) / 100;

        for($index = 0; $index < $num - 1; $index++) {
            $pos_a = mt_rand(0, $num - 1);
            $pos_b = mt_rand(0, $num - 1);

            $tmp = $ret[$pos_a];
            $ret[$pos_a] = $ret[$pos_b];
            $ret[$pos_b] = $tmp;
        }

        return $ret;
    }
}