\input cwebmac
% This file is part of the Stanford GraphBase (c) Stanford University 1993
% This material goes at the beginning of all Stanford GraphBase CWEB files

\def\topofcontents{
  \leftline{\sc\today\ at \hours}\bigskip\bigskip
  \centerline{\titlefont\title}}

\font\ninett=cmtt9
\def\botofcontents{\vskip 0pt plus 1filll
    \ninerm\baselineskip10pt
    \noindent\copyright\ 1993 Stanford University
    \bigskip\noindent
    This file may be freely copied and distributed, provided that
    no changes whatsoever are made. All users are asked to help keep
    the Stanford GraphBase files consistent and ``uncorrupted,''
    identical everywhere in the world. Changes are permissible only
    if the modified file is given a new name, different from the names of
    existing files in the Stanford GraphBase, and only if the modified file is
    clearly identified as not being part of that GraphBase.
    (The {\ninett CWEB} system has a ``change file'' facility by
    which users can easily make minor alterations without modifying
    the master source files in any way. Everybody is supposed to use
    change files instead of changing the files.)
    The author has tried his best to produce correct and useful programs,
    in order to help promote computer science research,
    but no warranty of any kind should be assumed.
    \smallskip\noindent
    Preliminary work on the Stanford GraphBase project
    was supported in part by National Science
    Foundation grant CCR-86-10181.}

\def\prerequisite#1{\def\startsection{\noindent
    Important: Before reading {\sc\title},
    please read or at least skim the program for {\sc#1}.\bigskip
    \let\startsection=\stsec\stsec}}
\def\prerequisites#1#2{\def\startsection{\noindent
    Important: Before reading {\sc\title}, please read
    or at least skim the programs for {\sc#1} and {\sc#2}.\bigskip
    \let\startsection=\stsec\stsec}}



\def\title{GB\_\,RAND}

\prerequisite{GB\_\,GRAPH}

\N{1}{1}Random graphs. This GraphBase module provides two external
subroutines called \\{random\_graph} and \\{random\_bigraph}, which generate
graphs in which the arcs or edges have been selected ``at random.''  A
third subroutine, \\{random\_lengths}, randomizes the lengths of the arcs
of a given graph.  The performance of algorithms on such graphs can
fruitfully be compared to their performance on the nonrandom graphs
generated by other GraphBase routines.

Before reading this code, the reader should be familiar with the basic
data structures and conventions described in {\sc GB\_\,GRAPH}. The
routines in {\sc GB\_\,GRAPH} are loaded together with all GraphBase
applications, and the programs below are typical illustrations of how
to use them.

\Y\B\4\D$\\{random\_graph}$ \5
\\{r\_graph}\C{ abbreviations for Procrustean external linkage }\par
\B\4\D$\\{random\_bigraph}$ \5
\\{r\_bigraph}\par
\B\4\D$\\{random\_lengths}$ \5
\\{r\_lengths}\par
\Y\B\4\X1:\.{gb\_rand.h }\X${}\E{}$\6
\8\#\&{define} \\{random\_graph} \5\\{r\_graph}\C{ users of {\sc GB\_\,RAND}
should include this header info }\6
\8\#\&{define} \\{random\_bigraph} \5\\{r\_bigraph}\6
\8\#\&{define} \\{random\_lengths} \5\\{r\_lengths}\6
\&{extern} \&{Graph} ${}{*}\\{random\_graph}(\,);{}$\6
\&{extern} \&{Graph} ${}{*}\\{random\_bigraph}(\,);{}$\6
\&{extern} \&{long} \\{random\_lengths}(\,);\par
\fi

\M{2}Here is an overview of the file \.{gb\_rand.c}, the \CEE/ code for the
routines in question.

\Y\B\8\#\&{include} \.{"gb\_graph.h"}\C{ this header file teaches \CEE/ about
GraphBase }\6
\8\#\&{include} \.{"gb\_flip.h"}\C{ we will use the {\sc GB\_\,FLIP} routines
for random numbers }\6
\ATH\7
\X8:Private declarations\X\6
\X18:Internal functions\X\6
\X5:External functions\X\par
\fi

\M{3}The procedure $\\{random\_graph}(\|n,\|m,\\{multi},\\{self},\\{directed},%
\\{dist\_from},\\{dist\_to},\\{min\_len},\\{max\_len},\\{seed})$ is designed to
produce a pseudo-random graph with
\|n vertices and \|m arcs or edges, using pseudo-random numbers that
depend on \\{seed} in a system-independent fashion. The remaining parameters
specify a variety of options:
$$\vcenter{\halign{#\hfil\cr
$\\{multi}\I\T{0}$ permits duplicate arcs;\cr
$\\{self}\I\T{0}$ permits self-loops (arcs from a vertex to itself);\cr
$\\{directed}\I\T{0}$ makes the graph directed; otherwise each arc becomes
an undirected edge;\cr
\\{dist\_from} and \\{dist\_to} specify probability distributions on the arcs;%
\cr
\\{min\_len} and \\{max\_len} bound the arc lengths, which will be uniformly
distributed between these limits.\cr
}}$$
If \\{dist\_from} or \\{dist\_to} are $\NULL$, the probability distribution is
uniform over vertices; otherwise the \\{dist} parameter points to an array of
\|n nonnegative integers that sum to $2^{30}$, specifying the respective
probabilities (times $2^{30}$) that each given vertex will appear as the
source or destination of the random arcs.

A special option $\\{multi}\K{-}\T{1}$ is provided. This acts exactly like
$\\{multi}\K\T{1}$, except that arcs are not physically duplicated in computer
memory---they are replaced by a single arc whose length is the minimum
of all arcs having a common source and destination.

The vertices are named simply \.{"0"}, \.{"1"}, \.{"2"}, and so on.

Warning: Users need to initialize the random number generator before
calling \\{random\_graph}, or any other GraphBase procedure that
consumes random numbers. (See {\sc GB\_\,FLIP}.)

\fi

