관리 메뉴

웹개발자의 기지개

[PHP] 배열값 가중치별로 랜덤값 얻어오기 본문

PHP

[PHP] 배열값 가중치별로 랜덤값 얻어오기

http://portfolio.wonpaper.net 2021. 9. 9. 04:23

특정한 값들 중에서 랜덤한 값을 가져올때, 가중치를 적용하여 해당 값을 얻어오고 싶을때,

아래의 소스를 유용하게 이용할 수 있을것 같다.

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?
function weighted_random($weights) {
  $r = rand(1, array_sum($weights));
  for($i=0$i<count($weights); $i++) {
    $r -= $weights[$i];
    if($r < 1return $i;
  }
  return false;
}
 
 
$values = ['a','b','c'];
$weights = [10,20,70];
 
/*
$index = weighted_random($weights);
$result = $values[$index];
echo $result;
*/
 
for($i=0;$i<50;$i++) {
  $index = weighted_random($weights);
  $result = $values[$index];
  echo "$result<br/>";
}
?>
cs

 

참고 : https://zetawiki.com/wiki/%EA%B0%80%EC%A4%91%EC%B9%98_%EB%9E%9C%EB%8D%A4_%EA%B5%AC%ED%95%98%EA%B8%B0

Comments