diff --git a/assessment/macros/randomizers.php b/assessment/macros/randomizers.php index c78391f53..4cfac0564 100644 --- a/assessment/macros/randomizers.php +++ b/assessment/macros/randomizers.php @@ -9,7 +9,9 @@ 'rands', 'rrands', 'randfrom', + 'randkeyfrom', 'randsfrom', + 'randkeysfrom', 'jointrandfrom', 'diffrandsfrom', 'nonzerorand', @@ -138,6 +140,23 @@ function randfrom($lst) { } +function randkeyfrom($lst) { + if (func_num_args() != 1) { + echo "randkeyfrom expects 1 argument"; + return 1; + } + if (!is_array($lst)) { + echo "randkeyfrom expects an array"; + return 1; + } + if (count($lst) == 0) { + echo 'cannot pick randkeyfrom empty array'; + return ''; + } + return $GLOBALS['RND']->array_rand($lst, 1); +} + + function randsfrom($lst, $n, $ord = 'def') { if (func_num_args() < 2) { echo "randsfrom expects 2 arguments"; @@ -163,6 +182,27 @@ function randsfrom($lst, $n, $ord = 'def') { } +function randkeysfrom($lst, $n = 1) { + if (func_num_args() < 1) { + echo "randkeysfrom expects at least 1 argument"; + return 1; + } + if (!is_array($lst)) { + echo "randkeysfrom expects an array"; + return 1; + } + $n = floor($n); + if ($n <= 0) { + echo "randkeysfrom: need n > 0"; + } + if (count($lst) == 0) { + echo 'cannot pick randkeysfrom empty array'; + return ''; + } + return $GLOBALS['RND']->array_rand($lst, $n); +} + + function jointrandfrom() { $args = func_get_args(); if (count($args) < 2) { diff --git a/help.html b/help.html index 08e1791ba..45ba8aa7c 100644 --- a/help.html +++ b/help.html @@ -2332,6 +2332,8 @@

Randomizers

$arr = [10,20,30] $val = randfrom($arr) // might return 20 +
  • randkeyfrom(array): Return a random key from the array. +
    Example
    $x = randkeyfrom(["a"=>"A", "b"=>"B", "c"=>"C"])  // e.g. $x="b"
  • randname(),randmalename(),randfemalename(): Returns a random first name
    Example
    $name = randname()       // might return "Sofia"
     $name = randmalename()   // might return "Carlos"
    @@ -2369,6 +2371,9 @@ 

    Randomizers

    Example
    $a,$b = randsfrom("red,green,blue,yellow", 2)  // e.g. "blue", "red"
     $arr = [2,4,6,8]
     $a,$b = randsfrom($arr, 2, 'inc');         // sorted ascending, e.g. 2, 6
  • +
  • randkeysfrom(array,n): Return n random keys from the array. +
    Example
    $arr = [0=>'x_0', 1=>'x_1', 2=>'x_2', 3=>'x_3']
    +$a,$b = randkeysfrom($arr, 2);  // e.g., $a=2, $b=0
  • jointrandfrom(list/array,list/array,[list/array,...]): Returns one element from each list, where the location used in each list is the same
    Example
    $first,$last = jointrandfrom("Alice,Bob,Carlos", "Smith,Jones,Rivera")
     // picks the same index from each list, so names stay paired: