Simplify Probability function with priority

Asked

Viewed 69 times

1

I have this function that works as I want. It takes a value between -2 and 2 to set the priority to choose between two strings.

My point 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)];
}

1 answer

1


Analyzing their if regardless of the value it will always have 2 elements that are the str1 and str2, then seeing the difference of others means that when it is less than 0 then you need to have str2 and when 0 need to have str1.

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)];
}

This way it works until you enter values smaller than -2 and greater than 2 following the same logic, if you do not want to add a if/return.

  • Good, I like this solution! ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.