Simplify Probability function with priority

1

I have this function that works the way I want it to. It gets a value between -2 to 2 to set the priority to choose between two strings.

My question is: How can I simplify the function?

function random_str($val){
   if($var == '-2') { $out = array('str1','str2','str2','str2'); }else
   if($var == '-1') { $out = array('str1','str2','str2'); }else
   if($var ==  '0') { $out = array('str1','str2',); }else
   if($var ==  '1') { $out = array('str1','str1','str2'); }else
   if($var ==  '2') { $out = array('str1','str1','str1','str2'); }
   return $out[array_rand($out)];
}
    
asked by anonymous 29.06.2015 / 16:44

1 answer

1

By analyzing your% of values, regardless of the value, it will always have 2 elements that are if and str1 , then seeing the difference of the others means that when it is less than str2 then you must have 0 e when it is necessary that str2 must have 0 .

function random_str($val){
    // padrão
    $out = array('str1', 'str2');

    while ($var != 0) {

        // menor que zero
        if ($var < 0) {
            array_push($out, 'str2');
            $var++;
        } else { // maior que zero
            array_push($out, 'str1');
            $var--;
        }
    }
    return $out[array_rand($out)];
}

That way it works until you enter values less than str1 and greater than -2 following the same logic, if you do not want to add a 2 .

    
29.06.2015 / 17:22