\M{4}Examples: $\\{random\_graph}(\T{1000},\T{5000},\T{0},\T{0},\T{0},\NULL,%
\NULL,\T{1},\T{1},\T{0})$ creates a random
undirected graph with 1000 vertices and 5000 edges (hence 10000 arcs) of
length~1, having
no duplicate edges or self-loops. There are ${1000\choose2}=499500$ possible
undirected edges on 1000 vertices; hence there are exactly $499500\choose5000$
possible graphs meeting these specifications. Every such graph would be
equally likely, if \\{random\_graph} had access to an ideal source of
random numbers. The GraphBase programs are designed to be
system-independent, so that identical graphs will be obtained by
everybody who asks for $\\{random\_graph}(\T{1000},\T{5000},\T{0},\T{0},\T{0},%
\NULL,\NULL,\T{1},\T{1},\T{0})$.
Equivalent experiments on algorithms for graph manipulation can therefore
be performed by researchers in different parts of the world.

The subroutine call $\\{random\_graph}(\T{1000},\T{5000},\T{0},\T{0},\T{0},%
\NULL,\NULL,\T{1},\T{1},\|s)$
will produce different graphs when the random seed \|s varies;
however, the graph for any particular value of~\|s will be the same on
all computers. The seed value can be any integer in the range $0\le s<2^{31}$.

