简体   繁体   中英

Adding random edges in a graph generated using BOOST graphical library

I would like to add random edges in my graph, which is as follow:

#include <iostream>
#include <utility>                   // for std::pair
#include <algorithm> 
#include <boost/graph/adjacency_list.hpp>
#include "boost/graph/topological_sort.hpp"
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/graphviz.hpp>

int main()
{
    using namespace std;
    using namespace boost;

    typedef adjacency_list< listS, vecS, undirectedS > undigraph;

    int const N = read_int_from_user("Number of vertices: ");   

    undigraph g(N);

    // add some edges,             // #1
    for (int i = 0; i != N; ++i)
    {
        for (int j = 0; j != N; ++j)
        {
            add_edge(i, j, g);
        }
    }
    write_graphviz(cout, g);
}

The lines following #1 do that.

But as you can see, there exists 8 edges from each vertex but I Would like to have only 4 to the max and would like to connect all the vertices in a random way and most importantly there can be only 4 valencies from each vertex. How can I achieve that?

EDIT: I said "ordered pair" when I meant "unordered pair"! Hope the rephrasing is clearer now.

What you need to do is sample without replacement from the set of all unordered pairs of nonnegative integers that are < N. Since it's much easier for a computer to represent an ordered pair than an unordered pair, the usual way to produce this set is to produce all ordered pairs in which the first element is less than the second:

vector<pair<int, int> > pairs;

for (int i = 0; i < N; ++i) {
    for (int j = i + 1; j < N; ++j) {
        pairs.push_back(make_pair(i, j));
    }
}

So eg if N = 4, the set of possible edges to consider is:

0, 1
0, 2
0, 3
1, 2
1, 3
2, 3

A nice way to sample from this set once you have it is to use reservoir sampling .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM