Random graphs with fixed numbers of neighbours

November 24, 2010

(This article was first published on Xi'an's Og » R, and kindly contributed to R-bloggers)

In connection with Le Monde puzzle #46, I eventually managed to write an R program that generates graphs with a given number n of nodes and a given number k of edges leaving each of those nodes. (My early attempt was simply too myopic to achieve any level of success when n was larger than 10!) Here is the core of the R code:

A=42 #number of nodes
L=13 #number of edges

if ((A*L)%%2==1){
 print("impossible graph")
 diag(con)=A      #eliminate self-connection

 while (min(suma)ApL-1)) vali=NULL

and it uses a sort of annealed backward step to avoid simulating a complete new collection of neighbours when reaching culs-de-sac….

#removes a random number of links among the nodes with L links

while (max(apply(con,1,sum))==ApL){

 if (sum(apply(con,1,sum)==ApL)==1){

There is nothing fancy or optimised about this code so I figure there are much better versions to be found elsewhere…

Ps-As noticed before, sample does not work on a set of length one, which is a bug in my opinion…. Instead, sample(4.5,1) returns a random permutation of (1,2,3,4).

> sample(4.5)
[1] 4 3 1 2

Filed under: R, Statistics Tagged: edges, graphs, Le Monde, nodes, simulation

To leave a comment for the author, please follow the link and comment on their blog: Xi'an's Og » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Tags: , , , , , ,

Comments are closed.


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)