To get a random directed graph, allowing self-loops and repeated arcs,
and with a uniform distribution on vertices, ask for
$$\hbox{$\\{random\_graph}(\|n,\|m,\T{1},\T{1},\T{1},\NULL,\NULL,\T{1},\T{1},%
\|s)$}.$$
Each of the $m$ arcs of that digraph has probability $1/n^2$ of being from
$u$ to $v$, for all $u$ and~$v$. If self-loops are disallowed (by
changing `$\T{1},\T{1},\T{1}$' to `$\T{1},\T{0},\T{1}$'), each arc has
probability
$1/(n^2-n)$ of being from $u$ to $v$, for all $u\ne v$.

To get a random directed graph in which vertex $k$ is twice as likely
as vertex $k+1$ to be the source of an arc but only half as likely to
be the destination of an arc, for all~$k$, try
$$\hbox{$\\{random\_graph}(\T{31},\|m,\T{1},\T{1},\T{1},\\{d0},\\{d1},\T{0},%
\T{255},\|s)$}$$
where the arrays \\{d0} and \\{d1} have the static declarations
$$\vbox{
\hbox{\&{long} \\{d0}[\T{31}]${}\K\{\T{\^20000000},\T{\^10000000},\hbox{\dots},%
\T{4},\T{2},\T{1},\T{1}\};$}
\hbox{\&{long} \\{d1}[\T{31}]${}\K\{\T{1},\T{1},\T{2},\T{4},\hbox{\dots},\T{%
\^10000000},\T{\^20000000}\};$}}$$
then about 1/4 of the arcs will run from 0 to 30, while arcs
from 30 to 0 will be extremely rare (occurring with probability $2^{-60}$).
Incidentally, the arc lengths in this example will be random bytes,
uniformly distributed between 0 and 255, because $\\{min\_len}\K\T{0}$ and
$\\{max\_len}\K\T{255}$.

If we forbid repeated arcs in this example, by setting $\\{multi}\K\T{0}$, the
effect is to discard all arcs having the same source and destination
as a previous arc, regardless of length. In such a case \|m~had better not
be too large, because the algorithm will keep going until it has found
\|m distinct arcs, and many arcs are quite rare indeed; they will
probably not be found until hundreds of centuries have elapsed.

A random bipartite graph can also be obtained as a special case of
\\{random\_graph}; this case is explained below.

Semantics:
If $\\{multi}\K\\{directed}\K\T{0}$ and $\\{self}\I\T{0}$, we have an
undirected graph without
duplicate edges but with self-loops permitted. A self-loop then consists of
two identical self-arcs, in spite of the fact that $\\{multi}\K\T{0}$.

\fi

\M{5}If the \\{random\_graph} routine encounters a problem, it returns
$\NULL$, after putting a code number into the external variable
\\{panic\_code}. This code number identifies the type of failure.
Otherwise \\{random\_graph} returns a pointer to the newly created graph
and leaves \\{panic\_code} unchanged. The \\{gb\_trouble\_code} will be
cleared to zero after \\{random\_graph} has acted.

\Y\B\4\D$\\{panic}(\|c)$ \5
${}\{{}$\5
\1${}\\{panic\_code}\K\|c{}$;\5
${}\\{gb\_trouble\_code}\K\T{0}{}$;\5
\&{return} ${}\NULL{}$;\5
${}\}{}$\2\par
\Y\B\4\X5:External functions\X${}\E{}$\6
\&{Graph} ${}{*}\\{random\_graph}(\|n,\39\|m,\39\\{multi},\39\\{self},\39%
\\{directed},\39\\{dist\_from},\39\\{dist\_to},\39\\{min\_len},\39\\{max\_len},%
\39\\{seed}){}$\1\1\6
\&{unsigned} \&{long} \|n;\C{ number of vertices desired }\6
\&{unsigned} \&{long} \|m;\C{ number of arcs or edges desired }\6
\&{long} \\{multi};\C{ allow duplicate arcs? }\6
\&{long} \\{self};\C{ allow self loops? }\6
\&{long} \\{directed};\C{ directed graph? }\6
\&{long} ${}{*}\\{dist\_from}{}$;\C{ distribution of arc sources }\6
\&{long} ${}{*}\\{dist\_to}{}$;\C{ distribution of of arc destinations }\6
\&{long} \\{min\_len}${},{}$ \\{max\_len};\C{ bounds on random lengths }\6
\&{long} \\{seed};\C{ random number seed }\2\2\6
${}\{{}$\5
\1\X6:Local variables\X\7
\&{if} ${}(\|n\E\T{0}){}$\1\5
\\{panic}(\\{bad\_specs});\C{ we gotta have a vertex }\2\6
\&{if} ${}(\\{min\_len}>\\{max\_len}){}$\1\5
\\{panic}(\\{very\_bad\_specs});\C{ what are you trying to do? }\2\6
\&{if} (((\&{unsigned} \&{long})(\\{max\_len}))${}-{}$((\&{unsigned} \&{long})(%
\\{min\_len}))${}\G{}$((\&{unsigned} \&{long}) \T{\^80000000}))\1\5
${}\\{panic}(\\{bad\_specs}+\T{1}){}$;\C{ too much range }\2\6
\X11:Check the distribution parameters\X;\6
\\{gb\_init\_rand}(\\{seed});\6
\X7:Create a graph with \|n vertices and no arcs\X;\6
\X13:Build tables for nonuniform distributions, if needed\X;\6
\&{for} ${}(\\{mm}\K\|m;{}$ \\{mm}; ${}\\{mm}\MM){}$\1\5
\X9:Add a random arc or a random edge\X;\2\6
\4\\{trouble}:\6
\&{if} (\\{gb\_trouble\_code})\5
${}\{{}$\1\6
\\{gb\_recycle}(\\{new\_graph});\6
\\{panic}(\\{alloc\_fault});\C{ oops, we ran out of memory somewhere back there
}\6
\4${}\}{}$\2\6
${}\\{gb\_free}(\\{new\_graph}\MG\\{aux\_data});{}$\6
\&{return} \\{new\_graph};\6
\4${}\}{}$\2\par
\As22\ET24.
\U2.\fi

\M{6}\B\X6:Local variables\X${}\E{}$\6
\&{Graph} ${}{*}\\{new\_graph}{}$;\C{ the graph constructed by \\{random%
\_graph} }\6
\&{long} \\{mm};\C{ the number of arcs or edges we still need to generate }\6
\&{register} \&{long} \|k;\C{ vertex being processed }\par
\A12.
\U5.\fi

\M{7}\B\D$\\{dist\_code}(\|x)$ \5
$(\|x\?\.{"dist"}:\.{"0"}{}$)\par
\Y\B\4\X7:Create a graph with \|n vertices and no arcs\X${}\E{}$\6
$\\{new\_graph}\K\\{gb\_new\_graph}(\|n);{}$\6
\&{if} ${}(\\{new\_graph}\E\NULL){}$\1\5
\\{panic}(\\{no\_room});\C{ out of memory before we're even started }\2\6
\&{for} ${}(\|k\K\T{0};{}$ ${}\|k<\|n;{}$ ${}\|k\PP){}$\5
${}\{{}$\1\6
${}\\{sprintf}(\\{name\_buffer},\39\.{"\%ld"},\39\|k);{}$\6
${}(\\{new\_graph}\MG\\{vertices}+\|k)\MG\\{name}\K\\{gb\_save\_string}(\\{name%
\_buffer});{}$\6
\4${}\}{}$\2\6
${}\\{sprintf}(\\{new\_graph}\MG\\{id},\39\.{"random\_graph(\%lu,\%l}\)\.{u,%
\%d,\%d,\%d,\%s,\%s,\%ld}\)\.{,\%ld,\%ld)"},\3{-1}\39\|n,\39\|m,\39\\{multi}>%
\T{0}\?\T{1}:\\{multi}<\T{0}\?{-}\T{1}:\T{0},\39\\{self}\?\T{1}:\T{0},\39%
\\{directed}\?\T{1}:\T{0},\3{-1}\39\\{dist\_code}(\\{dist\_from}),\39\\{dist%
\_code}(\\{dist\_to}),\39\\{min\_len},\39\\{max\_len},\39\\{seed}){}$;\par
\U5.\fi

\M{8}\B\X8:Private declarations\X${}\E{}$\6
\&{static} \&{char} \\{name\_buffer}[\,]${}\K\.{"9999999999"}{}$;\par
\As14, 17\ETs25.
\U2.\fi

\M{9}\B\D$\\{rand\_len}$ \5
$(\\{min\_len}\E\\{max\_len}\?\\{min\_len}:\\{min\_len}+\\{gb\_unif\_rand}(%
\\{max\_len}-\\{min\_len}){}$)\par
\Y\B\4\X9:Add a random arc or a random edge\X${}\E{}$\6
${}\{{}$\5
\1\&{register} \&{Vertex} ${}{*}\|u,{}$ ${}{*}\|v;{}$\7
\4\\{repeat}:\6
\&{if} (\\{dist\_from})\1\5
\X15:Generate a random vertex \|u according to \\{dist\_from}\X\2\6
\&{else}\1\5
${}\|u\K\\{new\_graph}\MG\\{vertices}+\\{gb\_unif\_rand}(\|n);{}$\2\6
\&{if} (\\{dist\_to})\1\5
\X16:Generate a random vertex \|v according to \\{dist\_to}\X\2\6
\&{else}\1\5
${}\|v\K\\{new\_graph}\MG\\{vertices}+\\{gb\_unif\_rand}(\|n);{}$\2\6
\&{if} ${}(\|u\E\|v\W\R\\{self}){}$\1\5
\&{goto} \\{repeat};\2\6
\&{if} ${}(\\{multi}\Z\T{0}){}$\1\5
\X10:Search for duplicate arcs or edges; \&{goto} \\{repeat} or \\{done} if
found\X;\2\6
\&{if} (\\{directed})\1\5
${}\\{gb\_new\_arc}(\|u,\39\|v,\39\\{rand\_len});{}$\2\6
\&{else}\1\5
${}\\{gb\_new\_edge}(\|u,\39\|v,\39\\{rand\_len});{}$\2\6
\4\\{done}:\5
;\6
\4${}\}{}$\2\par
\U5.\fi

\M{10}When we decrease the length of an existing edge, we use the fact that
its two arcs are adjacent in memory. If $\|u\E\|v$ in this case, we encounter
the first of two mated arcs before seeing the second; hence the mate of
the arc we find is in location $\|a+\T{1}$ when $\|u\Z\|v$, and in location
$\|a-\T{1}$ when $\|u>\|v$.

We must exit to location \\{trouble} if memory has been exhausted;
otherwise there is a danger of an infinite loop, with $\\{dummy\_arc}\MG%
\\{next}\K\\{dummy\_arc}$.

\Y\B\4\X10:Search for duplicate arcs or edges; \&{goto} \\{repeat} or \\{done}
if found\X${}\E{}$\6
\&{if} (\\{gb\_trouble\_code})\1\5
\&{goto} \\{trouble};\2\6
\&{else}\5
${}\{{}$\5
\1\&{register} \&{Arc} ${}{*}\|a;{}$\6
\&{long} \\{len};\C{ length of new arc or edge being combined with previous }\7
\&{for} ${}(\|a\K\|u\MG\\{arcs};{}$ \|a; ${}\|a\K\|a\MG\\{next}){}$\1\6
\&{if} ${}(\|a\MG\\{tip}\E\|v){}$\1\6
\&{if} ${}(\\{multi}\E\T{0}){}$\1\5
\&{goto} \\{repeat};\C{ reject a duplicate arc }\2\6
\&{else}\5
${}\{{}$\C{ $\\{multi}<\T{0}$ }\1\6
${}\\{len}\K\\{rand\_len};{}$\6
\&{if} ${}(\\{len}<\|a\MG\\{len}){}$\5
${}\{{}$\1\6
${}\|a\MG\\{len}\K\\{len};{}$\6
\&{if} ${}(\R\\{directed}){}$\5
${}\{{}$\1\6
\&{if} ${}(\|u\Z\|v){}$\1\5
${}(\|a+\T{1})\MG\\{len}\K\\{len};{}$\2\6
\&{else}\1\5
${}(\|a-\T{1})\MG\\{len}\K\\{len};{}$\2\6
\4${}\}{}$\2\6
\4${}\}{}$\2\6
\&{goto} \\{done};\6
\4${}\}{}$\2\2\2\6
\4${}\}{}$\2\par
\U9.\fi

\N{1}{11}Nonuniform random number generation. The \\{random\_graph} procedure
is
complete except for the parts that handle general distributions \\{dist\_from}
and \\{dist\_to}. Before attempting to generate those distributions, we had
better
check them to make sure that the specifications are well formed;
otherwise disaster might ensue later. This part of the program is easy.

\Y\B\4\X11:Check the distribution parameters\X${}\E{}$\6
${}\{{}$\5
\1\&{register} \&{long} \\{acc};\C{ sum of probabilities }\6
\&{register} \&{long} ${}{*}\|p{}$;\C{ pointer to current probability of
interest }\7
\&{if} (\\{dist\_from})\5
${}\{{}$\1\6
\&{for} ${}(\\{acc}\K\T{0},\,\39\|p\K\\{dist\_from};{}$ ${}\|p<\\{dist\_from}+%
\|n;{}$ ${}\|p\PP){}$\5
${}\{{}$\1\6
\&{if} ${}({*}\|p<\T{0}){}$\1\5
\\{panic}(\\{invalid\_operand});\C{ \\{dist\_from} contains a negative entry }%
\2\6
\&{if} ${}({*}\|p>\T{\^40000000}-\\{acc}){}$\1\5
${}\\{panic}(\\{invalid\_operand}+\T{1}){}$;\C{ probability too high }\2\6
${}\\{acc}\MRL{+{\K}}{*}\|p;{}$\6
\4${}\}{}$\2\6
\&{if} ${}(\\{acc}\I\T{\^40000000}){}$\1\5
${}\\{panic}(\\{invalid\_operand}+\T{2}){}$;\C{ \\{dist\_from} table doesn't
sum to $2^{30}$ }\2\6
\4${}\}{}$\2\6
\&{if} (\\{dist\_to})\5
${}\{{}$\1\6
\&{for} ${}(\\{acc}\K\T{0},\,\39\|p\K\\{dist\_to};{}$ ${}\|p<\\{dist\_to}+%
\|n;{}$ ${}\|p\PP){}$\5
${}\{{}$\1\6
\&{if} ${}({*}\|p<\T{0}){}$\1\5
${}\\{panic}(\\{invalid\_operand}+\T{5}){}$;\C{ \\{dist\_to} contains a
negative entry }\2\6
\&{if} ${}({*}\|p>\T{\^40000000}-\\{acc}){}$\1\5
${}\\{panic}(\\{invalid\_operand}+\T{6}){}$;\C{ probability too high }\2\6
${}\\{acc}\MRL{+{\K}}{*}\|p;{}$\6
\4${}\}{}$\2\6
\&{if} ${}(\\{acc}\I\T{\^40000000}){}$\1\5
${}\\{panic}(\\{invalid\_operand}+\T{7}){}$;\C{ \\{dist\_to} table doesn't sum
to $2^{30}$ }\2\6
\4${}\}{}$\2\6
\4${}\}{}$\2\par
\U5.\fi

\M{12}We generate nonuniform distributions by using Walker's alias
method (see, for example, {\sl Seminumerical Algorithms}, second edition,
exercise 3.4.1--7). Walker's method involves setting up ``magic'' tables
of length \\{nn}, where \\{nn} is the smallest power of~2 that is $\G$ \|n.

\Y\B\F\\{magic\_entry} \5
\\{int}\par
\Y\B\4\X6:Local variables\X${}\mathrel+\E{}$\6
\&{long} \\{nn}${}\K\T{1}{}$;\C{ this will be increased to $2^{\lceil\mskip1mu%
\lg n\rceil}$ }\6
\&{long} \\{kk}${}\K\T{31}{}$;\C{ this will be decreased to $31-\lceil\mskip1mu%
\lg n\rceil$ }\6
\&{magic\_entry} ${}{*}\\{from\_table},{}$ ${}{*}\\{to\_table}{}$;\C{ alias
tables }\par
\fi

\M{13}\B\X13:Build tables for nonuniform distributions, if needed\X${}\E{}$\6
${}\{{}$\1\6
\&{if} (\\{dist\_from})\5
${}\{{}$\1\6
\&{while} ${}(\\{nn}<\|n){}$\1\5
${}\\{nn}\MRL{+{\K}}\\{nn},\39\\{kk}\MM;{}$\2\6
${}\\{from\_table}\K\\{walker}(\|n,\39\\{nn},\39\\{dist\_from},\39\\{new%
\_graph});{}$\6
\4${}\}{}$\2\6
\&{if} (\\{dist\_to})\5
${}\{{}$\1\6
\&{while} ${}(\\{nn}<\|n){}$\1\5
${}\\{nn}\MRL{+{\K}}\\{nn},\39\\{kk}\MM;{}$\2\6
${}\\{to\_table}\K\\{walker}(\|n,\39\\{nn},\39\\{dist\_to},\39\\{new%
\_graph});{}$\6
\4${}\}{}$\2\6
\&{if} (\\{gb\_trouble\_code})\5
${}\{{}$\1\6
\\{gb\_recycle}(\\{new\_graph});\6
\\{panic}(\\{alloc\_fault});\C{ oops, we ran out of memory somewhere back there
}\6
\4${}\}{}$\2\6
\4${}\}{}$\2\par
\U5.\fi

\M{14}\B\X8:Private declarations\X${}\mathrel+\E{}$\6
\&{typedef} \&{struct} ${}\{{}$\1\6
\&{long} \\{prob};\C{ a probability, multiplied by $2^{31}$ and translated }\6
\&{long} \\{inx};\C{ index that might be selected }\2\6
${}\}{}$ \&{magic\_entry};\par
\fi

\M{15}Once the magic tables have been set up, we can generate
nonuniform vertices by using the following code:

\Y\B\4\X15:Generate a random vertex \|u according to \\{dist\_from}\X${}\E{}$\6
${}\{{}$\5
\1\&{register} \&{magic\_entry} ${}{*}\\{magic};{}$\6
\&{register} \&{long} \\{uu}${}\K\\{gb\_next\_rand}(\,){}$;\C{ uniform random
number }\7
${}\|k\K\\{uu}\GG\\{kk};{}$\6
${}\\{magic}\K\\{from\_table}+\|k;{}$\6
\&{if} ${}(\\{uu}\Z\\{magic}\MG\\{prob}){}$\1\5
${}\|u\K\\{new\_graph}\MG\\{vertices}+\|k;{}$\2\6
\&{else}\1\5
${}\|u\K\\{new\_graph}\MG\\{vertices}+\\{magic}\MG\\{inx};{}$\2\6
\4${}\}{}$\2\par
\U9.\fi

\M{16}\B\X16:Generate a random vertex \|v according to \\{dist\_to}\X${}\E{}$\6
${}\{{}$\5
\1\&{register} \&{magic\_entry} ${}{*}\\{magic};{}$\6
\&{register} \&{long} \\{uu}${}\K\\{gb\_next\_rand}(\,){}$;\C{ uniform random
number }\7
${}\|k\K\\{uu}\GG\\{kk};{}$\6
${}\\{magic}\K\\{to\_table}+\|k;{}$\6
\&{if} ${}(\\{uu}\Z\\{magic}\MG\\{prob}){}$\1\5
${}\|v\K\\{new\_graph}\MG\\{vertices}+\|k;{}$\2\6
\&{else}\1\5
${}\|v\K\\{new\_graph}\MG\\{vertices}+\\{magic}\MG\\{inx};{}$\2\6
\4${}\}{}$\2\par
\U9.\fi

\M{17}So all we have to do is set up those magic tables. If \\{uu} is a uniform
random integer between 0 and $2^{31}-1$, the index $\|k\K\\{uu}\GG\\{kk}$ is a
uniform random integer between 0
and $\\{nn}-\T{1}$, because of the relation between \\{nn} and \\{kk}. Once \|k
is
computed, the code above selects vertex~\|k with probability
$(\|p+\T{1}-(\|k\LL\\{kk}))$/$2^{31}$, where $\|p\K\\{magic}\MG\\{prob}$ and %
\\{magic} is the $k$th
element of the magic table; otherwise the code selects
vertex $\\{magic}\MG\\{inx}$. The trick is to set things up so that each vertex
is selected with the proper overall probability.

Let's imagine that the given distribution vector has length \\{nn},
instead of~\|n, by extending it if necessary with zeroes. Then the
average entry among these \\{nn} integers is exactly $t=2^{30}/\\{nn}$.
If some entry, say entry~\|i, exceeds \|t, there must be another entry
that's less than \|t, say entry~\|j. We can set the $j$th entry
of the magic table so that its \\{prob} field selects vertex~$j$ with the
correct probability, and so that its \\{inx} field equals~\|i. Then
we are selecting vertex~\|i with a certain residual probability; so we
subtract that residual from \|i's present probability, and repeat the
process with vertex~\|j eliminated. The average of the remaining entries
is still~\|t, so we can repeat this procedure until all remaining entries
are exactly equal to~\|t. The rest is easy.

During the calculation, we maintain two linked lists of
$(\\{prob},\\{inx})$ pairs. The \\{hi} list contains entries with $\\{prob}>%
\|t$,
and the \\{lo} list contains the rest. During this part of the computation
we call these list elements `nodes', and we use the field names
\\{key} and~\|j instead of \\{prob} and \\{inx}.

\Y\B\4\X8:Private declarations\X${}\mathrel+\E{}$\6
\&{typedef} \&{struct} \&{node\_struct} ${}\{{}$\1\6
\&{long} \\{key};\C{ a numeric quantity }\6
\&{struct} \&{node\_struct} ${}{*}\\{link}{}$;\C{ the next node on the list }\6
\&{long} \|j;\C{ a vertex number to be selected with probability $%
\\{key}/2^{30}$ }\2\6
${}\}{}$ \&{node};\6
\&{static} \&{Area} \\{temp\_nodes};\C{ nodes will be allocated in this area }\6
\&{static} \&{node} ${}{*}\\{base\_node}{}$;\C{ beginning of a block of nodes }%
\par
\fi

\M{18}\B\X18:Internal functions\X${}\E{}$\6
\&{static} \&{magic\_entry} ${}{*}\\{walker}(\|n,\39\\{nn},\39\\{dist},\39%
\|g){}$\1\1\6
\&{long} \|n;\C{ length of \\{dist} vector }\6
\&{long} \\{nn};\C{ $2^{\lceil\mskip1mu\lg n\rceil}$ }\6
\&{register} \&{long} ${}{*}\\{dist}{}$;\C{ start of distribution table, which
sums to $2^{30}$ }\6
\&{Graph} ${}{*}\|g{}$;\C{ tables will be allocated for this graph's vertices }%
\2\2\6
${}\{{}$\5
\1\&{magic\_entry} ${}{*}\\{table}{}$;\C{ this will be the magic table we
compute }\6
\&{long} \|t;\C{ average \\{key} value }\6
\&{node} ${}{*}\\{hi}\K\NULL,{}$ ${}{*}\\{lo}\K\NULL{}$;\C{ nodes not yet
included in magic table }\6
\&{register} \&{node} ${}{*}\|p,{}$ ${}{*}\|q{}$;\C{ pointer variables for list
manipulation }\7
${}\\{base\_node}\K\\{gb\_typed\_alloc}(\\{nn},\39\&{node},\39\\{temp%
\_nodes});{}$\6
${}\\{table}\K\\{gb\_typed\_alloc}(\\{nn},\39\&{magic\_entry},\39\|g\MG\\{aux%
\_data});{}$\6
\&{if} ${}(\R\\{gb\_trouble\_code}){}$\5
${}\{{}$\1\6
\X19:Initialize the \\{hi} and \\{lo} lists\X;\6
\&{while} (\\{hi})\1\5
\X20:Remove a \\{lo} element and match it with a \\{hi} element; deduct the
residual probability from that \\{hi}~element\X;\2\6
\&{while} (\\{lo})\1\5
\X21:Remove a \\{lo} element of \\{key} value \|t\X;\2\6
\4${}\}{}$\2\6
\\{gb\_free}(\\{temp\_nodes});\6
\&{return} \\{table};\C{ if \\{gb\_trouble\_code} is nonzero, the table is
empty }\6
\4${}\}{}$\2\par
\U2.\fi

\M{19}\B\X19:Initialize the \\{hi} and \\{lo} lists\X${}\E{}$\6
$\|t\K\T{\^40000000}/\\{nn}{}$;\C{ this division is exact }\6
${}\|p\K\\{base\_node};{}$\6
\&{while} ${}(\\{nn}>\|n){}$\5
${}\{{}$\1\6
${}\|p\MG\\{key}\K\T{0};{}$\6
${}\|p\MG\\{link}\K\\{lo};{}$\6
${}\|p\MG\|j\K\MM\\{nn};{}$\6
${}\\{lo}\K\|p\PP;{}$\6
\4${}\}{}$\2\6
\&{for} ${}(\\{dist}\K\\{dist}+\|n-\T{1};{}$ ${}\|n>\T{0};{}$ ${}\\{dist}\MM,%
\39\|p\PP){}$\5
${}\{{}$\1\6
${}\|p\MG\\{key}\K{*}\\{dist};{}$\6
${}\|p\MG\|j\K\MM\|n;{}$\6
\&{if} ${}({*}\\{dist}>\|t){}$\1\5
${}\|p\MG\\{link}\K\\{hi},\,\39\\{hi}\K\|p;{}$\2\6
\&{else}\1\5
${}\|p\MG\\{link}\K\\{lo},\,\39\\{lo}\K\|p;{}$\2\6
\4${}\}{}$\2\par
\U18.\fi

\M{20}When we change the scale factor from $2^{30}$ to $2^{31}$, we need to
be careful lest integer overflow occur. The introduction of register \|x into
this code removes the risk.

\Y\B\4\X20:Remove a \\{lo} element and match it with a \\{hi} element; deduct
the residual probability from that \\{hi}~element\X${}\E{}$\6
${}\{{}$\5
\1\&{register} \&{magic\_entry} ${}{*}\|r;{}$\6
\&{register} \&{long} \|x;\7
${}\|p\K\\{hi},\,\39\\{hi}\K\|p\MG\\{link};{}$\6
${}\|q\K\\{lo},\,\39\\{lo}\K\|q\MG\\{link};{}$\6
${}\|r\K\\{table}+\|q\MG\|j;{}$\6
${}\|x\K\|t*\|q\MG\|j+\|q\MG\\{key}-\T{1};{}$\6
${}\|r\MG\\{prob}\K\|x+\|x+\T{1};{}$\6
${}\|r\MG\\{inx}\K\|p\MG\|j{}$;\C{ we have just given $\|q\MG\\{key}$ units of
probability to vertex $\|q\MG\|j$,      and $\|t-\|q\MG\\{key}$ units to vertex
$\|p\MG\|j$ }\6
\&{if} ${}((\|p\MG\\{key}\MRL{-{\K}}\|t-\|q\MG\\{key})>\|t){}$\1\5
${}\|p\MG\\{link}\K\\{hi},\,\39\\{hi}\K\|p;{}$\2\6
\&{else}\1\5
${}\|p\MG\\{link}\K\\{lo},\,\39\\{lo}\K\|p;{}$\2\6
\4${}\}{}$\2\par
\U18.\fi

\M{21}When all remaining entries have the average probability, the
\\{inx} component need not be set, because it will never be used.

\Y\B\4\X21:Remove a \\{lo} element of \\{key} value \|t\X${}\E{}$\6
${}\{{}$\5
\1\&{register} \&{magic\_entry} ${}{*}\|r;{}$\6
\&{register} \&{long} \|x;\7
${}\|q\K\\{lo},\39\\{lo}\K\|q\MG\\{link};{}$\6
${}\|r\K\\{table}+\|q\MG\|j;{}$\6
${}\|x\K\|t*\|q\MG\|j+\|t-\T{1};{}$\6
${}\|r\MG\\{prob}\K\|x+\|x+\T{1}{}$;\C{ that's \|t units of probability for
vertex $\|q\MG\|j$ }\6
\4${}\}{}$\2\par
\U18.\fi

\N{1}{22}Random bipartite graphs. The procedure call
$$\hbox{$\\{random\_bigraph}(\\{n1},\\{n2},\|m,\\{multi},\\{dist1},\\{dist2},%
\\{min\_len},\\{max\_len},\\{seed})$}$$
is designed to produce a pseudo-random bipartite graph
with \\{n1} vertices in one part and \\{n2} in the other, having \|m edges.
The remaining parameters \\{multi}, \\{dist1}, \\{dist2}, \\{min\_len}, \\{max%
\_len},
and \\{seed} have the same meaning as the analogous parameters of \\{random%
\_graph}.

In fact, \\{random\_bigraph} does its work by reducing its parameters
to a special case of \\{random\_graph}. Almost all that needs to be done is
to pad \\{dist1} with \\{n2} trailing zeroes and \\{dist2} with \\{n1} leading
zeroes. The only slightly tricky part occurs when \\{dist1} and/or \\{dist2}
are
null, since non-null distribution vectors summing exactly to $2^{30}$ must then
be fabricated.

\Y\B\4\X5:External functions\X${}\mathrel+\E{}$\6
\&{Graph} ${}{*}\\{random\_bigraph}(\\{n1},\39\\{n2},\39\|m,\39\\{multi},\39%
\\{dist1},\39\\{dist2},\39\\{min\_len},\39\\{max\_len},\39\\{seed}){}$\1\1\6
\&{unsigned} \&{long} \\{n1}${},{}$ \\{n2};\C{ number of vertices desired in
each part }\6
\&{unsigned} \&{long} \|m;\C{ number of edges desired }\6
\&{long} \\{multi};\C{ allow duplicate edges? }\6
\&{long} ${}{*}\\{dist1},{}$ ${}{*}\\{dist2}{}$;\C{ distribution of edge
endpoints }\6
\&{long} \\{min\_len}${},{}$ \\{max\_len};\C{ bounds on random lengths }\6
\&{long} \\{seed};\C{ random number seed }\2\2\6
${}\{{}$\5
\1\&{unsigned} \&{long} \|n${}\K\\{n1}+\\{n2}{}$;\C{ total number of vertices }%
\6
\&{Area} \\{new\_dists};\6
\&{long} ${}{*}\\{dist\_from},{}$ ${}{*}\\{dist\_to};{}$\6
\&{Graph} ${}{*}\\{new\_graph};{}$\7
\\{init\_area}(\\{new\_dists});\6
\&{if} ${}(\\{n1}\E\T{0}\V\\{n2}\E\T{0}){}$\1\5
\\{panic}(\\{bad\_specs});\C{ illegal options }\2\6
\&{if} ${}(\\{min\_len}>\\{max\_len}){}$\1\5
\\{panic}(\\{very\_bad\_specs});\C{ what are you trying to do? }\2\6
\&{if} (((\&{unsigned} \&{long})(\\{max\_len}))${}-{}$((\&{unsigned} \&{long})(%
\\{min\_len}))${}\G{}$((\&{unsigned} \&{long}) \T{\^80000000}))\1\5
${}\\{panic}(\\{bad\_specs}+\T{1}){}$;\C{ too much range }\2\6
${}\\{dist\_from}\K\\{gb\_typed\_alloc}(\|n,\39\&{long},\39\\{new\_dists});{}$\6
${}\\{dist\_to}\K\\{gb\_typed\_alloc}(\|n,\39\&{long},\39\\{new\_dists});{}$\6
\&{if} (\\{gb\_trouble\_code})\5
${}\{{}$\1\6
\\{gb\_free}(\\{new\_dists});\6
${}\\{panic}(\\{no\_room}+\T{2}){}$;\C{ no room for auxiliary distribution
tables }\6
\4${}\}{}$\2\6
\X23:Compute the entries of \\{dist\_from} and \\{dist\_to}\X;\6
${}\\{new\_graph}\K\\{random\_graph}(\|n,\39\|m,\39\\{multi},\39\T{0\$L},\39%
\T{0\$L},\39\\{dist\_from},\39\\{dist\_to},\39\\{min\_len},\39\\{max\_len},\39%
\\{seed});{}$\6
${}\\{sprintf}(\\{new\_graph}\MG\\{id},\39\.{"random\_bigraph(\%lu,}\)\.{\%lu,%
\%lu,\%d,\%s,\%s,\%ld}\)\.{,\%ld,\%ld)"},\3{-1}\39\\{n1},\39\\{n2},\39\|m,\39%
\\{multi}>\T{0}\?\T{1}:\\{multi}<\T{0}\?{-}\T{1}:\T{0},\39\\{dist\_code}(%
\\{dist1}),\39\\{dist\_code}(\\{dist2}),\3{-1}\39\\{min\_len},\39\\{max\_len},%
\39\\{seed});{}$\6
${}\\{mark\_bipartite}(\\{new\_graph},\39\\{n1});{}$\6
\\{gb\_free}(\\{new\_dists});\6
\&{return} \\{new\_graph};\6
\4${}\}{}$\2\par
\fi

\M{23}The relevant identity we need here is the replicative law for the
floor function:
$$\left\lfloor x\over n\right\rfloor+\left\lfloor x+1\over n\right\rfloor
+ \cdots + \left\lfloor x+n-1\over n\right\rfloor = \lfloor x\rfloor\,.$$

\Y\B\4\X23:Compute the entries of \\{dist\_from} and \\{dist\_to}\X${}\E{}$\6
${}\{{}$\5
\1\&{register} \&{long} ${}{*}\|p,{}$ ${}{*}\|q{}$;\C{ traversers of the dists
}\6
\&{register} \&{long} \|k;\C{ vertex count }\7
${}\|p\K\\{dist1};{}$\6
${}\|q\K\\{dist\_from};{}$\6
\&{if} (\|p)\1\6
\&{while} ${}(\|p<\\{dist1}+\\{n1}){}$\1\5
${}{*}\|q\PP\K{*}\|p\PP;{}$\2\2\6
\&{else}\1\6
\&{for} ${}(\|k\K\T{0};{}$ ${}\|k<\\{n1};{}$ ${}\|k\PP){}$\1\5
${}{*}\|q\PP\K(\T{\^40000000}+\|k)/\\{n1};{}$\2\2\6
${}\|p\K\\{dist2};{}$\6
${}\|q\K\\{dist\_to}+\\{n1};{}$\6
\&{if} (\|p)\1\6
\&{while} ${}(\|p<\\{dist2}+\\{n2}){}$\1\5
${}{*}\|q\PP\K{*}\|p\PP;{}$\2\2\6
\&{else}\1\6
\&{for} ${}(\|k\K\T{0};{}$ ${}\|k<\\{n2};{}$ ${}\|k\PP){}$\1\5
${}{*}\|q\PP\K(\T{\^40000000}+\|k)/\\{n2};{}$\2\2\6
\4${}\}{}$\2\par
\U22.\fi

\N{1}{24}Random lengths. The subroutine call
$$\hbox{$\\{random\_lengths}(\|g,\\{directed},\\{min\_len},\\{max\_len},%
\\{dist},\\{seed})$}$$
takes an existing graph and assigns new lengths to
each of its arcs. If $\\{dist}\K\NULL$, the lengths will be uniformly
distributed
between \\{min\_len} and \\{max\_len} inclusive; otherwise \\{dist}
should be a probability distribution vector of length $\\{max\_len}-\\{min%
\_len}+\T{1}$,
like those in \\{random\_graph}.

If $\\{directed}\K\T{0}$, pairs of arcs $u\to v$ and $v\to u$ will be regarded
as
a single edge, both arcs receiving the same length.

The procedure returns a nonzero value if something goes wrong; in that
case, graph \|g will not have been changed.

Alias tables for generating nonuniform random lengths will survive
in $\|g\MG\\{aux\_data}$.

\Y\B\4\X5:External functions\X${}\mathrel+\E{}$\6
\&{long} ${}\\{random\_lengths}(\|g,\39\\{directed},\39\\{min\_len},\39\\{max%
\_len},\39\\{dist},\39\\{seed}){}$\1\1\6
\&{Graph} ${}{*}\|g{}$;\C{ graph whose lengths will be randomized }\6
\&{long} \\{directed};\C{ is it directed? }\6
\&{long} \\{min\_len}${},{}$ \\{max\_len};\C{ bounds on random lengths }\6
\&{long} ${}{*}\\{dist}{}$;\C{ distribution of lengths }\6
\&{long} \\{seed};\C{ random number seed }\2\2\6
${}\{{}$\5
\1\&{register} \&{Vertex} ${}{*}\|u,{}$ ${}{*}\|v{}$;\C{ current vertices of
interest }\6
\&{register} \&{Arc} ${}{*}\|a{}$;\C{ current arc of interest }\6
\&{long} \\{nn}${}\K\T{1},{}$ \\{kk}${}\K\T{31}{}$;\C{ variables for nonuniform
generation }\6
\&{magic\_entry} ${}{*}\\{dist\_table}{}$;\C{ alias table for nonuniform
generation }\7
\&{if} ${}(\|g\E\NULL){}$\1\5
\&{return} \\{missing\_operand};\C{ where is \|g? }\2\6
\\{gb\_init\_rand}(\\{seed});\6
\&{if} ${}(\\{min\_len}>\\{max\_len}){}$\1\5
\&{return} \\{very\_bad\_specs};\C{ what are you trying to do? }\2\6
\&{if} (((\&{unsigned} \&{long})(\\{max\_len}))${}-{}$((\&{unsigned} \&{long})(%
\\{min\_len}))${}\G{}$((\&{unsigned} \&{long}) \T{\^80000000}))\1\5
\&{return} \\{bad\_specs};\C{ too much range }\2\6
\X26:Check \\{dist} for validity, and set up the \\{dist\_table}\X;\6
${}\\{sprintf}(\\{buffer},\39\.{",\%d,\%ld,\%ld,\%s,\%ld)}\)\.{"},\39%
\\{directed}\?\T{1}:\T{0},\3{-1}\39\\{min\_len},\39\\{max\_len},\39\\{dist%
\_code}(\\{dist}),\39\\{seed});{}$\6
${}\\{make\_compound\_id}(\|g,\39\.{"random\_lengths("},\39\|g,\39%
\\{buffer});{}$\6
\X27:Run through all arcs and assign new lengths\X;\6
\&{return} \T{0};\6
\4${}\}{}$\2\par
\fi

\M{25}\B\X8:Private declarations\X${}\mathrel+\E{}$\6
\&{static} \&{char} \\{buffer}[\,]${}\K\.{"1,-1000000001,-1000}\)%
\.{000000,dist,10000000}\)\.{00)"}{}$;\par
\fi

\M{26}\B\X26:Check \\{dist} for validity, and set up the \\{dist\_table}\X${}%
\E{}$\6
\&{if} (\\{dist})\5
${}\{{}$\5
\1\&{register} \&{long} \\{acc};\C{ sum of probabilities }\6
\&{register} \&{long} ${}{*}\|p{}$;\C{ pointer to current probability of
interest }\6
\&{register} \&{long} \|n${}\K\\{max\_len}-\\{min\_len}+\T{1};{}$\7
\&{for} ${}(\\{acc}\K\T{0},\39\|p\K\\{dist};{}$ ${}\|p<\\{dist}+\|n;{}$ ${}\|p%
\PP){}$\5
${}\{{}$\1\6
\&{if} ${}({*}\|p<\T{0}){}$\1\5
\&{return} ${}{-}\T{1}{}$;\C{ negative probability }\2\6
\&{if} ${}({*}\|p>\T{\^40000000}-\\{acc}){}$\1\5
\&{return} \T{1};\C{ probability too high }\2\6
${}\\{acc}\MRL{+{\K}}{*}\|p;{}$\6
\4${}\}{}$\2\6
\&{if} ${}(\\{acc}\I\T{\^40000000}){}$\1\5
\&{return} \T{2};\C{ probabilities don't sum to 1 }\2\6
\&{while} ${}(\\{nn}<\|n){}$\1\5
${}\\{nn}\MRL{+{\K}}\\{nn},\39\\{kk}\MM;{}$\2\6
${}\\{dist\_table}\K\\{walker}(\|n,\39\\{nn},\39\\{dist},\39\|g);{}$\6
\&{if} (\\{gb\_trouble\_code})\5
${}\{{}$\1\6
${}\\{gb\_trouble\_code}\K\T{0};{}$\6
\&{return} \\{alloc\_fault};\C{ not enough room to generate the magic tables }\6
\4${}\}{}$\2\6
\4${}\}{}$\2\par
\U24.\fi

\M{27}\B\X27:Run through all arcs and assign new lengths\X${}\E{}$\6
\&{for} ${}(\|u\K\|g\MG\\{vertices};{}$ ${}\|u<\|g\MG\\{vertices}+\|g\MG\|n;{}$
${}\|u\PP){}$\1\6
\&{for} ${}(\|a\K\|u\MG\\{arcs};{}$ \|a; ${}\|a\K\|a\MG\\{next}){}$\5
${}\{{}$\1\6
${}\|v\K\|a\MG\\{tip};{}$\6
\&{if} ${}(\\{directed}\E\T{0}\W\|u>\|v){}$\1\5
${}\|a\MG\\{len}\K(\|a-\T{1})\MG\\{len};{}$\2\6
\&{else}\5
${}\{{}$\5
\1\&{register} \&{long} \\{len};\C{ a random length }\7
\&{if} ${}(\\{dist}\E\T{0}){}$\1\5
${}\\{len}\K\\{rand\_len};{}$\2\6
\&{else}\5
${}\{{}$\5
\1\&{long} \\{uu}${}\K\\{gb\_next\_rand}(\,);{}$\6
\&{long} \|k${}\K\\{uu}\GG\\{kk};{}$\6
\&{magic\_entry} ${}{*}\\{magic}\K\\{dist\_table}+\|k;{}$\7
\&{if} ${}(\\{uu}\Z\\{magic}\MG\\{prob}){}$\1\5
${}\\{len}\K\\{min\_len}+\|k;{}$\2\6
\&{else}\1\5
${}\\{len}\K\\{min\_len}+\\{magic}\MG\\{inx};{}$\2\6
\4${}\}{}$\2\6
${}\|a\MG\\{len}\K\\{len};{}$\6
\&{if} ${}(\\{directed}\E\T{0}\W\|u\E\|v\W\|a\MG\\{next}\E\|a+\T{1}){}$\1\5
${}(\PP\|a)\MG\\{len}\K\\{len};{}$\2\6
\4${}\}{}$\2\6
\4${}\}{}$\2\2\par
\U24.\fi

\N{1}{28}Index. Here is a list that shows where the identifiers of this program
are
defined and used.
\fi


\inx
\fin
\con
