Deal
?
|
Deal (?
) is a dyadic primitive function which returns a random partial permutation. The name Deal comes from the analogy of dealing cards in a card game such as Poker. Both arguments of k?n
must be non-negative integer scalars with k≤n
, and Deal generates a random k-permutation by selecting k
numbers from the first n
indices without replacement. Some dialects, such as J, treat Deal as a scalar function. Deal shares the glyph ?
with the monadic scalar function Roll.
Examples
Deal can be used to generate a random permutation of a given size, and shuffle an array using it.
?⍨10 7 4 3 10 6 2 1 8 9 5 v←'shuffling array' v[?⍨≢v] n airuhflryfags
It can also simulate a card game, e.g. deal a hand of 5 cards out of a standard 52-card deck.
numbers←'23456789TJQKA' suits←'CDSH' ⍝ Club, Diamond, Spade, Heart cards←,numbers∘.,suits cards[5?≢cards] ┌──┬──┬──┬──┬──┐ │5S│KS│JH│6D│9C│ └──┴──┴──┴──┴──┘
Description
Both arguments of k?n
must be non-negative integer scalars with k≤n
. The result of Deal is a vector of length k
, whose elements are pairwise distinct random values picked from ⍳n
.
The possible number of permutations generated for particular values of k
and n
is .
Deal depends on index origin. In particular, it picks k numbers from 1 to n if ⎕IO←1
, and from 0 to n-1 if ⎕IO←0
.
The choices made by Deal do not have to be truly random: they may be pseudorandom (generated by a deterministic but difficult to predict algorithm) or taken from the operating system. They way random numbers are generated is controlled by the random link ⎕RL
. Note that using pseudorandom numbers for Deal may not be ideal for generating large permutations, since the possible number of permutations generated is bounded by the cycle length of the random number generator used. Traditionally, APL uses the Lehmer random number generator, but Dyalog APL defaults to the allow choosing a different random number generator and defaults to the Mersenne Twister.