#
# rand_poset(n) generates a random poset on n vertices, by flipping a fair
#  coin to decide whether [i,j] should be a relation, for 1 <= i < j <= n.
#  Then the covering relation of the transitive closure is returned.
# rand_poset(n,p) does the same, except using a biased coin for which the
#  probability of including the edge [i,j] is p (0<p<1).
# rand_poset(n,coin) does the same, using the procedure coin()
#  to generate coin tosses (1==include edge; anything else==no edge).
#
`posets/rand_poset`:=proc(n) local coin,i,j,bias,P;
  coin:=proc(x,p) if rand()<p then x fi end;
  if nargs=1 then bias:=0.5*10^12
    elif type(args[2],'numeric') then bias:=args[2]*10^12
    elif type(args[2],'procedure') then bias:=args[2];
      coin:=proc(x,f) if f()=1 then x fi end;
    else ERROR(`second argument must be numeric or a procedure`)
  fi;
  P:={seq(seq(coin([i,j],bias),j=i+1..n),i=1..n)};
  posets['covers'](P,[$1..n]);
end:
#
save `posets/rand_poset`, cat(HomeLib,`/posets/rand_poset.m`);
read cat(HomeLib,`/help/posets/rand_poset`);
quit;

