mercredi 8 juin 2016

Random implementation need advice

I'm currently working on a Galaxy generator, and I was in need of getting the next that a random would use, for contnuing the generation wthout using a blank generation (re-run previous generation)

so I made this little PHP class to do that, I also mplemented an float rand method

If you have any advice for improving it I will enjoy talk with you

<?php

namespace Classes;

define('GC_RAND_MAX',   0x7fffffff);

class Random
{   
    private $seed = 1;

    public function setSeed($seed) {
        $this->seed = $seed;
    }

    public function getSeed() {
        return $this->seed;
    }

    public function rand($min = 0, $max = 0) {
        $this->seed = ($this->seed * 1103515245 + 12345) & GC_RAND_MAX;
        $number = (($this->seed >> 1) & GC_RAND_MAX);

        if ($min > $max) { $min = $max; $max = $min; }
        else { $min = $min; $max = $max; }
        if ($max - $min)
            $number = ($number % ($max + 1 - $min)) + $min;

        return $number;
    }

    public function getRandMax(){
        return GC_RAND_MAX;
    }

    public function floatRand($Min, $Max, $round = 0) {
        //validate input
        if ($Min > $Max) { $Min = $Max; $Max = $Min; }
        else { $Min = $Min; $Max = $Max; }

        $range = $Max - $Min;
        $randomfloat = $Min + $range * ($this->rand() << 4 & $this->rand()) / (GC_RAND_MAX >> 1);

        if($round > 0)
            $randomfloat = round($randomfloat, $round);
        return $randomfloat;
    }
}




Aucun commentaire:

Enregistrer un commentaire