From dc6596b5abf7541f3f819909a0d626c5fd433b68 Mon Sep 17 00:00:00 2001 From: hide_d Date: Wed, 28 Mar 2018 04:42:13 +0900 Subject: [PATCH] =?UTF-8?q?=EC=9E=90=EC=A3=BC=20=EC=82=AC=EC=9A=A9?= =?UTF-8?q?=ED=95=A0=20random,=20=EC=88=98=EC=8B=9D=20=EB=B9=84=EA=B5=90?= =?UTF-8?q?=20=ED=95=A8=EC=88=98=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/sammo/Util.php | 66 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/src/sammo/Util.php b/src/sammo/Util.php index bdb2ee54..2ee61211 100644 --- a/src/sammo/Util.php +++ b/src/sammo/Util.php @@ -169,6 +169,72 @@ class Util extends \utilphp\util{ return $dict; } + + /** + * 0.0~1.0 사이의 랜덤 float + * @return float + */ + public static function randF(){ + return mt_rand() / mt_getrandmax(); + } + + /** + * $prob의 확률로 true를 반환 + * @return boolean + */ + public static function randBool($prob = 0.5){ + return randF() < $prob; + } + /** + * $min과 $max 사이의 값으로 교정 + */ + public static function valueFit($value, $min, $max){ + if($value < $min){ + return $min; + } + if($value > $max){ + return $max; + } + return $value; + } + + /** + * 각 값의 비중에 따라 랜덤한 값을 선택 + * + * @param array 각 수치의 비중 + * + * @return object 선택된 랜덤 값의 key값. 단순 배열인 경우에는 index + */ + public static function choiceRandomUsingWeight(array $items){ + $sum = 0; + foreach($items as $value){ + $sum += $value; + } + + $rd = self::randF()*$sum; + foreach($items as $key=>$value){ + if($rd <= $value){ + return $key; + } + $rd -= $value; + } + + //fallback. 이곳으로 빠지지 않음 + end($items); + return key($items); + } + + /** + * 배열의 아무거나 고름. Python의 random.choice() + * + * @param array 선택하고자 하는 배열 + * + * @return object 선택된 value값. + */ + public static function choiceRandom(array $items){ + return $items[array_rand($items)]; + } + }; \ No newline at end of file