NchooseK

From WeBWorK_wiki
Jump to navigation Jump to search

NchooseK

Description

Randomly chooses an array of k entries from the array 0 .. (n-1). (n entries beginning with 0)

Syntax

NchooseK($n, $k)

Params

$n -- the length of the original array
$k -- the length of the sub array

Returns

A subarray of length k with entries between 0 and (n-1)

Examples

To obtain 3 random letters from the first five letters of the alphabet.

@slice = NchooseK(5,3) # @slice might be (1, 0, 3)
@random_letters = A..Z[@slice]
# @random_letters will now contain the subarray (B, A, D) taken from the array (A, B, C, D, E, ..... Z)
#(Remember that perl arrays begin indexing with zero.)


A fancy way to obtain a permuation of an array:

@permuted_array = @array[ NchooseK($#array, $#array) ]

Notes

Defined in [PGchoicemacros.pl]