#C1.txt: Maple Code for ExpMath Spring 2021,Lecture 1, Jan. 21, 2021 Help:=proc(): print(` LC(p) , IsDer(pi), RandPer(n) `): end: #LC(p): Inputs a RATIONAL number p and outputs a pseudo-random number #1 with probability p and 2 with probability 1-p LC:=proc(p) local m,n,r: if not ( type(p,numeric) and p>=0 and p<=1) then RETURN(FAIL): fi: if p=0 then RETURN(2): fi: if p=1 then RETURN(1): fi: if not type(p,fraction) then RETURN(FAIL): fi: m:=numer(p): n:=denom(p): r:=rand(1..n)(): if r<=m then 1: else 2: fi: end: #DEF: A derangement of {1, ...,n} is a permutation such that pi[i]<>i for every i #IsDer(pi): inputs a permutation of {1,...,n} pi (n=nops(pi)) #and outputs true iff it is a derangement IsDer:=proc(pi) local n,i: n:=nops(pi): for i from 1 to n do if pi[i]=i then RETURN(false): fi: od: true: end: #RandDer(n): Generates a random derangement using the NAIVE approach suggested by #Alon Itai in his not entirely-raving Math review of the Nijenhuius-Wilf classic RandDer:=proc(n) local pi: pi:=randperm(n): while not IsDer(pi) do pi:=randperm(pi): od: pi: end: