Page 1 of 1

rand() and switch() combination

Posted: Sat Feb 16, 2008 5:40 am
by Terriator
Hey, I'm currently playing around with the following function:

Code: Select all

 
function tagger(){
    $rand = rand(1,5);
    $int = rand(10,30);
    $types = "SISP";
    switch($rand){
        case 1: $tag = "DINC:$types:PERC:$int";  break;
        case 2: $tag = "DSDEC:$types:PERC:$int";  break;
        case 3: $tag = "CHAD:$types:PERC:$int";  break;
        case 4: $tag = "REFL:$types:PERC:$int";  break;
        case 5: $tag = "DSTA:$types:PERC:$int";  break;
    }
    return $tag;
}
$tag1 = tagger();
$tag2 = tagger();
$tag3 = tagger();
 
The problem is that I need to make sure that $tag1, $tag2 and $tag3 can't take on the same cases in the switch argument. That is; $tag1, $tag2 and $tag3 should each have a distinct case from the switch function. How would I do this most efficient?

Re: rand() and switch() combination

Posted: Sat Feb 16, 2008 12:10 pm
by Christopher
Maybe something like this (untested):

Code: Select all

function rand_unique(&$array){
    array_shuffle($array);
    $rand = rand(0, count($array)-1);
    $value = $array[$rand];
    unset($array[$rand]);
    return $value;
}
 
function tagger(&$array){
    $int = rand_unique($array);
    $types = "SISP";
    switch($rand){
        case 1: $tag = "DINC:$types:PERC:$int";  break;
        case 2: $tag = "DSDEC:$types:PERC:$int";  break;
        case 3: $tag = "CHAD:$types:PERC:$int";  break;
        case 4: $tag = "REFL:$types:PERC:$int";  break;
        case 5: $tag = "DSTA:$types:PERC:$int";  break;
    }
    return $tag;
}
 
$array = array_fill(1, 5);
$tag1 = tagger($array);
$tag2 = tagger($array);
$tag3 = tagger($array);